lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | agpl-3.0 | 3057d1fcdfa60127ba44f3196ddc3fad1607ed60 | 0 | aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,aihua/opennms,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,aihua/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,roskens/opennms-pre-github | /*
* This file is part of the OpenNMS(R) Application.
*
* OpenNMS(R) is Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved.
* OpenNMS(R) is a derivative work, containing both original code, included code and modified
* code that was published under the GNU General Public License. Copyrights for modified
* and included code are below.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* Modifications:
*
* Created: March 30th, 2010 [email protected]
*
* Copyright (C) 2010 The OpenNMS Group, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information contact:
* OpenNMS Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*/
package org.opennms.reporting.jasperreports.svclayer;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.xml.JRPrintXmlLoader;
import org.apache.log4j.Category;
import org.opennms.api.reporting.ReportException;
import org.opennms.api.reporting.ReportFormat;
import org.opennms.api.reporting.ReportService;
import org.opennms.api.reporting.parameter.ReportParameters;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.config.DataSourceFactory;
import org.opennms.netmgt.dao.JasperReportConfigDao;
public class JasperReportService implements ReportService {
private static final String LOG4J_CATEGORY = "OpenNMS.Report";
private JasperReportConfigDao m_jasperReportConfigDao;
private final Category log;
public JasperReportService() {
String oldPrefix = ThreadCategory.getPrefix();
ThreadCategory.setPrefix(LOG4J_CATEGORY);
log = ThreadCategory.getInstance(JasperReportService.class);
ThreadCategory.setPrefix(oldPrefix);
}
public List<ReportFormat> getFormats(String reportId) {
List<ReportFormat> formats = new ArrayList<ReportFormat>();
formats.add(ReportFormat.PDF);
return formats;
}
public ReportParameters getParameters(String ReportId) {
return new ReportParameters();
}
public void render(String ReportId, String location, ReportFormat format,
OutputStream outputStream) throws ReportException {
try {
JasperPrint jasperPrint = JRPrintXmlLoader.load(location);
switch (format) {
case PDF:
log.debug("rendering as PDF");
JasperExportManager.exportReportToPdfStream(jasperPrint,
outputStream);
break;
default:
log.debug("rendering as PDF as no valid format found");
JasperExportManager.exportReportToPdfStream(jasperPrint,
outputStream);
}
} catch (JRException e) {
log.error("unable to render report", e);
throw new ReportException("unable to render report", e);
}
}
public String run(HashMap<String, Object> reportParms, String reportId)
throws ReportException {
String baseDir = System.getProperty("opennms.report.dir");
JasperReport jasperReport = null;
JasperPrint jasperPrint = null;
String outputFileName = null;
String sourceFileName = m_jasperReportConfigDao.getTemplateLocation(reportId);
if (sourceFileName != null) {
try {
jasperReport = JasperCompileManager.compileReport(System.getProperty("opennms.home")
+ "/etc/report-templates/" + sourceFileName);
} catch (JRException e) {
log.error("unable to compile jasper report", e);
throw new ReportException("unable to compile jasperReport", e);
}
outputFileName = new String(baseDir + "/"
+ jasperReport.getName() + ".jrpxml");
log.debug("jrpcml output file: " + outputFileName);
if (m_jasperReportConfigDao.getEngine(reportId).equals("jdbc")) {
Connection connection;
try {
connection = DataSourceFactory.getDataSource().getConnection();
jasperPrint = JasperFillManager.fillReport(jasperReport,
reportParms,
connection);
JRXmlExporter exporter = new JRXmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
exporter.setParameter(
JRExporterParameter.OUTPUT_FILE_NAME,
outputFileName);
exporter.exportReport();
connection.close();
} catch (SQLException e) {
log.error("sql exception getting or closing datasource ",
e);
throw new ReportException(
"sql exception getting or closing datasource",
e);
} catch (JRException e) {
log.error("jasper report exception ", e);
throw new ReportException(
"unable to run emptyDataSource jasperReport",
e);
}
} else if (m_jasperReportConfigDao.getEngine(reportId).equals(
"null")) {
try {
jasperPrint = JasperFillManager.fillReport(
jasperReport,
reportParms,
new JREmptyDataSource());
JRXmlExporter exporter = new JRXmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
exporter.setParameter(
JRExporterParameter.OUTPUT_FILE_NAME,
outputFileName);
exporter.exportReport();
} catch (JRException e) {
log.error("jasper report exception ", e);
throw new ReportException(
"unable to run emptyDataSource jasperReport",
e);
}
} else {
throw new ReportException(
"no suitable datasource configured for reportId: "
+ reportId);
}
}
return outputFileName;
}
public void runAndRender(HashMap<String, Object> reportParms,
String reportId, ReportFormat format, OutputStream outputStream)
throws ReportException {
JasperReport jasperReport = null;
JasperPrint jasperPrint = null;
String sourceFileName = m_jasperReportConfigDao.getTemplateLocation(reportId);
if (sourceFileName != null) {
try {
jasperReport = JasperCompileManager.compileReport(System.getProperty("opennms.home")
+ "/etc/report-templates/" + sourceFileName);
} catch (JRException e) {
log.error("unable to compile jasper report", e);
throw new ReportException("unable to compile jasperReport", e);
}
if (m_jasperReportConfigDao.getEngine(reportId).equals("jdbc")) {
Connection connection;
try {
connection = DataSourceFactory.getDataSource().getConnection();
jasperPrint = JasperFillManager.fillReport(jasperReport,
reportParms,
connection);
JasperExportManager.exportReportToPdfStream(jasperPrint,
outputStream);
connection.close();
} catch (SQLException e) {
log.error("sql exception getting or closing datasource ",
e);
throw new ReportException(
"sql exception getting or closing datasource",
e);
} catch (JRException e) {
log.error("jasper report exception ", e);
throw new ReportException(
"unable to run or render jdbc jasperReport",
e);
}
} else if (m_jasperReportConfigDao.getEngine(reportId).equals(
"null")) {
try {
jasperPrint = JasperFillManager.fillReport(
jasperReport,
reportParms,
new JREmptyDataSource());
JasperExportManager.exportReportToPdfStream(jasperPrint,
outputStream);
} catch (JRException e) {
log.error("jasper report exception ", e);
throw new ReportException(
"unable to run or render emptyDataSource jasperReport",
e);
}
}
}
}
public boolean validate(HashMap<String, Object> reportParms,
String reportId) {
// returns true until we can take parameters
return true;
}
public void setConfigDao(JasperReportConfigDao jasperReportConfigDao) {
m_jasperReportConfigDao = jasperReportConfigDao;
}
}
| features/reporting/jasper-reports/src/main/java/org/opennms/reporting/jasperreports/svclayer/JasperReportService.java | /*
* This file is part of the OpenNMS(R) Application.
*
* OpenNMS(R) is Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved.
* OpenNMS(R) is a derivative work, containing both original code, included code and modified
* code that was published under the GNU General Public License. Copyrights for modified
* and included code are below.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* Modifications:
*
* Created: March 30th, 2010 [email protected]
*
* Copyright (C) 2010 The OpenNMS Group, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information contact:
* OpenNMS Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*/
package org.opennms.reporting.jasperreports.svclayer;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.xml.JRPrintXmlLoader;
import org.apache.log4j.Category;
import org.opennms.api.reporting.ReportException;
import org.opennms.api.reporting.ReportFormat;
import org.opennms.api.reporting.ReportService;
import org.opennms.api.reporting.parameter.ReportParameters;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.config.DataSourceFactory;
import org.opennms.netmgt.dao.JasperReportConfigDao;
public class JasperReportService implements ReportService {
private static final String LOG4J_CATEGORY = "OpenNMS.Report";
private JasperReportConfigDao m_jasperReportConfigDao;
private Category log;
public JasperReportService() {
ThreadCategory.setPrefix(LOG4J_CATEGORY);
log = ThreadCategory.getInstance(JasperReportService.class);
}
public List<ReportFormat> getFormats(String reportId) {
List<ReportFormat> formats = new ArrayList<ReportFormat>();
formats.add(ReportFormat.PDF);
return formats;
}
public ReportParameters getParameters(String ReportId) {
return new ReportParameters();
}
public void render(String ReportId, String location, ReportFormat format,
OutputStream outputStream) throws ReportException {
try {
JasperPrint jasperPrint = JRPrintXmlLoader.load(location);
switch (format) {
case PDF:
log.debug("rendering as PDF");
JasperExportManager.exportReportToPdfStream(jasperPrint,
outputStream);
break;
default:
log.debug("rendering as PDF as no valid format found");
JasperExportManager.exportReportToPdfStream(jasperPrint,
outputStream);
}
} catch (JRException e) {
log.error("unable to render report", e);
throw new ReportException("unable to render report", e);
}
}
public String run(HashMap<String, Object> reportParms, String reportId)
throws ReportException {
String baseDir = System.getProperty("opennms.report.dir");
JasperReport jasperReport = null;
JasperPrint jasperPrint = null;
String outputFileName = null;
String sourceFileName = m_jasperReportConfigDao.getTemplateLocation(reportId);
if (sourceFileName != null) {
try {
jasperReport = JasperCompileManager.compileReport(System.getProperty("opennms.home")
+ "/etc/report-templates/" + sourceFileName);
} catch (JRException e) {
log.error("unable to compile jasper report", e);
throw new ReportException("unable to compile jasperReport", e);
}
outputFileName = new String(baseDir + "/"
+ jasperReport.getName() + ".jrpxml");
log.debug("jrpcml output file: " + outputFileName);
if (m_jasperReportConfigDao.getEngine(reportId).equals("jdbc")) {
Connection connection;
try {
connection = DataSourceFactory.getDataSource().getConnection();
jasperPrint = JasperFillManager.fillReport(jasperReport,
reportParms,
connection);
JRXmlExporter exporter = new JRXmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
exporter.setParameter(
JRExporterParameter.OUTPUT_FILE_NAME,
outputFileName);
exporter.exportReport();
connection.close();
} catch (SQLException e) {
log.error("sql exception getting or closing datasource ",
e);
throw new ReportException(
"sql exception getting or closing datasource",
e);
} catch (JRException e) {
log.error("jasper report exception ", e);
throw new ReportException(
"unable to run emptyDataSource jasperReport",
e);
}
} else if (m_jasperReportConfigDao.getEngine(reportId).equals(
"null")) {
try {
jasperPrint = JasperFillManager.fillReport(
jasperReport,
reportParms,
new JREmptyDataSource());
JRXmlExporter exporter = new JRXmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT,
jasperPrint);
exporter.setParameter(
JRExporterParameter.OUTPUT_FILE_NAME,
outputFileName);
exporter.exportReport();
} catch (JRException e) {
log.error("jasper report exception ", e);
throw new ReportException(
"unable to run emptyDataSource jasperReport",
e);
}
} else {
throw new ReportException(
"no suitable datasource configured for reportId: "
+ reportId);
}
}
return outputFileName;
}
public void runAndRender(HashMap<String, Object> reportParms,
String reportId, ReportFormat format, OutputStream outputStream)
throws ReportException {
JasperReport jasperReport = null;
JasperPrint jasperPrint = null;
String sourceFileName = m_jasperReportConfigDao.getTemplateLocation(reportId);
if (sourceFileName != null) {
try {
jasperReport = JasperCompileManager.compileReport(System.getProperty("opennms.home")
+ "/etc/report-templates/" + sourceFileName);
} catch (JRException e) {
log.error("unable to compile jasper report", e);
throw new ReportException("unable to compile jasperReport", e);
}
if (m_jasperReportConfigDao.getEngine(reportId).equals("jdbc")) {
Connection connection;
try {
connection = DataSourceFactory.getDataSource().getConnection();
jasperPrint = JasperFillManager.fillReport(jasperReport,
reportParms,
connection);
JasperExportManager.exportReportToPdfStream(jasperPrint,
outputStream);
connection.close();
} catch (SQLException e) {
log.error("sql exception getting or closing datasource ",
e);
throw new ReportException(
"sql exception getting or closing datasource",
e);
} catch (JRException e) {
log.error("jasper report exception ", e);
throw new ReportException(
"unable to run or render jdbc jasperReport",
e);
}
} else if (m_jasperReportConfigDao.getEngine(reportId).equals(
"null")) {
try {
jasperPrint = JasperFillManager.fillReport(
jasperReport,
reportParms,
new JREmptyDataSource());
JasperExportManager.exportReportToPdfStream(jasperPrint,
outputStream);
} catch (JRException e) {
log.error("jasper report exception ", e);
throw new ReportException(
"unable to run or render emptyDataSource jasperReport",
e);
}
}
}
}
public boolean validate(HashMap<String, Object> reportParms,
String reportId) {
// returns true until we can take parameters
return true;
}
public void setConfigDao(JasperReportConfigDao jasperReportConfigDao) {
m_jasperReportConfigDao = jasperReportConfigDao;
}
}
| Minor log prefix cleanup.
| features/reporting/jasper-reports/src/main/java/org/opennms/reporting/jasperreports/svclayer/JasperReportService.java | Minor log prefix cleanup. | <ide><path>eatures/reporting/jasper-reports/src/main/java/org/opennms/reporting/jasperreports/svclayer/JasperReportService.java
<ide>
<ide> private JasperReportConfigDao m_jasperReportConfigDao;
<ide>
<del> private Category log;
<add> private final Category log;
<ide>
<ide> public JasperReportService() {
<add> String oldPrefix = ThreadCategory.getPrefix();
<ide> ThreadCategory.setPrefix(LOG4J_CATEGORY);
<ide> log = ThreadCategory.getInstance(JasperReportService.class);
<add> ThreadCategory.setPrefix(oldPrefix);
<ide> }
<ide>
<ide> public List<ReportFormat> getFormats(String reportId) { |
|
JavaScript | apache-2.0 | f5c8cfffd2c15991759a9b8f7804f553a7ef1039 | 0 | arduino-org/s4t-iotronic,MDSLab/s4t-iotronic,MDSLab/s4t-iotronic | /*
The MIT License (MIT)
Copyright (c) 2014 Andrea Rocco Lotronto
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.
*/
var autobahn = require('autobahn');
var express = require('express');
s4t_wamp_server = function(){
}
s4t_wamp_server.prototype.start = function(restPort, wamp_router_url){
var boards = {};
var getIP = require('./getIP.js');
var IPLocal = getIP('eth0', 'IPv4');
//var url_wamp_router = "ws://172.17.3.139:8181/ws"; //example of url wamp router
var connection = new autobahn.Connection({
//url: url_wamp_router,
url:wamp_router_url,
realm: "s4t"
});
var topic_command = 'board.command'
var topic_connection = 'board.connection'
connection.onopen = function (session, details) {
var rest = express();
rest.get('/', function (req, res){
res.send('API: <br> http://'+IPLocal+':'+restPort+'/list for board list');
});
rest.get('/command/', function (req, res){
//DEBUG Message
//console.log('POST::::'+req.originalUrl);
var board = req.query.board;
var command = req.query.command;
var pin = req.query.pin;
var mode = req.query.mode;
var value = req.query.val;
if(boards[board] != undefined){
//DEBUG Message
//console.log("ID exsist");
//console.log(command);
switch(command){
case 'ssh':
//random port for reverse service
var port = randomIntInc(6000,7000);
session.publish(topic_command, [board, command, port]);
//res.send("ssh -p "+port+" root@"+IPLocal);
res.json(IPLocal+':'+port);
break;
case 'ideino':
var port = randomIntInc(6000,7000);
session.publish(topic_command, [board, command, port]);
//res.send("http://"+IPLocal+":"+port);
res.json(IPLocal+':'+port);
break;
case 'osjs':
var port = randomIntInc(6000,7000);
session.publish(topic_command, [board, command, port]);
//res.send("http://"+IPLocal+":"+port);
res.json(IPLocal+':'+port);
break;
case 'mode':
if(mode === 'input' || mode ==='output'){
session.publish(topic_command, [board, command, pin, mode]);
res.json(pin+':'+mode);
break;
}
else{
res.json('null');
break;
}
//Analog
case 'analog':
console.log('VALORE='+value);
if(value!=undefined){//WRITE
console.log('ANALOG WRITE');
if(value<=0 && value <=1024){
session.publish(topic_command, [board, command, pin, value]);
res.json(pin+':'+value);
break;
}
else{
res.json('null');
break;
}
}
else{//READ
console.log('ANALOG READ');
session.call('command.rpc.read.analog', [board, command, pin]).then(
function(result){
res.json(result);
},session.log);
break;
}
//Digital
case 'digital':
console.log('VALORE='+value);
if(value!=undefined){//WRITE
console.log('DIGITAL WRITE');
if(value==0 || value==1){//WRITE
session.publish(topic_command, [board, command, pin, value]);
res.json(pin+':'+value);
break;
}
else{
res.json('null');
break;
}
}
else{//READ
console.log('DIGITAL READ');
session.call('command.rpc.read.digital', [board, command, pin]).then(
function(result){
res.json(result);
},session.log);
break;
}
default:
res.json('null')
break;
}
}
else
//res.send("Error: malformed REST ");
res.json('null');
});
rest.get('/list/', function (req, res){
var response='{ list: ['
//var board_list='';
//for (var i in boards){
// board_list += boards[i];
// command_list = "ssh"
// }
for (var i in boards){
response += boards[i]+","
}
var len = response.length;
response = response.slice(0,len-1);
response += '] }'
//res.send('List of the board: '+board_list+'<br>'+'use URL: '+IPLocal+":"+restPort+"/commad/?board=board_name&command=ssh|ideino");
res.json(response);
});
rest.listen(restPort);
console.log("Server REST started on: http://"+IPLocal+":"+restPort);
console.log("Connected to router WAMP");
// Publish, Subscribe, Call and Register
var onBoardConnected = function (args){
//registrare le schede che si connettono
console.log(args);
if(args[1]=='connection'){
boards[args[0]] = args[0];
//DEBUGGG Message
console.log("Board connected:"+args[0]+" board state:"+args[1]);
//DEBUGGG Message
console.log("List of board::"+boards.length);
for (var i in boards){
console.log('Key: '+i+' value: '+boards[i]);
}
}
if(args[1]=='disconnect'){
delete boards[args[0]];
//DEBUGGG
console.log("Board disconnected:"+args[0]+" board state:"+args[1]);
//DEBUGGG
console.log("List of the board::"+boards.length);
for (var i in boards){
console.log('Key: '+i+' value: '+boards[i]);
}
}
}
session.subscribe(topic_connection, onBoardConnected);
console.log("Subsscribe to topic: "+topic_connection);
};
connection.onclose = function (reason, details) {
// handle connection lost
}
connection.open();
}
//function for pseudo random number
function randomIntInc (low, high) {
return Math.floor(Math.random() * (high - low + 1) + low);
}
module.exports = s4t_wamp_server; | s4t-server-node/lib/s4t_wamp_server.js | /*
The MIT License (MIT)
Copyright (c) 2014 Andrea Rocco Lotronto
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.
*/
var autobahn = require('autobahn');
var express = require('express');
s4t_wamp_server = function(){
}
s4t_wamp_server.prototype.start = function(restPort, wamp_router_url){
var boards = {};
var getIP = require('./getIP.js');
var IPLocal = getIP('eth0', 'IPv4');
//var url_wamp_router = "ws://172.17.3.139:8181/ws"; //example of url wamp router
var connection = new autobahn.Connection({
//url: url_wamp_router,
url:wamp_router_url,
realm: "s4t"
});
var topic_command = 'board.command'
var topic_connection = 'board.connection'
connection.onopen = function (session, details) {
var rest = express();
rest.get('/', function (req, res){
res.send('API: <br> http://'+IPLocal+':'+restPort+'/list for board list');
});
rest.get('/command/', function (req, res){
//DEBUG Message
//console.log('POST::::'+req.originalUrl);
var board = req.query.board;
var command = req.query.command;
var pin = req.query.pin;
var mode = req.query.mode;
var value = req.query.val;
if(boards[board] != undefined){
//DEBUG Message
//console.log("ID exsist");
//console.log(command);
switch(command){
case 'ssh':
//random port for reverse service
var port = randomIntInc(6000,7000);
session.publish(topic_command, [board, command, port]);
//res.send("ssh -p "+port+" root@"+IPLocal);
res.json(IPLocal+':'+port);
break;
case 'ideino':
var port = randomIntInc(6000,7000);
session.publish(topic_command, [board, command, port]);
//res.send("http://"+IPLocal+":"+port);
res.json(IPLocal+':'+port);
break;
case 'osjs':
var port = randomIntInc(6000,7000);
session.publish(topic_command, [board, command, port]);
//res.send("http://"+IPLocal+":"+port);
res.json(IPLocal+':'+port);
break;
case 'mode':
if(mode === 'input' || mode ==='output'){
session.publish(topic_command, [board, command, pin, mode]);
res.json(pin+':'+mode);
break;
}
else{
res.json('null');
break;
}
//Analog
case 'analog':
console.log('VALORE='+value);
if(value!=undefined){//WRITE
console.log('ANALOG WRITE');
if(value<=0 && value <=1024){
session.publish(topic_command, [board, command, pin, value]);
res.json(pin+':'+value);
break;
}
else{
res.json('null');
break;
}
}
else{//READ
console.log('ANALOG WRITE');
session.call('command.rpc.read.analog', [board, command, pin]).then(
function(result){
res.json(result);
}
);
break;
}
//Digital
case 'digital':
console.log('VALORE='+value);
if(value!=undefined){//WRITE
console.log('DIGITAL WRITE');
if(value==0 || value==1){//WRITE
session.publish(topic_command, [board, command, pin, value]);
res.json(pin+':'+value);
break;
}
else{
res.json('null');
break;
}
}
else{//READ
console.log('DIGITAL READ');
session.call('command.rpc.read.digital', [board, command, pin]).then(
function(result){
res.json(result);
},session.log);
break;
}
default:
res.json('null')
break;
}
}
else
//res.send("Error: malformed REST ");
res.json('null');
});
rest.get('/list/', function (req, res){
var response='{ list: ['
//var board_list='';
//for (var i in boards){
// board_list += boards[i];
// command_list = "ssh"
// }
for (var i in boards){
response += boards[i]+","
}
var len = response.length;
response = response.slice(0,len-1);
response += '] }'
//res.send('List of the board: '+board_list+'<br>'+'use URL: '+IPLocal+":"+restPort+"/commad/?board=board_name&command=ssh|ideino");
res.json(response);
});
rest.listen(restPort);
console.log("Server REST started on: http://"+IPLocal+":"+restPort);
console.log("Connected to router WAMP");
// Publish, Subscribe, Call and Register
var onBoardConnected = function (args){
//registrare le schede che si connettono
console.log(args);
if(args[1]=='connection'){
boards[args[0]] = args[0];
//DEBUGGG Message
console.log("Board connected:"+args[0]+" board state:"+args[1]);
//DEBUGGG Message
console.log("List of board::"+boards.length);
for (var i in boards){
console.log('Key: '+i+' value: '+boards[i]);
}
}
if(args[1]=='disconnect'){
delete boards[args[0]];
//DEBUGGG
console.log("Board disconnected:"+args[0]+" board state:"+args[1]);
//DEBUGGG
console.log("List of the board::"+boards.length);
for (var i in boards){
console.log('Key: '+i+' value: '+boards[i]);
}
}
}
session.subscribe(topic_connection, onBoardConnected);
console.log("Subsscribe to topic: "+topic_connection);
};
connection.onclose = function (reason, details) {
// handle connection lost
}
connection.open();
}
//function for pseudo random number
function randomIntInc (low, high) {
return Math.floor(Math.random() * (high - low + 1) + low);
}
module.exports = s4t_wamp_server; | adjustments for demo
| s4t-server-node/lib/s4t_wamp_server.js | adjustments for demo | <ide><path>4t-server-node/lib/s4t_wamp_server.js
<ide> }
<ide> }
<ide> else{//READ
<del> console.log('ANALOG WRITE');
<add> console.log('ANALOG READ');
<ide> session.call('command.rpc.read.analog', [board, command, pin]).then(
<ide> function(result){
<ide> res.json(result);
<del> }
<del> );
<add> },session.log);
<ide> break;
<ide> }
<ide> |
|
Java | apache-2.0 | e149d3e8cca3bde97656ab986e91c3cf9d994612 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | /**
* 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.
*/
package org.apache.solr.handler.admin;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.*;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.analysis.CharFilterFactory;
import org.apache.solr.analysis.TokenFilterFactory;
import org.apache.solr.analysis.TokenizerChain;
import org.apache.solr.analysis.TokenizerFactory;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.luke.FieldFlag;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.Base64;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.FieldType;
import org.apache.solr.update.SolrIndexWriter;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.SolrIndexSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.lucene.index.FieldInfo.IndexOptions.DOCS_AND_FREQS;
import static org.apache.lucene.index.FieldInfo.IndexOptions.DOCS_ONLY;
/**
* This handler exposes the internal lucene index. It is inspired by and
* modeled on Luke, the Lucene Index Browser by Andrzej Bialecki.
* http://www.getopt.org/luke/
*
* For more documentation see:
* http://wiki.apache.org/solr/LukeRequestHandler
*
* @since solr 1.2
*/
public class LukeRequestHandler extends RequestHandlerBase
{
private static Logger log = LoggerFactory.getLogger(LukeRequestHandler.class);
public static final String NUMTERMS = "numTerms";
public static final String DOC_ID = "docId";
public static final String ID = "id";
public static final int DEFAULT_COUNT = 10;
static final int HIST_ARRAY_SIZE = 33;
private static enum ShowStyle {
ALL,
DOC,
SCHEMA,
INDEX;
public static ShowStyle get(String v) {
if(v==null) return null;
if("schema".equalsIgnoreCase(v)) return SCHEMA;
if("index".equalsIgnoreCase(v)) return INDEX;
if("doc".equalsIgnoreCase(v)) return DOC;
if("all".equalsIgnoreCase(v)) return ALL;
throw new SolrException(ErrorCode.BAD_REQUEST, "Unknown Show Style: "+v);
}
};
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception
{
IndexSchema schema = req.getSchema();
SolrIndexSearcher searcher = req.getSearcher();
DirectoryReader reader = searcher.getIndexReader();
SolrParams params = req.getParams();
ShowStyle style = ShowStyle.get(params.get("show"));
// If no doc is given, show all fields and top terms
rsp.add("index", getIndexInfo(reader));
if(ShowStyle.INDEX==style) {
return; // that's all we need
}
Integer docId = params.getInt( DOC_ID );
if( docId == null && params.get( ID ) != null ) {
// Look for something with a given solr ID
SchemaField uniqueKey = schema.getUniqueKeyField();
String v = uniqueKey.getType().toInternal( params.get(ID) );
Term t = new Term( uniqueKey.getName(), v );
docId = searcher.getFirstMatch( t );
if( docId < 0 ) {
throw new SolrException( SolrException.ErrorCode.NOT_FOUND, "Can't find document: "+params.get( ID ) );
}
}
// Read the document from the index
if( docId != null ) {
if( style != null && style != ShowStyle.DOC ) {
throw new SolrException(ErrorCode.BAD_REQUEST, "missing doc param for doc style");
}
Document doc = null;
try {
doc = reader.document( docId );
}
catch( Exception ex ) {}
if( doc == null ) {
throw new SolrException( SolrException.ErrorCode.NOT_FOUND, "Can't find document: "+docId );
}
SimpleOrderedMap<Object> info = getDocumentFieldsInfo( doc, docId, reader, schema );
SimpleOrderedMap<Object> docinfo = new SimpleOrderedMap<Object>();
docinfo.add( "docId", docId );
docinfo.add( "lucene", info );
docinfo.add( "solr", doc );
rsp.add( "doc", docinfo );
}
else if ( ShowStyle.SCHEMA == style ) {
rsp.add( "schema", getSchemaInfo( req.getSchema() ) );
}
else {
rsp.add( "fields", getIndexedFieldsInfo(req) ) ;
}
// Add some generally helpful information
NamedList<Object> info = new SimpleOrderedMap<Object>();
info.add( "key", getFieldFlagsKey() );
info.add( "NOTE", "Document Frequency (df) is not updated when a document is marked for deletion. df values include deleted documents." );
rsp.add( "info", info );
rsp.setHttpCaching(false);
}
/**
* @return a string representing a IndexableField's flags.
*/
private static String getFieldFlags( IndexableField f )
{
IndexOptions opts = (f == null) ? null : f.fieldType().indexOptions();
StringBuilder flags = new StringBuilder();
flags.append( (f != null && f.fieldType().indexed()) ? FieldFlag.INDEXED.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().tokenized()) ? FieldFlag.TOKENIZED.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().stored()) ? FieldFlag.STORED.getAbbreviation() : '-' );
flags.append( (false) ? FieldFlag.MULTI_VALUED.getAbbreviation() : '-' ); // SchemaField Specific
flags.append( (f != null && f.fieldType().storeTermVectors()) ? FieldFlag.TERM_VECTOR_STORED.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().storeTermVectorOffsets()) ? FieldFlag.TERM_VECTOR_OFFSET.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().storeTermVectorPositions()) ? FieldFlag.TERM_VECTOR_POSITION.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().omitNorms()) ? FieldFlag.OMIT_NORMS.getAbbreviation() : '-' );
flags.append( (f != null && DOCS_ONLY == opts ) ?
FieldFlag.OMIT_TF.getAbbreviation() : '-' );
flags.append((f != null && DOCS_AND_FREQS == opts) ?
FieldFlag.OMIT_POSITIONS.getAbbreviation() : '-');
flags.append( (f != null && f.getClass().getSimpleName().equals("LazyField")) ? FieldFlag.LAZY.getAbbreviation() : '-' );
flags.append( (f != null && f.binaryValue()!=null) ? FieldFlag.BINARY.getAbbreviation() : '-' );
flags.append( (false) ? FieldFlag.SORT_MISSING_FIRST.getAbbreviation() : '-' ); // SchemaField Specific
flags.append( (false) ? FieldFlag.SORT_MISSING_LAST.getAbbreviation() : '-' ); // SchemaField Specific
return flags.toString();
}
/**
* @return a string representing a SchemaField's flags.
*/
private static String getFieldFlags( SchemaField f )
{
FieldType t = (f==null) ? null : f.getType();
// see: http://www.nabble.com/schema-field-properties-tf3437753.html#a9585549
boolean lazy = false; // "lazy" is purely a property of reading fields
boolean binary = false; // Currently not possible
StringBuilder flags = new StringBuilder();
flags.append( (f != null && f.indexed()) ? FieldFlag.INDEXED.getAbbreviation() : '-' );
flags.append( (t != null && t.isTokenized()) ? FieldFlag.TOKENIZED.getAbbreviation() : '-' );
flags.append( (f != null && f.stored()) ? FieldFlag.STORED.getAbbreviation() : '-' );
flags.append( (f != null && f.multiValued()) ? FieldFlag.MULTI_VALUED.getAbbreviation() : '-' );
flags.append( (f != null && f.storeTermVector() ) ? FieldFlag.TERM_VECTOR_STORED.getAbbreviation() : '-' );
flags.append( (f != null && f.storeTermOffsets() ) ? FieldFlag.TERM_VECTOR_OFFSET.getAbbreviation() : '-' );
flags.append( (f != null && f.storeTermPositions() ) ? FieldFlag.TERM_VECTOR_POSITION.getAbbreviation() : '-' );
flags.append( (f != null && f.omitNorms()) ? FieldFlag.OMIT_NORMS.getAbbreviation() : '-' );
flags.append( (f != null &&
f.omitTermFreqAndPositions() ) ? FieldFlag.OMIT_TF.getAbbreviation() : '-' );
flags.append( (f != null && f.omitPositions() ) ? FieldFlag.OMIT_POSITIONS.getAbbreviation() : '-' );
flags.append( (lazy) ? FieldFlag.LAZY.getAbbreviation() : '-' );
flags.append( (binary) ? FieldFlag.BINARY.getAbbreviation() : '-' );
flags.append( (f != null && f.sortMissingFirst() ) ? FieldFlag.SORT_MISSING_FIRST.getAbbreviation() : '-' );
flags.append( (f != null && f.sortMissingLast() ) ? FieldFlag.SORT_MISSING_LAST.getAbbreviation() : '-' );
return flags.toString();
}
/**
* @return a key to what each character means
*/
public static SimpleOrderedMap<String> getFieldFlagsKey() {
SimpleOrderedMap<String> key = new SimpleOrderedMap<String>();
for (FieldFlag f : FieldFlag.values()) {
key.add(String.valueOf(f.getAbbreviation()), f.getDisplay() );
}
return key;
}
private static SimpleOrderedMap<Object> getDocumentFieldsInfo( Document doc, int docId, IndexReader reader,
IndexSchema schema ) throws IOException
{
final CharsRef spare = new CharsRef();
SimpleOrderedMap<Object> finfo = new SimpleOrderedMap<Object>();
for( Object o : doc.getFields() ) {
Field field = (Field)o;
SimpleOrderedMap<Object> f = new SimpleOrderedMap<Object>();
SchemaField sfield = schema.getFieldOrNull( field.name() );
FieldType ftype = (sfield==null)?null:sfield.getType();
f.add( "type", (ftype==null)?null:ftype.getTypeName() );
f.add( "schema", getFieldFlags( sfield ) );
f.add( "flags", getFieldFlags( field ) );
Term t = new Term(field.name(), ftype!=null ? ftype.storedToIndexed(field) : field.stringValue());
f.add( "value", (ftype==null)?null:ftype.toExternal( field ) );
// TODO: this really should be "stored"
f.add( "internal", field.stringValue() ); // may be a binary number
BytesRef bytes = field.binaryValue();
if (bytes != null) {
f.add( "binary", Base64.byteArrayToBase64(bytes.bytes, bytes.offset, bytes.length));
}
f.add( "boost", field.boost() );
f.add( "docFreq", t.text()==null ? 0 : reader.docFreq( t ) ); // this can be 0 for non-indexed fields
// If we have a term vector, return that
if( field.fieldType().storeTermVectors() ) {
try {
Terms v = reader.getTermVector( docId, field.name() );
if( v != null ) {
SimpleOrderedMap<Integer> tfv = new SimpleOrderedMap<Integer>();
final TermsEnum termsEnum = v.iterator(null);
BytesRef text;
while((text = termsEnum.next()) != null) {
final int freq = (int) termsEnum.totalTermFreq();
UnicodeUtil.UTF8toUTF16(text, spare);
tfv.add(spare.toString(), freq);
}
f.add( "termVector", tfv );
}
}
catch( Exception ex ) {
log.warn( "error writing term vector", ex );
}
}
finfo.add( field.name(), f );
}
return finfo;
}
private static SimpleOrderedMap<Object> getIndexedFieldsInfo(SolrQueryRequest req)
throws Exception {
SolrIndexSearcher searcher = req.getSearcher();
SolrParams params = req.getParams();
Set<String> fields = null;
String fl = params.get(CommonParams.FL);
if (fl != null) {
fields = new TreeSet<String>(Arrays.asList(fl.split( "[,\\s]+" )));
}
AtomicReader reader = searcher.getAtomicReader();
IndexSchema schema = searcher.getSchema();
// Don't be tempted to put this in the loop below, the whole point here is to alphabetize the fields!
Set<String> fieldNames = new TreeSet<String>();
for(FieldInfo fieldInfo : reader.getFieldInfos()) {
fieldNames.add(fieldInfo.name);
}
// Walk the term enum and keep a priority queue for each map in our set
SimpleOrderedMap<Object> finfo = new SimpleOrderedMap<Object>();
for (String fieldName : fieldNames) {
if (fields != null && ! fields.contains(fieldName) && ! fields.contains("*")) {
continue; //we're not interested in this field Still an issue here
}
SimpleOrderedMap<Object> fieldMap = new SimpleOrderedMap<Object>();
SchemaField sfield = schema.getFieldOrNull( fieldName );
FieldType ftype = (sfield==null)?null:sfield.getType();
fieldMap.add( "type", (ftype==null)?null:ftype.getTypeName() );
fieldMap.add("schema", getFieldFlags(sfield));
if (sfield != null && schema.isDynamicField(sfield.getName()) && schema.getDynamicPattern(sfield.getName()) != null) {
fieldMap.add("dynamicBase", schema.getDynamicPattern(sfield.getName()));
}
Terms terms = reader.fields().terms(fieldName);
if (terms == null) { // Not indexed, so we need to report what we can (it made it through the fl param if specified)
finfo.add( fieldName, fieldMap );
continue;
}
if(sfield != null && sfield.indexed() ) {
// In the pre-4.0 days, this did a veeeery expensive range query. But we can be much faster now,
// so just do this all the time.
Document doc = getFirstLiveDoc(reader, fieldName, terms);
if( doc != null ) {
// Found a document with this field
try {
IndexableField fld = doc.getField( fieldName );
if( fld != null ) {
fieldMap.add("index", getFieldFlags(fld));
}
else {
// it is a non-stored field...
fieldMap.add("index", "(unstored field)");
}
}
catch( Exception ex ) {
log.warn( "error reading field: "+fieldName );
}
}
fieldMap.add("docs", terms.getDocCount());
}
if (fields != null && (fields.contains(fieldName) || fields.contains("*"))) {
getDetailedFieldInfo(req, fieldName, fieldMap);
}
// Add the field
finfo.add( fieldName, fieldMap );
}
return finfo;
}
// Just get a document with the term in it, the first one will do!
// Is there a better way to do this? Shouldn't actually be very costly
// to do it this way.
private static Document getFirstLiveDoc(AtomicReader reader, String fieldName, Terms terms) throws IOException {
DocsEnum docsEnum = null;
TermsEnum termsEnum = terms.iterator(null);
BytesRef text;
// Deal with the chance that the first bunch of terms are in deleted documents. Is there a better way?
for (int idx = 0; idx < 1000 && docsEnum == null; ++idx) {
text = termsEnum.next();
if (text == null) { // Ran off the end of the terms enum without finding any live docs with that field in them.
return null;
}
Term term = new Term(fieldName, text);
docsEnum = reader.termDocsEnum(reader.getLiveDocs(),
term.field(),
new BytesRef(term.text()),
false);
if (docsEnum != null) {
int docId;
if ((docId = docsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
return reader.document(docId);
}
}
}
return null;
}
/**
* Return info from the index
*/
private static SimpleOrderedMap<Object> getSchemaInfo( IndexSchema schema ) {
Map<String, List<String>> typeusemap = new TreeMap<String, List<String>>();
Map<String, Object> fields = new TreeMap<String, Object>();
SchemaField uniqueField = schema.getUniqueKeyField();
for( SchemaField f : schema.getFields().values() ) {
populateFieldInfo(schema, typeusemap, fields, uniqueField, f);
}
Map<String, Object> dynamicFields = new TreeMap<String, Object>();
for (SchemaField f : schema.getDynamicFieldPrototypes()) {
populateFieldInfo(schema, typeusemap, dynamicFields, uniqueField, f);
}
SimpleOrderedMap<Object> types = new SimpleOrderedMap<Object>();
Map<String, FieldType> sortedTypes = new TreeMap<String, FieldType>(schema.getFieldTypes());
for( FieldType ft : sortedTypes.values() ) {
SimpleOrderedMap<Object> field = new SimpleOrderedMap<Object>();
field.add("fields", typeusemap.get( ft.getTypeName() ) );
field.add("tokenized", ft.isTokenized() );
field.add("className", ft.getClass().getName());
field.add("indexAnalyzer", getAnalyzerInfo(ft.getAnalyzer()));
field.add("queryAnalyzer", getAnalyzerInfo(ft.getQueryAnalyzer()));
types.add( ft.getTypeName(), field );
}
// Must go through this to maintain binary compatbility. Putting a TreeMap into a resp leads to casting errors
SimpleOrderedMap<Object> finfo = new SimpleOrderedMap<Object>();
SimpleOrderedMap<Object> fieldsSimple = new SimpleOrderedMap<Object>();
for (Map.Entry<String, Object> ent : fields.entrySet()) {
fieldsSimple.add(ent.getKey(), ent.getValue());
}
finfo.add("fields", fieldsSimple);
SimpleOrderedMap<Object> dynamicSimple = new SimpleOrderedMap<Object>();
for (Map.Entry<String, Object> ent : dynamicFields.entrySet()) {
dynamicSimple.add(ent.getKey(), ent.getValue());
}
finfo.add("dynamicFields", dynamicSimple);
finfo.add("uniqueKeyField",
null == uniqueField ? null : uniqueField.getName());
finfo.add("defaultSearchField", schema.getDefaultSearchFieldName());
finfo.add("types", types);
return finfo;
}
private static SimpleOrderedMap<Object> getAnalyzerInfo(Analyzer analyzer) {
SimpleOrderedMap<Object> aninfo = new SimpleOrderedMap<Object>();
aninfo.add("className", analyzer.getClass().getName());
if (analyzer instanceof TokenizerChain) {
TokenizerChain tchain = (TokenizerChain)analyzer;
CharFilterFactory[] cfiltfacs = tchain.getCharFilterFactories();
SimpleOrderedMap<Map<String, Object>> cfilters = new SimpleOrderedMap<Map<String, Object>>();
for (CharFilterFactory cfiltfac : cfiltfacs) {
Map<String, Object> tok = new HashMap<String, Object>();
String className = cfiltfac.getClass().getName();
tok.put("className", className);
tok.put("args", cfiltfac.getArgs());
cfilters.add(className.substring(className.lastIndexOf('.')+1), tok);
}
if (cfilters.size() > 0) {
aninfo.add("charFilters", cfilters);
}
SimpleOrderedMap<Object> tokenizer = new SimpleOrderedMap<Object>();
TokenizerFactory tfac = tchain.getTokenizerFactory();
tokenizer.add("className", tfac.getClass().getName());
tokenizer.add("args", tfac.getArgs());
aninfo.add("tokenizer", tokenizer);
TokenFilterFactory[] filtfacs = tchain.getTokenFilterFactories();
SimpleOrderedMap<Map<String, Object>> filters = new SimpleOrderedMap<Map<String, Object>>();
for (TokenFilterFactory filtfac : filtfacs) {
Map<String, Object> tok = new HashMap<String, Object>();
String className = filtfac.getClass().getName();
tok.put("className", className);
tok.put("args", filtfac.getArgs());
filters.add(className.substring(className.lastIndexOf('.')+1), tok);
}
if (filters.size() > 0) {
aninfo.add("filters", filters);
}
}
return aninfo;
}
private static void populateFieldInfo(IndexSchema schema,
Map<String, List<String>> typeusemap, Map<String, Object> fields,
SchemaField uniqueField, SchemaField f) {
FieldType ft = f.getType();
SimpleOrderedMap<Object> field = new SimpleOrderedMap<Object>();
field.add( "type", ft.getTypeName() );
field.add( "flags", getFieldFlags(f) );
if( f.isRequired() ) {
field.add( "required", f.isRequired() );
}
if( f.getDefaultValue() != null ) {
field.add( "default", f.getDefaultValue() );
}
if (f == uniqueField){
field.add("uniqueKey", true);
}
if (ft.getAnalyzer().getPositionIncrementGap(f.getName()) != 0) {
field.add("positionIncrementGap", ft.getAnalyzer().getPositionIncrementGap(f.getName()));
}
field.add("copyDests", schema.getCopyFieldsList(f.getName()));
field.add("copySources", schema.getCopySources(f.getName()));
fields.put( f.getName(), field );
List<String> v = typeusemap.get( ft.getTypeName() );
if( v == null ) {
v = new ArrayList<String>();
}
v.add( f.getName() );
typeusemap.put( ft.getTypeName(), v );
}
/**
* @deprecated use {@link #getIndexInfo(DirectoryReader)} since you now have to explicitly pass the "fl" prameter
* and this was always called with "false" anyway from CoreAdminHandler
*/
public static SimpleOrderedMap<Object> getIndexInfo(DirectoryReader reader, boolean detail) throws IOException {
return getIndexInfo(reader);
}
// This method just gets the top-most level of information. This was conflated with getting detailed info
// for *all* the fields, called from CoreAdminHandler etc.
public static SimpleOrderedMap<Object> getIndexInfo(DirectoryReader reader) throws IOException {
Directory dir = reader.directory();
SimpleOrderedMap<Object> indexInfo = new SimpleOrderedMap<Object>();
indexInfo.add("numDocs", reader.numDocs());
indexInfo.add("maxDoc", reader.maxDoc());
indexInfo.add("version", reader.getVersion()); // TODO? Is this different then: IndexReader.getCurrentVersion( dir )?
indexInfo.add("segmentCount", reader.getSequentialSubReaders().length);
indexInfo.add("current", reader.isCurrent() );
indexInfo.add("hasDeletions", reader.hasDeletions() );
indexInfo.add("directory", dir );
indexInfo.add("userData", reader.getIndexCommit().getUserData());
String s = reader.getIndexCommit().getUserData().get(SolrIndexWriter.COMMIT_TIME_MSEC_KEY);
if (s != null) {
indexInfo.add("lastModified", new Date(Long.parseLong(s)));
}
return indexInfo;
}
// Get terribly detailed information about a particular field. This is a very expensive call, use it with caution
// especially on large indexes!
@SuppressWarnings("unchecked")
private static void getDetailedFieldInfo(SolrQueryRequest req, String field, SimpleOrderedMap<Object> fieldMap)
throws IOException {
SolrParams params = req.getParams();
int numTerms = params.getInt( NUMTERMS, DEFAULT_COUNT );
TopTermQueue tiq = new TopTermQueue(numTerms + 1); // Something to collect the top N terms in.
final CharsRef spare = new CharsRef();
Fields fields = MultiFields.getFields(req.getSearcher().getIndexReader());
if (fields == null) { // No indexed fields
return;
}
Terms terms = fields.terms(field);
if (terms == null) { // No terms in the field.
return;
}
TermsEnum termsEnum = terms.iterator(null);
BytesRef text;
int[] buckets = new int[HIST_ARRAY_SIZE];
while ((text = termsEnum.next()) != null) {
int freq = termsEnum.docFreq(); // This calculation seems odd, but it gives the same results as it used to.
int slot = 32 - Integer.numberOfLeadingZeros(Math.max(0, freq - 1));
buckets[slot] = buckets[slot] + 1;
if (freq > tiq.minFreq) {
UnicodeUtil.UTF8toUTF16(text, spare);
String t = spare.toString();
tiq.distinctTerms = new Long(terms.size()).intValue();
tiq.add(new TopTermQueue.TermInfo(new Term(field, t), termsEnum.docFreq()));
if (tiq.size() > numTerms) { // if tiq full
tiq.pop(); // remove lowest in tiq
tiq.minFreq = tiq.getTopTermInfo().docFreq;
}
}
}
tiq.histogram.add(buckets);
fieldMap.add("distinct", tiq.distinctTerms);
// Include top terms
fieldMap.add("topTerms", tiq.toNamedList(req.getSearcher().getSchema()));
// Add a histogram
fieldMap.add("histogram", tiq.histogram.toNamedList());
}
//////////////////////// SolrInfoMBeans methods //////////////////////
@Override
public String getDescription() {
return "Lucene Index Browser. Inspired and modeled after Luke: http://www.getopt.org/luke/";
}
@Override
public String getSource() {
return "$URL$";
}
@Override
public URL[] getDocs() {
try {
return new URL[] { new URL("http://wiki.apache.org/solr/LukeRequestHandler") };
}
catch( MalformedURLException ex ) { return null; }
}
///////////////////////////////////////////////////////////////////////////////////////
static class TermHistogram
{
int _maxBucket = -1;
int _buckets[] = new int[HIST_ARRAY_SIZE];
public void add(int[] buckets) {
for (int idx = 0; idx < buckets.length; ++idx) {
if (buckets[idx] != 0) _maxBucket = idx;
}
for (int idx = 0; idx <= _maxBucket; ++idx) {
_buckets[idx] = buckets[idx];
}
}
// TODO? should this be a list or a map?
public NamedList<Integer> toNamedList()
{
NamedList<Integer> nl = new NamedList<Integer>();
for( int bucket = 0; bucket <= _maxBucket; bucket++ ) {
nl.add( ""+ (1 << bucket), _buckets[bucket] );
}
return nl;
}
}
/**
* Private internal class that counts up frequent terms
*/
private static class TopTermQueue extends PriorityQueue
{
static class TermInfo {
TermInfo(Term t, int df) {
term = t;
docFreq = df;
}
int docFreq;
Term term;
}
public int minFreq = 0;
public int distinctTerms = 0;
public TermHistogram histogram;
TopTermQueue(int size) {
super(size);
histogram = new TermHistogram();
}
@Override
protected final boolean lessThan(Object a, Object b) {
TermInfo termInfoA = (TermInfo)a;
TermInfo termInfoB = (TermInfo)b;
return termInfoA.docFreq < termInfoB.docFreq;
}
/**
* This is a destructive call... the queue is empty at the end
*/
public NamedList<Integer> toNamedList( IndexSchema schema )
{
// reverse the list..
List<TermInfo> aslist = new LinkedList<TermInfo>();
while( size() > 0 ) {
aslist.add( 0, (TermInfo)pop() );
}
NamedList<Integer> list = new NamedList<Integer>();
for (TermInfo i : aslist) {
String txt = i.term.text();
SchemaField ft = schema.getFieldOrNull( i.term.field() );
if( ft != null ) {
txt = ft.getType().indexedToReadable( txt );
}
list.add( txt, i.docFreq );
}
return list;
}
public TermInfo getTopTermInfo() {
return (TermInfo)top();
}
}
}
| solr/core/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java | /**
* 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.
*/
package org.apache.solr.handler.admin;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.*;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.analysis.CharFilterFactory;
import org.apache.solr.analysis.TokenFilterFactory;
import org.apache.solr.analysis.TokenizerChain;
import org.apache.solr.analysis.TokenizerFactory;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.luke.FieldFlag;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.Base64;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.FieldType;
import org.apache.solr.update.SolrIndexWriter;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.SolrIndexSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.lucene.index.FieldInfo.IndexOptions.DOCS_AND_FREQS;
import static org.apache.lucene.index.FieldInfo.IndexOptions.DOCS_ONLY;
/**
* This handler exposes the internal lucene index. It is inspired by and
* modeled on Luke, the Lucene Index Browser by Andrzej Bialecki.
* http://www.getopt.org/luke/
* <p>
* NOTE: the response format is still likely to change. It should be designed so
* that it works nicely with an XSLT transformation. Until we have a nice
* XSLT front end for /admin, the format is still open to change.
* </p>
*
* For more documentation see:
* http://wiki.apache.org/solr/LukeRequestHandler
*
*
* @since solr 1.2
*/
public class LukeRequestHandler extends RequestHandlerBase
{
private static Logger log = LoggerFactory.getLogger(LukeRequestHandler.class);
public static final String NUMTERMS = "numTerms";
public static final String DOC_ID = "docId";
public static final String ID = "id";
public static final int DEFAULT_COUNT = 10;
static final int HIST_ARRAY_SIZE = 33;
private static enum ShowStyle {
ALL,
DOC,
SCHEMA,
INDEX;
public static ShowStyle get(String v) {
if(v==null) return null;
if("schema".equalsIgnoreCase(v)) return SCHEMA;
if("index".equalsIgnoreCase(v)) return INDEX;
if("doc".equalsIgnoreCase(v)) return DOC;
if("all".equalsIgnoreCase(v)) return ALL;
throw new SolrException(ErrorCode.BAD_REQUEST, "Unknown Show Style: "+v);
}
};
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception
{
IndexSchema schema = req.getSchema();
SolrIndexSearcher searcher = req.getSearcher();
DirectoryReader reader = searcher.getIndexReader();
SolrParams params = req.getParams();
ShowStyle style = ShowStyle.get(params.get("show"));
// If no doc is given, show all fields and top terms
rsp.add("index", getIndexInfo(reader));
if(ShowStyle.INDEX==style) {
return; // that's all we need
}
Integer docId = params.getInt( DOC_ID );
if( docId == null && params.get( ID ) != null ) {
// Look for something with a given solr ID
SchemaField uniqueKey = schema.getUniqueKeyField();
String v = uniqueKey.getType().toInternal( params.get(ID) );
Term t = new Term( uniqueKey.getName(), v );
docId = searcher.getFirstMatch( t );
if( docId < 0 ) {
throw new SolrException( SolrException.ErrorCode.NOT_FOUND, "Can't find document: "+params.get( ID ) );
}
}
// Read the document from the index
if( docId != null ) {
if( style != null && style != ShowStyle.DOC ) {
throw new SolrException(ErrorCode.BAD_REQUEST, "missing doc param for doc style");
}
Document doc = null;
try {
doc = reader.document( docId );
}
catch( Exception ex ) {}
if( doc == null ) {
throw new SolrException( SolrException.ErrorCode.NOT_FOUND, "Can't find document: "+docId );
}
SimpleOrderedMap<Object> info = getDocumentFieldsInfo( doc, docId, reader, schema );
SimpleOrderedMap<Object> docinfo = new SimpleOrderedMap<Object>();
docinfo.add( "docId", docId );
docinfo.add( "lucene", info );
docinfo.add( "solr", doc );
rsp.add( "doc", docinfo );
}
else if ( ShowStyle.SCHEMA == style ) {
rsp.add( "schema", getSchemaInfo( req.getSchema() ) );
}
else {
rsp.add( "fields", getIndexedFieldsInfo(req) ) ;
}
// Add some generally helpful information
NamedList<Object> info = new SimpleOrderedMap<Object>();
info.add( "key", getFieldFlagsKey() );
info.add( "NOTE", "Document Frequency (df) is not updated when a document is marked for deletion. df values include deleted documents." );
rsp.add( "info", info );
rsp.setHttpCaching(false);
}
/**
* @return a string representing a IndexableField's flags.
*/
private static String getFieldFlags( IndexableField f )
{
IndexOptions opts = (f == null) ? null : f.fieldType().indexOptions();
StringBuilder flags = new StringBuilder();
flags.append( (f != null && f.fieldType().indexed()) ? FieldFlag.INDEXED.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().tokenized()) ? FieldFlag.TOKENIZED.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().stored()) ? FieldFlag.STORED.getAbbreviation() : '-' );
flags.append( (false) ? FieldFlag.MULTI_VALUED.getAbbreviation() : '-' ); // SchemaField Specific
flags.append( (f != null && f.fieldType().storeTermVectors()) ? FieldFlag.TERM_VECTOR_STORED.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().storeTermVectorOffsets()) ? FieldFlag.TERM_VECTOR_OFFSET.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().storeTermVectorPositions()) ? FieldFlag.TERM_VECTOR_POSITION.getAbbreviation() : '-' );
flags.append( (f != null && f.fieldType().omitNorms()) ? FieldFlag.OMIT_NORMS.getAbbreviation() : '-' );
flags.append( (f != null && DOCS_ONLY == opts ) ?
FieldFlag.OMIT_TF.getAbbreviation() : '-' );
flags.append((f != null && DOCS_AND_FREQS == opts) ?
FieldFlag.OMIT_POSITIONS.getAbbreviation() : '-');
flags.append( (f != null && f.getClass().getSimpleName().equals("LazyField")) ? FieldFlag.LAZY.getAbbreviation() : '-' );
flags.append( (f != null && f.binaryValue()!=null) ? FieldFlag.BINARY.getAbbreviation() : '-' );
flags.append( (false) ? FieldFlag.SORT_MISSING_FIRST.getAbbreviation() : '-' ); // SchemaField Specific
flags.append( (false) ? FieldFlag.SORT_MISSING_LAST.getAbbreviation() : '-' ); // SchemaField Specific
return flags.toString();
}
/**
* @return a string representing a SchemaField's flags.
*/
private static String getFieldFlags( SchemaField f )
{
FieldType t = (f==null) ? null : f.getType();
// see: http://www.nabble.com/schema-field-properties-tf3437753.html#a9585549
boolean lazy = false; // "lazy" is purely a property of reading fields
boolean binary = false; // Currently not possible
StringBuilder flags = new StringBuilder();
flags.append( (f != null && f.indexed()) ? FieldFlag.INDEXED.getAbbreviation() : '-' );
flags.append( (t != null && t.isTokenized()) ? FieldFlag.TOKENIZED.getAbbreviation() : '-' );
flags.append( (f != null && f.stored()) ? FieldFlag.STORED.getAbbreviation() : '-' );
flags.append( (f != null && f.multiValued()) ? FieldFlag.MULTI_VALUED.getAbbreviation() : '-' );
flags.append( (f != null && f.storeTermVector() ) ? FieldFlag.TERM_VECTOR_STORED.getAbbreviation() : '-' );
flags.append( (f != null && f.storeTermOffsets() ) ? FieldFlag.TERM_VECTOR_OFFSET.getAbbreviation() : '-' );
flags.append( (f != null && f.storeTermPositions() ) ? FieldFlag.TERM_VECTOR_POSITION.getAbbreviation() : '-' );
flags.append( (f != null && f.omitNorms()) ? FieldFlag.OMIT_NORMS.getAbbreviation() : '-' );
flags.append( (f != null &&
f.omitTermFreqAndPositions() ) ? FieldFlag.OMIT_TF.getAbbreviation() : '-' );
flags.append( (f != null && f.omitPositions() ) ? FieldFlag.OMIT_POSITIONS.getAbbreviation() : '-' );
flags.append( (lazy) ? FieldFlag.LAZY.getAbbreviation() : '-' );
flags.append( (binary) ? FieldFlag.BINARY.getAbbreviation() : '-' );
flags.append( (f != null && f.sortMissingFirst() ) ? FieldFlag.SORT_MISSING_FIRST.getAbbreviation() : '-' );
flags.append( (f != null && f.sortMissingLast() ) ? FieldFlag.SORT_MISSING_LAST.getAbbreviation() : '-' );
return flags.toString();
}
/**
* @return a key to what each character means
*/
public static SimpleOrderedMap<String> getFieldFlagsKey() {
SimpleOrderedMap<String> key = new SimpleOrderedMap<String>();
for (FieldFlag f : FieldFlag.values()) {
key.add(String.valueOf(f.getAbbreviation()), f.getDisplay() );
}
return key;
}
private static SimpleOrderedMap<Object> getDocumentFieldsInfo( Document doc, int docId, IndexReader reader,
IndexSchema schema ) throws IOException
{
final CharsRef spare = new CharsRef();
SimpleOrderedMap<Object> finfo = new SimpleOrderedMap<Object>();
for( Object o : doc.getFields() ) {
Field field = (Field)o;
SimpleOrderedMap<Object> f = new SimpleOrderedMap<Object>();
SchemaField sfield = schema.getFieldOrNull( field.name() );
FieldType ftype = (sfield==null)?null:sfield.getType();
f.add( "type", (ftype==null)?null:ftype.getTypeName() );
f.add( "schema", getFieldFlags( sfield ) );
f.add( "flags", getFieldFlags( field ) );
Term t = new Term(field.name(), ftype!=null ? ftype.storedToIndexed(field) : field.stringValue());
f.add( "value", (ftype==null)?null:ftype.toExternal( field ) );
// TODO: this really should be "stored"
f.add( "internal", field.stringValue() ); // may be a binary number
BytesRef bytes = field.binaryValue();
if (bytes != null) {
f.add( "binary", Base64.byteArrayToBase64(bytes.bytes, bytes.offset, bytes.length));
}
f.add( "boost", field.boost() );
f.add( "docFreq", t.text()==null ? 0 : reader.docFreq( t ) ); // this can be 0 for non-indexed fields
// If we have a term vector, return that
if( field.fieldType().storeTermVectors() ) {
try {
Terms v = reader.getTermVector( docId, field.name() );
if( v != null ) {
SimpleOrderedMap<Integer> tfv = new SimpleOrderedMap<Integer>();
final TermsEnum termsEnum = v.iterator(null);
BytesRef text;
while((text = termsEnum.next()) != null) {
final int freq = (int) termsEnum.totalTermFreq();
UnicodeUtil.UTF8toUTF16(text, spare);
tfv.add(spare.toString(), freq);
}
f.add( "termVector", tfv );
}
}
catch( Exception ex ) {
log.warn( "error writing term vector", ex );
}
}
finfo.add( field.name(), f );
}
return finfo;
}
@SuppressWarnings("unchecked")
private static SimpleOrderedMap<Object> getIndexedFieldsInfo(SolrQueryRequest req)
throws Exception {
SolrIndexSearcher searcher = req.getSearcher();
SolrParams params = req.getParams();
Set<String> fields = null;
String fl = params.get(CommonParams.FL);
if (fl != null) {
fields = new TreeSet<String>(Arrays.asList(fl.split( "[,\\s]+" )));
}
AtomicReader reader = searcher.getAtomicReader();
IndexSchema schema = searcher.getSchema();
// Don't be tempted to put this in the loop below, the whole point here is to alphabetize the fields!
Set<String> fieldNames = new TreeSet<String>();
for(FieldInfo fieldInfo : reader.getFieldInfos()) {
fieldNames.add(fieldInfo.name);
}
// Walk the term enum and keep a priority queue for each map in our set
SimpleOrderedMap<Object> finfo = new SimpleOrderedMap<Object>();
for (String fieldName : fieldNames) {
if (fields != null && ! fields.contains(fieldName) && ! fields.contains("*")) {
continue; //we're not interested in this field Still an issue here
}
SimpleOrderedMap<Object> fieldMap = new SimpleOrderedMap<Object>();
SchemaField sfield = schema.getFieldOrNull( fieldName );
FieldType ftype = (sfield==null)?null:sfield.getType();
fieldMap.add( "type", (ftype==null)?null:ftype.getTypeName() );
fieldMap.add("schema", getFieldFlags(sfield));
if (sfield != null && schema.isDynamicField(sfield.getName()) && schema.getDynamicPattern(sfield.getName()) != null) {
fieldMap.add("dynamicBase", schema.getDynamicPattern(sfield.getName()));
}
Terms terms = reader.fields().terms(fieldName);
if (terms == null) { // Not indexed, so we need to report what we can (it made it through the fl param if specified)
finfo.add( fieldName, fieldMap );
continue;
}
if(sfield != null && sfield.indexed() ) {
// In the pre-4.0 days, this did a veeeery expensive range query. But we can be much faster now,
// so just do this all the time.
Document doc = getFirstLiveDoc(reader, fieldName, terms);
if( doc != null ) {
// Found a document with this field
try {
IndexableField fld = doc.getField( fieldName );
if( fld != null ) {
fieldMap.add("index", getFieldFlags(fld));
}
else {
// it is a non-stored field...
fieldMap.add("index", "(unstored field)");
}
}
catch( Exception ex ) {
log.warn( "error reading field: "+fieldName );
}
}
fieldMap.add("docs", terms.getDocCount());
}
if (fields != null && (fields.contains(fieldName) || fields.contains("*"))) {
getDetailedFieldInfo(req, fieldName, fieldMap);
}
// Add the field
finfo.add( fieldName, fieldMap );
}
return finfo;
}
// Just get a document with the term in it, the first one will do!
// Is there a better way to do this? Shouldn't actually be very costly
// to do it this way.
private static Document getFirstLiveDoc(AtomicReader reader, String fieldName, Terms terms) throws IOException {
DocsEnum docsEnum = null;
TermsEnum termsEnum = terms.iterator(null);
BytesRef text;
// Deal with the chance that the first bunch of terms are in deleted documents. Is there a better way?
for (int idx = 0; idx < 1000 && docsEnum == null; ++idx) {
text = termsEnum.next();
if (text == null) { // Ran off the end of the terms enum without finding any live docs with that field in them.
return null;
}
Term term = new Term(fieldName, text);
docsEnum = reader.termDocsEnum(reader.getLiveDocs(),
term.field(),
new BytesRef(term.text()),
false);
if (docsEnum != null) {
int docId;
if ((docId = docsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) {
return reader.document(docId);
}
}
}
return null;
}
/**
* Return info from the index
*/
private static SimpleOrderedMap<Object> getSchemaInfo( IndexSchema schema ) {
Map<String, List<String>> typeusemap = new TreeMap<String, List<String>>();
Map<String, Object> fields = new TreeMap<String, Object>();
SchemaField uniqueField = schema.getUniqueKeyField();
for( SchemaField f : schema.getFields().values() ) {
populateFieldInfo(schema, typeusemap, fields, uniqueField, f);
}
Map<String, Object> dynamicFields = new TreeMap<String, Object>();
for (SchemaField f : schema.getDynamicFieldPrototypes()) {
populateFieldInfo(schema, typeusemap, dynamicFields, uniqueField, f);
}
SimpleOrderedMap<Object> types = new SimpleOrderedMap<Object>();
Map<String, FieldType> sortedTypes = new TreeMap<String, FieldType>(schema.getFieldTypes());
for( FieldType ft : sortedTypes.values() ) {
SimpleOrderedMap<Object> field = new SimpleOrderedMap<Object>();
field.add("fields", typeusemap.get( ft.getTypeName() ) );
field.add("tokenized", ft.isTokenized() );
field.add("className", ft.getClass().getName());
field.add("indexAnalyzer", getAnalyzerInfo(ft.getAnalyzer()));
field.add("queryAnalyzer", getAnalyzerInfo(ft.getQueryAnalyzer()));
types.add( ft.getTypeName(), field );
}
// Must go through this to maintain binary compatbility. Putting a TreeMap into a resp leads to casting errors
SimpleOrderedMap<Object> finfo = new SimpleOrderedMap<Object>();
SimpleOrderedMap<Object> fieldsSimple = new SimpleOrderedMap<Object>();
for (Map.Entry<String, Object> ent : fields.entrySet()) {
fieldsSimple.add(ent.getKey(), ent.getValue());
}
finfo.add("fields", fieldsSimple);
SimpleOrderedMap<Object> dynamicSimple = new SimpleOrderedMap<Object>();
for (Map.Entry<String, Object> ent : dynamicFields.entrySet()) {
dynamicSimple.add(ent.getKey(), ent.getValue());
}
finfo.add("dynamicFields", dynamicSimple);
finfo.add("uniqueKeyField",
null == uniqueField ? null : uniqueField.getName());
finfo.add("defaultSearchField", schema.getDefaultSearchFieldName());
finfo.add("types", types);
return finfo;
}
private static SimpleOrderedMap<Object> getAnalyzerInfo(Analyzer analyzer) {
SimpleOrderedMap<Object> aninfo = new SimpleOrderedMap<Object>();
aninfo.add("className", analyzer.getClass().getName());
if (analyzer instanceof TokenizerChain) {
TokenizerChain tchain = (TokenizerChain)analyzer;
CharFilterFactory[] cfiltfacs = tchain.getCharFilterFactories();
SimpleOrderedMap<Map<String, Object>> cfilters = new SimpleOrderedMap<Map<String, Object>>();
for (CharFilterFactory cfiltfac : cfiltfacs) {
Map<String, Object> tok = new HashMap<String, Object>();
String className = cfiltfac.getClass().getName();
tok.put("className", className);
tok.put("args", cfiltfac.getArgs());
cfilters.add(className.substring(className.lastIndexOf('.')+1), tok);
}
if (cfilters.size() > 0) {
aninfo.add("charFilters", cfilters);
}
SimpleOrderedMap<Object> tokenizer = new SimpleOrderedMap<Object>();
TokenizerFactory tfac = tchain.getTokenizerFactory();
tokenizer.add("className", tfac.getClass().getName());
tokenizer.add("args", tfac.getArgs());
aninfo.add("tokenizer", tokenizer);
TokenFilterFactory[] filtfacs = tchain.getTokenFilterFactories();
SimpleOrderedMap<Map<String, Object>> filters = new SimpleOrderedMap<Map<String, Object>>();
for (TokenFilterFactory filtfac : filtfacs) {
Map<String, Object> tok = new HashMap<String, Object>();
String className = filtfac.getClass().getName();
tok.put("className", className);
tok.put("args", filtfac.getArgs());
filters.add(className.substring(className.lastIndexOf('.')+1), tok);
}
if (filters.size() > 0) {
aninfo.add("filters", filters);
}
}
return aninfo;
}
private static void populateFieldInfo(IndexSchema schema,
Map<String, List<String>> typeusemap, Map<String, Object> fields,
SchemaField uniqueField, SchemaField f) {
FieldType ft = f.getType();
SimpleOrderedMap<Object> field = new SimpleOrderedMap<Object>();
field.add( "type", ft.getTypeName() );
field.add( "flags", getFieldFlags(f) );
if( f.isRequired() ) {
field.add( "required", f.isRequired() );
}
if( f.getDefaultValue() != null ) {
field.add( "default", f.getDefaultValue() );
}
if (f == uniqueField){
field.add("uniqueKey", true);
}
if (ft.getAnalyzer().getPositionIncrementGap(f.getName()) != 0) {
field.add("positionIncrementGap", ft.getAnalyzer().getPositionIncrementGap(f.getName()));
}
field.add("copyDests", schema.getCopyFieldsList(f.getName()));
field.add("copySources", schema.getCopySources(f.getName()));
fields.put( f.getName(), field );
List<String> v = typeusemap.get( ft.getTypeName() );
if( v == null ) {
v = new ArrayList<String>();
}
v.add( f.getName() );
typeusemap.put( ft.getTypeName(), v );
}
/**
* @deprecated use {@link #getIndexInfo(DirectoryReader)} since you now have to explicitly pass the "fl" prameter
* and this was always called with "false" anyway from CoreAdminHandler
*/
public static SimpleOrderedMap<Object> getIndexInfo(DirectoryReader reader, boolean detail) throws IOException {
return getIndexInfo(reader);
}
// This method just gets the top-most level of information. This was conflated with getting detailed info
// for *all* the fields, called from CoreAdminHandler etc.
public static SimpleOrderedMap<Object> getIndexInfo(DirectoryReader reader) throws IOException {
Directory dir = reader.directory();
SimpleOrderedMap<Object> indexInfo = new SimpleOrderedMap<Object>();
indexInfo.add("numDocs", reader.numDocs());
indexInfo.add("maxDoc", reader.maxDoc());
indexInfo.add("version", reader.getVersion()); // TODO? Is this different then: IndexReader.getCurrentVersion( dir )?
indexInfo.add("segmentCount", reader.getSequentialSubReaders().length);
indexInfo.add("current", reader.isCurrent() );
indexInfo.add("hasDeletions", reader.hasDeletions() );
indexInfo.add("directory", dir );
indexInfo.add("userData", reader.getIndexCommit().getUserData());
String s = reader.getIndexCommit().getUserData().get(SolrIndexWriter.COMMIT_TIME_MSEC_KEY);
if (s != null) {
indexInfo.add("lastModified", new Date(Long.parseLong(s)));
}
return indexInfo;
}
// Get terribly detailed information about a particular field. This is a very expensive call, use it with caution
// especially on large indexes!
private static void getDetailedFieldInfo(SolrQueryRequest req, String field, SimpleOrderedMap<Object> fieldMap)
throws IOException {
SolrParams params = req.getParams();
int numTerms = params.getInt( NUMTERMS, DEFAULT_COUNT );
TopTermQueue tiq = new TopTermQueue(numTerms + 1); // Something to collect the top N terms in.
final CharsRef spare = new CharsRef();
Fields fields = MultiFields.getFields(req.getSearcher().getIndexReader());
if (fields == null) { // No indexed fields
return;
}
Terms terms = fields.terms(field);
if (terms == null) { // No terms in the field.
return;
}
TermsEnum termsEnum = terms.iterator(null);
BytesRef text;
int[] buckets = new int[HIST_ARRAY_SIZE];
while ((text = termsEnum.next()) != null) {
int freq = termsEnum.docFreq(); // This calculation seems odd, but it gives the same results as it used to.
int slot = 32 - Integer.numberOfLeadingZeros(Math.max(0, freq - 1));
buckets[slot] = buckets[slot] + 1;
if (freq > tiq.minFreq) {
UnicodeUtil.UTF8toUTF16(text, spare);
String t = spare.toString();
tiq.distinctTerms = new Long(terms.size()).intValue();
tiq.add(new TopTermQueue.TermInfo(new Term(field, t), termsEnum.docFreq()));
if (tiq.size() > numTerms) { // if tiq full
tiq.pop(); // remove lowest in tiq
tiq.minFreq = tiq.getTopTermInfo().docFreq;
}
}
}
tiq.histogram.add(buckets);
fieldMap.add("distinct", tiq.distinctTerms);
// Include top terms
fieldMap.add("topTerms", tiq.toNamedList(req.getSearcher().getSchema()));
// Add a histogram
fieldMap.add("histogram", tiq.histogram.toNamedList());
}
//////////////////////// SolrInfoMBeans methods //////////////////////
@Override
public String getDescription() {
return "Lucene Index Browser. Inspired and modeled after Luke: http://www.getopt.org/luke/";
}
@Override
public String getSource() {
return "$URL$";
}
@Override
public URL[] getDocs() {
try {
return new URL[] { new URL("http://wiki.apache.org/solr/LukeRequestHandler") };
}
catch( MalformedURLException ex ) { return null; }
}
///////////////////////////////////////////////////////////////////////////////////////
static class TermHistogram
{
int _maxBucket = -1;
int _buckets[] = new int[HIST_ARRAY_SIZE];
public void add(int[] buckets) {
for (int idx = 0; idx < buckets.length; ++idx) {
if (buckets[idx] != 0) _maxBucket = idx;
}
for (int idx = 0; idx <= _maxBucket; ++idx) {
_buckets[idx] = buckets[idx];
}
}
// TODO? should this be a list or a map?
public NamedList<Integer> toNamedList()
{
NamedList<Integer> nl = new NamedList<Integer>();
for( int bucket = 0; bucket <= _maxBucket; bucket++ ) {
nl.add( ""+ (1 << bucket), _buckets[bucket] );
}
return nl;
}
}
/**
* Private internal class that counts up frequent terms
*/
private static class TopTermQueue extends PriorityQueue
{
static class TermInfo {
TermInfo(Term t, int df) {
term = t;
docFreq = df;
}
int docFreq;
Term term;
}
public int minFreq = 0;
public int distinctTerms = 0;
public TermHistogram histogram;
TopTermQueue(int size) {
super(size);
histogram = new TermHistogram();
}
@Override
protected final boolean lessThan(Object a, Object b) {
TermInfo termInfoA = (TermInfo)a;
TermInfo termInfoB = (TermInfo)b;
return termInfoA.docFreq < termInfoB.docFreq;
}
/**
* This is a destructive call... the queue is empty at the end
*/
public NamedList<Integer> toNamedList( IndexSchema schema )
{
// reverse the list..
List<TermInfo> aslist = new LinkedList<TermInfo>();
while( size() > 0 ) {
aslist.add( 0, (TermInfo)pop() );
}
NamedList<Integer> list = new NamedList<Integer>();
for (TermInfo i : aslist) {
String txt = i.term.text();
SchemaField ft = schema.getFieldOrNull( i.term.field() );
if( ft != null ) {
txt = ft.getType().indexedToReadable( txt );
}
list.add( txt, i.docFreq );
}
return list;
}
public TermInfo getTopTermInfo() {
return (TermInfo)top();
}
}
}
| remove comments about Luke XSLT
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1327414 13f79535-47bb-0310-9956-ffa450edef68
| solr/core/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java | remove comments about Luke XSLT | <ide><path>olr/core/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java
<ide> * This handler exposes the internal lucene index. It is inspired by and
<ide> * modeled on Luke, the Lucene Index Browser by Andrzej Bialecki.
<ide> * http://www.getopt.org/luke/
<del> * <p>
<del> * NOTE: the response format is still likely to change. It should be designed so
<del> * that it works nicely with an XSLT transformation. Until we have a nice
<del> * XSLT front end for /admin, the format is still open to change.
<del> * </p>
<ide> *
<ide> * For more documentation see:
<ide> * http://wiki.apache.org/solr/LukeRequestHandler
<del> *
<ide> *
<ide> * @since solr 1.2
<ide> */
<ide> return finfo;
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<ide> private static SimpleOrderedMap<Object> getIndexedFieldsInfo(SolrQueryRequest req)
<ide> throws Exception {
<ide>
<ide>
<ide> // Get terribly detailed information about a particular field. This is a very expensive call, use it with caution
<ide> // especially on large indexes!
<add> @SuppressWarnings("unchecked")
<ide> private static void getDetailedFieldInfo(SolrQueryRequest req, String field, SimpleOrderedMap<Object> fieldMap)
<ide> throws IOException {
<ide> |
|
Java | apache-2.0 | e07b1a4698b6d684999bd3f19769c224e5e147a0 | 0 | facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho | /**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho.processor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.facebook.common.internal.ImmutableList;
import com.facebook.litho.annotations.Event;
import com.facebook.litho.annotations.FromEvent;
import com.facebook.litho.annotations.OnCreateInitialState;
import com.facebook.litho.annotations.OnCreateTreeProp;
import com.facebook.litho.annotations.OnEvent;
import com.facebook.litho.annotations.OnLoadStyle;
import com.facebook.litho.annotations.OnUpdateState;
import com.facebook.litho.annotations.Param;
import com.facebook.litho.annotations.Prop;
import com.facebook.litho.annotations.PropDefault;
import com.facebook.litho.annotations.ResType;
import com.facebook.litho.annotations.State;
import com.facebook.litho.annotations.TreeProp;
import com.facebook.litho.javapoet.JPUtil;
import com.facebook.litho.processor.GetTreePropsForChildrenMethodBuilder.CreateTreePropMethodData;
import com.facebook.litho.specmodels.model.ClassNames;
import com.facebook.litho.specmodels.model.PropDefaultModel;
import com.facebook.litho.specmodels.processor.PropDefaultsExtractor;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import com.squareup.javapoet.WildcardTypeName;
import static com.facebook.litho.processor.Utils.capitalize;
import static com.facebook.litho.processor.Visibility.PRIVATE;
import static com.facebook.litho.specmodels.generator.GeneratorConstants.DELEGATE_FIELD_NAME;
import static com.facebook.litho.specmodels.generator.GeneratorConstants.SPEC_INSTANCE_NAME;
import static java.util.Arrays.asList;
import static javax.lang.model.type.TypeKind.ARRAY;
import static javax.lang.model.type.TypeKind.DECLARED;
import static javax.lang.model.type.TypeKind.DOUBLE;
import static javax.lang.model.type.TypeKind.FLOAT;
import static javax.lang.model.type.TypeKind.TYPEVAR;
import static javax.lang.model.type.TypeKind.VOID;
public class Stages {
public static final String IMPL_CLASS_NAME_SUFFIX = "Impl";
private static final String INNER_IMPL_BUILDER_CLASS_NAME = "Builder";
private static final String STATE_UPDATE_IMPL_NAME_SUFFIX = "StateUpdate";
public static final String STATE_CONTAINER_IMPL_NAME_SUFFIX = "StateContainerImpl";
public static final String STATE_CONTAINER_IMPL_MEMBER = "mStateContainerImpl";
private static final String REQUIRED_PROPS_NAMES = "REQUIRED_PROPS_NAMES";
private static final String REQUIRED_PROPS_COUNT = "REQUIRED_PROPS_COUNT";
private static final int ON_STYLE_PROPS = 1;
private static final int ON_CREATE_INITIAL_STATE = 1;
private final boolean mSupportState;
public enum StaticFlag {
STATIC,
NOT_STATIC
}
public enum StyleableFlag {
STYLEABLE,
NOT_STYLEABLE
}
// Using these names in props might cause conflicts with the method names in the
// component's generated layout builder class so we trigger a more user-friendly
// error if the component tries to use them. This list should be kept in sync
// with BaseLayoutBuilder.
private static final String[] RESERVED_PROP_NAMES = new String[] {
"withLayout",
"key",
"loadingEventHandler",
};
private static final Class<Annotation>[] TREE_PROP_ANNOTATIONS = new Class[] {
TreeProp.class,
};
private static final Class<Annotation>[] PROP_ANNOTATIONS = new Class[] {
Prop.class,
};
private static final Class<Annotation>[] STATE_ANNOTATIONS = new Class[] {
State.class,
};
private final ProcessingEnvironment mProcessingEnv;
private final TypeElement mSourceElement;
private final String mQualifiedClassName;
private final Class<Annotation>[] mStageAnnotations;
private final Class<Annotation>[] mInterStagePropAnnotations;
private final Class<Annotation>[] mParameterAnnotations;
private final TypeSpec.Builder mClassTypeSpec;
private final List<TypeVariableName> mTypeVariables;
private final List<TypeElement> mEventDeclarations;
private final Map<String, String> mPropJavadocs;
private final String mSimpleClassName;
private String mSourceDelegateAccessorName = DELEGATE_FIELD_NAME;
private List<VariableElement> mProps;
private List<VariableElement> mOnCreateInitialStateDefinedProps;
private ImmutableList<PropDefaultModel> mPropDefaults;
private List<VariableElement> mTreeProps;
private final Map<String, VariableElement> mStateMap = new LinkedHashMap<>();
// Map of name to VariableElement, for members of the inner implementation class, in order
private LinkedHashMap<String, VariableElement> mImplMembers;
private List<Parameter> mImplParameters;
private final Map<String, TypeMirror> mExtraStateMembers;
// List of methods that have @OnEvent on it.
private final List<ExecutableElement> mOnEventMethods;
// List of methods annotated with @OnUpdateState.
private final List<ExecutableElement> mOnUpdateStateMethods;
private final List<ExecutableElement> mOnCreateTreePropsMethods;
// List of methods that define stages (e.g. OnCreateLayout)
private List<ExecutableElement> mStages;
public TypeElement getSourceElement() {
return mSourceElement;
}
public Stages(
ProcessingEnvironment processingEnv,
TypeElement sourceElement,
String qualifiedClassName,
Class<Annotation>[] stageAnnotations,
Class<Annotation>[] interStagePropAnnotations,
TypeSpec.Builder typeSpec,
List<TypeVariableName> typeVariables,
boolean supportState,
Map<String, TypeMirror> extraStateMembers,
List<TypeElement> eventDeclarations,
Map<String, String> propJavadocs) {
mProcessingEnv = processingEnv;
mSourceElement = sourceElement;
mQualifiedClassName = qualifiedClassName;
mStageAnnotations = stageAnnotations;
mInterStagePropAnnotations = interStagePropAnnotations;
mClassTypeSpec = typeSpec;
mTypeVariables = typeVariables;
mEventDeclarations = eventDeclarations;
mPropJavadocs = propJavadocs;
final List<Class<Annotation>> parameterAnnotations = new ArrayList<>();
parameterAnnotations.addAll(asList(PROP_ANNOTATIONS));
parameterAnnotations.addAll(asList(STATE_ANNOTATIONS));
parameterAnnotations.addAll(asList(mInterStagePropAnnotations));
parameterAnnotations.addAll(asList(TREE_PROP_ANNOTATIONS));
mParameterAnnotations = parameterAnnotations.toArray(
new Class[parameterAnnotations.size()]);
mSupportState = supportState;
mSimpleClassName = Utils.getSimpleClassName(mQualifiedClassName);
mOnEventMethods = Utils.getAnnotatedMethods(mSourceElement, OnEvent.class);
mOnUpdateStateMethods = Utils.getAnnotatedMethods(mSourceElement, OnUpdateState.class);
mOnCreateTreePropsMethods = Utils.getAnnotatedMethods(mSourceElement, OnCreateTreeProp.class);
mExtraStateMembers = extraStateMembers;
validateOnEventMethods();
populatePropDefaults();
populateStages();
validateAnnotatedParameters();
populateOnCreateInitialStateDefinedProps();
populateProps();
populateTreeProps();
if (mSupportState) {
populateStateMap();
}
validatePropDefaults();
populateImplMembers();
populateImplParameters();
validateStyleOutputs();
}
private boolean isInterStagePropAnnotationValidInStage(
Class<? extends Annotation> interStageProp,
Class<? extends Annotation> stage) {
final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp);
final int stageIndex = asList(mStageAnnotations).indexOf(stage);
if (interStagePropIndex < 0 || stageIndex < 0) {
throw new IllegalArgumentException(); // indicates bug in the annotation processor
}
// This logic relies on the fact that there are prop annotations for each stage (except for
// some number at the end)
return interStagePropIndex < stageIndex;
}
private boolean doesInterStagePropAnnotationMatchStage(
Class<? extends Annotation> interStageProp,
Class<? extends Annotation> stage) {
final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp);
// Null stage is allowed and indicates prop
int stageIndex = -1;
if (stage != null) {
stageIndex = asList(mStageAnnotations).indexOf(stage);
if (interStagePropIndex < 0 || stageIndex < 0) {
throw new IllegalArgumentException(); // indicates bug in the annotation processor
}
}
return interStagePropIndex == stageIndex;
}
private void validateOnEventMethods() {
final Map<String, Boolean> existsMap = new HashMap<>();
for (ExecutableElement element : mOnEventMethods) {
if (existsMap.containsKey(element.getSimpleName().toString())) {
throw new ComponentsProcessingException(
element,
"@OnEvent declared methods must have unique names");
}
final DeclaredType eventClass = Utils.getAnnotationParameter(
mProcessingEnv,
element,
OnEvent.class,
"value");
final TypeMirror returnType = Utils.getAnnotationParameter(
mProcessingEnv,
eventClass.asElement(),
Event.class,
"returnType");
if (!mProcessingEnv.getTypeUtils().isSameType(element.getReturnType(), returnType)) {
throw new ComponentsProcessingException(
element,
"Method " + element.getSimpleName() + " must return " + returnType +
", since that is what " + eventClass + " expects.");
}
final List<? extends VariableElement> parameters =
Utils.getEnclosedFields((TypeElement) eventClass.asElement());
for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) {
boolean hasMatchingParameter = false;
for (VariableElement parameter : parameters) {
if (parameter.getSimpleName().equals(v.getSimpleName()) &&
parameter.asType().toString().equals(v.asType().toString())) {
hasMatchingParameter = true;
break;
}
}
if (!hasMatchingParameter) {
throw new ComponentsProcessingException(
v,
v.getSimpleName() + " of this type is not a member of " +
eventClass);
}
return;
}
existsMap.put(element.getSimpleName().toString(), true);
}
}
/**
* Ensures that the declared events don't clash with the predefined ones.
*/
private void validateEventDeclarations() {
for (TypeElement eventDeclaration : mEventDeclarations) {
final Event eventAnnotation = eventDeclaration.getAnnotation(Event.class);
if (eventAnnotation == null) {
throw new ComponentsProcessingException(
eventDeclaration,
"Events must be declared with the @Event annotation, event is: " + eventDeclaration);
}
final List<? extends VariableElement> fields = Utils.getEnclosedFields(eventDeclaration);
for (VariableElement field : fields) {
if (!field.getModifiers().contains(Modifier.PUBLIC) ||
field.getModifiers().contains(Modifier.FINAL)) {
throw new ComponentsProcessingException(
field,
"Event fields must be declared as public non-final");
}
}
}
}
private void validateStyleOutputs() {
final ExecutableElement delegateMethod = Utils.getAnnotatedMethod(
mSourceElement,
OnLoadStyle.class);
if (delegateMethod == null) {
return;
}
final List<? extends VariableElement> parameters = delegateMethod.getParameters();
if (parameters.size() < ON_STYLE_PROPS) {
throw new ComponentsProcessingException(
delegateMethod,
"The @OnLoadStyle method should have an ComponentContext" +
"followed by Output parameters matching component create.");
}
final TypeName firstParamType = ClassName.get(parameters.get(0).asType());
if (!firstParamType.equals(ClassNames.COMPONENT_CONTEXT)) {
throw new ComponentsProcessingException(
parameters.get(0),
"The first argument of the @OnLoadStyle method should be an ComponentContext.");
}
for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) {
final VariableElement v = parameters.get(i);
final TypeMirror outputType = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT);
if (outputType == null) {
throw new ComponentsProcessingException(
parameters.get(i),
"The @OnLoadStyle method should have only have Output arguments matching " +
"component create.");
}
final Types typeUtils = mProcessingEnv.getTypeUtils();
final String name = v.getSimpleName().toString();
boolean matchesProp = false;
for (Element prop : mProps) {
if (!prop.getSimpleName().toString().equals(name)) {
continue;
}
matchesProp = true;
if (!typeUtils.isAssignable(prop.asType(), outputType)) {
throw new ComponentsProcessingException(
v,
"Searching for prop \"" + name + "\" of type " + ClassName.get(outputType) +
" but found prop with the same name of type " +
ClassName.get(prop.asType()));
}
}
if (!matchesProp) {
throw new ComponentsProcessingException(
v,
"Output named '" + v.getSimpleName() + "' does not match any prop " +
"in the component.");
}
}
}
/**
* Validate that:
* <ul>
* <li>1. Parameters are consistently typed across stages.</li>
* <li>2. Outputs for the same parameter name aren't duplicated.</li>
* <li>3. Declared inter-stage prop parameters from previous stages (i.e. not
* {@link Prop}) correspond to outputs from that stage</li>
* <li>4. Inter-stage prop parameters come from previous stages. i.e. It is illegal to declare
* a @FromMeasure parameter in @OnInflate</li>
* <li>5. Inter-stage parameters don't have duplicate annotations (and that outputs aren't
* annotated as inter-stage props)</li>
* <li>6. Ensure props don't use reserved words as names.</li>
* <li>7. Ensure required props don't have default values.</li>
* <li>8. Ensure same props are annotated identically</li>
* <li>9. Ensure props are of legal types</li>
* </ul>
*/
private void validateAnnotatedParameters() {
final List<PrintableException> exceptions = new ArrayList<>();
final Map<String, VariableElement> variableNameToElementMap = new HashMap<>();
final Map<String, Class<? extends Annotation>> outputVariableToStage = new HashMap<>();
for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) {
final ExecutableElement stage = Utils.getAnnotatedMethod(
mSourceElement,
stageAnnotation);
if (stage == null) {
continue;
}
// Enforce #5: getSpecDefinedParameters will verify that parameters don't have duplicate
// annotations
for (VariableElement v : getSpecDefinedParameters(stage)) {
try {
final String variableName = v.getSimpleName().toString();
final Annotation interStagePropAnnotation = getInterStagePropAnnotation(v);
final boolean isOutput =
Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT) != null;
if (isOutput) {
outputVariableToStage.put(variableName, stageAnnotation);
}
// Enforce #3
if (interStagePropAnnotation != null) {
final Class<? extends Annotation> outputStage = outputVariableToStage.get(variableName);
if (!doesInterStagePropAnnotationMatchStage(
interStagePropAnnotation.annotationType(), outputStage)) {
throw new ComponentsProcessingException(
v,
"Inter-stage prop declaration is incorrect, the same name and type must be " +
"used in every method where the inter-stage prop is declared.");
}
}
// Enforce #4
if (interStagePropAnnotation != null
&& !isInterStagePropAnnotationValidInStage(
interStagePropAnnotation.annotationType(), stageAnnotation)) {
throw new ComponentsProcessingException(
v,
"Inter-stage create must refer to previous stages.");
}
final VariableElement existingType = variableNameToElementMap.get(variableName);
if (existingType != null && !isSameType(existingType.asType(), v.asType())) {
// We have a type mis-match. This is allowed, provided that the previous type is an
// outputand the new type is an prop, and the type argument of the output matches the
// prop. In the future, we may want to allow stages to modify outputs from previous
// stages, but for now we disallow it.
// Enforce #1 and #2
if ((getInterStagePropAnnotation(v) == null ||
Utils.getGenericTypeArgument(existingType.asType(), ClassNames.OUTPUT) == null) &&
Utils.getGenericTypeArgument(existingType.asType(), ClassNames.DIFF) == null) {
throw new ComponentsProcessingException(
v,
"Inconsistent type for '" + variableName + "': '" + existingType.asType() +
"' and '" + v.asType() + "'");
}
} else if (existingType == null) {
// We haven't see a parameter with this name yet. Therefore it must be either @Prop,
// @State or an output.
final boolean isFromProp = getParameterAnnotation(v, PROP_ANNOTATIONS) != null;
final boolean isFromState = getParameterAnnotation(v, STATE_ANNOTATIONS) != null;
final boolean isFromTreeProp
= getParameterAnnotation(v, TREE_PROP_ANNOTATIONS) != null;
if (isFromState && !mSupportState) {
throw new ComponentsProcessingException(
v,
"State is not supported in this kind of Spec.");
}
if (!isFromProp && !isFromState && !isOutput && !isFromTreeProp) {
throw new ComponentsProcessingException(
v,
"Inter-stage prop declared without source.");
}
}
// Enforce #6
final Prop propAnnotation = v.getAnnotation(Prop.class);
if (propAnnotation != null) {
for (String reservedPropName : RESERVED_PROP_NAMES) {
if (reservedPropName.equals(variableName)) {
throw new ComponentsProcessingException(
v,
"'" + reservedPropName + "' is a reserved prop name used by " +
"the component's layout builder. Please use another name.");
}
}
// Enforce #7
final boolean hasDefaultValue = hasDefaultValue(v);
if (hasDefaultValue && !propAnnotation.optional()) {
throw new ComponentsProcessingException(
v,
"Prop is not optional but has a declared default value.");
}
// Enforce #8
if (existingType != null) {
final Prop existingPropAnnotation = existingType.getAnnotation(Prop.class);
if (existingPropAnnotation != null) {
if (!hasSameAnnotations(v, existingType)) {
throw new ComponentsProcessingException(
v,
"The prop '" + variableName + "' is configured differently for different " +
"methods. Ensure each instance of this prop is declared identically.");
}
}
}
// Enforce #9
TypeName typeName;
try {
typeName = ClassName.get(v.asType());
} catch (IllegalArgumentException e) {
throw new ComponentsProcessingException(
v,
"Prop type does not exist");
}
// Enforce #10
final List<ClassName> illegalPropTypes = Arrays.asList(
ClassNames.COMPONENT_LAYOUT,
ClassNames.COMPONENT_LAYOUT_BUILDER,
ClassNames.COMPONENT_LAYOUT_CONTAINER_BUILDER,
ClassNames.COMPONENT_BUILDER,
ClassNames.COMPONENT_BUILDER_WITH_LAYOUT,
ClassNames.REFERENCE_BUILDER);
if (illegalPropTypes.contains(typeName)) {
throw new ComponentsProcessingException(
v,
"Props may not be declared with the following types:" +
illegalPropTypes);
}
}
variableNameToElementMap.put(variableName, v);
} catch (PrintableException e) {
exceptions.add(e);
}
}
}
if (!exceptions.isEmpty()) {
throw new MultiPrintableException(exceptions);
}
}
private boolean hasSameAnnotations(VariableElement v1, VariableElement v2) {
final List<? extends AnnotationMirror> v1Annotations = v1.getAnnotationMirrors();
final List<? extends AnnotationMirror> v2Annotations = v2.getAnnotationMirrors();
if (v1Annotations.size() != v2Annotations.size()) {
return false;
}
final int count = v1Annotations.size();
for (int i = 0; i < count; i++) {
final AnnotationMirror a1 = v1Annotations.get(i);
final AnnotationMirror a2 = v2Annotations.get(i);
// Some object in this hierarchy don't implement equals correctly.
// They do however produce very nice strings representations which we can compare instead.
if (!a1.toString().equals(a2.toString())) {
return false;
}
}
return true;
}
public void validateStatic() {
validateStaticFields();
validateStaticMethods();
}
private void validateStaticFields() {
for (Element element : mSourceElement.getEnclosedElements()) {
if (element.getKind() == ElementKind.FIELD &&
!element.getModifiers().contains(Modifier.STATIC)) {
throw new ComponentsProcessingException(
element,
"Field " + element.getSimpleName() + " in " + mSourceElement.getQualifiedName() +
" must be static");
}
}
}
private void validateStaticMethods() {
for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) {
final ExecutableElement stage = Utils.getAnnotatedMethod(
mSourceElement,
stageAnnotation);
if (stage != null && !stage.getModifiers().contains(Modifier.STATIC)) {
throw new ComponentsProcessingException(
stage,
"Method " + stage.getSimpleName() + " in " + mSourceElement.getQualifiedName() +
" must be static");
}
}
}
/**
* Gather a list of VariableElement that are the props to this component
*/
private void populateProps() {
// We use a linked hash map to guarantee iteration order
final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>();
for (ExecutableElement stage : mStages) {
for (VariableElement v : getProps(stage)) {
// Validation unnecessary - already handled by validateAnnotatedParameters
final String variableName = v.getSimpleName().toString();
variableNameToElementMap.put(variableName, v);
}
}
mProps = new ArrayList<>(variableNameToElementMap.values());
addCreateInitialStateDefinedProps(mProps);
}
/**
* Gather a list of VariableElement that are the state to this component
*/
private void populateStateMap() {
// We use a linked hash map to guarantee iteration order
final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>();
for (ExecutableElement stage : mStages) {
for (VariableElement v : getState(stage)) {
final String variableName = v.getSimpleName().toString();
if (mStateMap.containsKey(variableName)) {
VariableElement existingType = mStateMap.get(variableName);
final State existingPropAnnotation = existingType.getAnnotation(State.class);
if (existingPropAnnotation != null) {
if (!hasSameAnnotations(v, existingType)) {
throw new ComponentsProcessingException(
v,
"The state '" + variableName + "' is configured differently for different " +
"methods. Ensure each instance of this state is declared identically.");
}
}
}
mStateMap.put(
variableName,
v);
}
}
}
private void populateTreeProps() {
final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>();
for (ExecutableElement stage : mStages) {
for (VariableElement v : Utils.getParametersWithAnnotation(stage, TreeProp.class)) {
final String variableName = v.getSimpleName().toString();
variableNameToElementMap.put(variableName, v);
}
}
mTreeProps = new ArrayList<>(variableNameToElementMap.values());
}
/**
* Get the list of stages (OnInflate, OnMeasure, OnMount) that are defined for this component.
*/
private void populateStages() {
mStages = new ArrayList<>();
for (Class<Annotation> stageAnnotation : mStageAnnotations) {
final ExecutableElement stage = Utils.getAnnotatedMethod(
mSourceElement,
stageAnnotation);
if (stage != null) {
mStages.add(stage);
}
}
if (mOnEventMethods != null) {
mStages.addAll(mOnEventMethods);
}
mStages.addAll(mOnCreateTreePropsMethods);
}
/**
* @param prop The prop to determine if it has a default or not.
* @return Returns true if the prop has a default, false otherwise.
*/
private boolean hasDefaultValue(VariableElement prop) {
final String name = prop.getSimpleName().toString();
final TypeName type = TypeName.get(prop.asType());
for (PropDefaultModel propDefault : mPropDefaults) {
if (propDefault.mName.equals(name) && propDefault.mType.equals(type)) {
return true;
}
}
return false;
}
/**
* Fail if any elements that exist in mPropDefaults do not exist in mProps.
*/
private void validatePropDefaults() {
for (PropDefaultModel propDefault : mPropDefaults) {
final ImmutableList<Modifier> modifiers = propDefault.mModifiers;
if (!modifiers.contains(Modifier.STATIC)
|| !modifiers.contains(Modifier.FINAL)
|| modifiers.contains(Modifier.PRIVATE)) {
throw new RuntimeException(
"Defaults for props (fields annotated with " + PropDefault.class + ") must be " +
"non-private, static, and final. This is not the case for " + propDefault.mName);
}
if (!hasValidNameAndType(propDefault)) {
throw new RuntimeException(
"Prop defaults (fields annotated with " + PropDefault.class + ") should have the " +
"same name and type as the prop that they set the default for. This is not the " +
"case for " + propDefault.mName);
}
}
}
/**
* @return true if the given prop default matches the name and type of a prop, false otherwise.
*/
private boolean hasValidNameAndType(PropDefaultModel propDefault) {
for (VariableElement prop : mProps) {
if (prop.getSimpleName().toString().equals(propDefault.mName)
&& TypeName.get(prop.asType()).equals(propDefault.mType)) {
return true;
}
}
return false;
}
/**
* Gather a list of parameters from the given element that are props to this component.
*/
private static List<VariableElement> getProps(ExecutableElement element) {
return Utils.getParametersWithAnnotation(element, Prop.class);
}
/**
* Gather a list of parameters from the given element that are state to this component.
*/
private static List<VariableElement> getState(ExecutableElement element) {
return Utils.getParametersWithAnnotation(element, State.class);
}
/**
* Gather a list of parameters from the given element that are defined by the spec. That is, they
* aren't one of the parameters predefined for a given method. For example, OnCreateLayout has a
* predefined parameter of type LayoutContext. Spec-defined parameters are annotated with one of
* our prop annotations or are of type {@link com.facebook.litho.Output}.
*/
private List<VariableElement> getSpecDefinedParameters(ExecutableElement element) {
return getSpecDefinedParameters(element, true);
}
private List<VariableElement> getSpecDefinedParameters(
ExecutableElement element,
boolean shouldIncludeOutputs) {
final ArrayList<VariableElement> specDefinedParameters = new ArrayList<>();
for (VariableElement v : element.getParameters()) {
final boolean isAnnotatedParameter = getParameterAnnotation(v) != null;
final boolean isInterStageOutput = Utils.getGenericTypeArgument(
v.asType(),
ClassNames.OUTPUT) != null;
if (isAnnotatedParameter && isInterStageOutput) {
throw new ComponentsProcessingException(
v,
"Variables that are both prop and output are forbidden.");
} else if (isAnnotatedParameter || (shouldIncludeOutputs && isInterStageOutput)) {
specDefinedParameters.add(v);
}
}
return specDefinedParameters;
}
private void populateOnCreateInitialStateDefinedProps() {
final ExecutableElement onCreateInitialState = Utils.getAnnotatedMethod(
getSourceElement(),
OnCreateInitialState.class);
if (onCreateInitialState == null) {
mOnCreateInitialStateDefinedProps = new ArrayList<>();
} else {
mOnCreateInitialStateDefinedProps = getSpecDefinedParameters(onCreateInitialState, false);
}
}
/**
* Get the @FromLayout, @FromMeasure, etc annotation on this element (@Prop isn't
* considered - use getParameterAnnotation if you want to consider them)
*/
private Annotation getInterStagePropAnnotation(VariableElement element) {
return getParameterAnnotation(element, mInterStagePropAnnotations);
}
/**
* Get the annotation, if any, present on a parameter. Annotations are restricted to our whitelist
* of parameter annotations: e.g. {@link Prop}, {@link State} etc)
*/
private Annotation getParameterAnnotation(VariableElement element) {
return getParameterAnnotation(element, mParameterAnnotations);
}
/**
* Get the annotation, if any, present on a parameter. Annotations are restricted to the specified
* whitelist. If there is a duplicate we will issue an error.
*/
private Annotation getParameterAnnotation(
VariableElement element,
Class<Annotation>[] possibleAnnotations) {
final ArrayList<Annotation> annotations = new ArrayList<>();
for (Class<Annotation> annotationClass : possibleAnnotations) {
final Annotation annotation = element.getAnnotation(annotationClass);
if (annotation != null) {
annotations.add(annotation);
}
}
if (annotations.isEmpty()) {
return null;
} else if (annotations.size() == 1) {
return annotations.get(0);
} else {
throw new ComponentsProcessingException(
element,
"Duplicate parameter annotation: '" + annotations.get(0) + "' and '" +
annotations.get(1) + "'");
}
}
/**
* Generate javadoc block describing component props.
*/
public void generateJavadoc() {
for (VariableElement v : mProps) {
final Prop propAnnotation = v.getAnnotation(Prop.class);
final String propTag = propAnnotation.optional() ? "@prop-optional" : "@prop-required";
final String javadoc =
mPropJavadocs != null ? mPropJavadocs.get(v.getSimpleName().toString()) : "";
final String sanitizedJavadoc =
javadoc != null ? javadoc.replace('\n', ' ') : null;
// Adds javadoc with following format:
// @prop-required name type javadoc.
// This can be changed later to use clear demarcation for fields.
// This is a block tag and cannot support inline tags like "{@link something}".
mClassTypeSpec.addJavadoc(
"$L $L $L $L\n",
propTag,
v.getSimpleName().toString(),
Utils.getTypeName(v.asType()),
sanitizedJavadoc);
}
}
/**
* Generate a method for this component which either lazily instantiates a singleton reference or
* return this depending on whether this lifecycle is static or not.
*/
public void generateGetter(boolean isStatic) {
final ClassName className = ClassName.bestGuess(mQualifiedClassName);
if (isStatic) {
mClassTypeSpec.addField(
FieldSpec
.builder(className, SPEC_INSTANCE_NAME, Modifier.PRIVATE, Modifier.STATIC)
.initializer("null")
.build());
mClassTypeSpec.addMethod(
MethodSpec.methodBuilder("get")
.addModifiers(Modifier.PUBLIC)
.addModifiers(Modifier.STATIC)
.addModifiers(Modifier.SYNCHRONIZED)
.returns(className)
.beginControlFlow("if ($L == null)", SPEC_INSTANCE_NAME)
.addStatement("$L = new $T()", SPEC_INSTANCE_NAME, className)
.endControlFlow()
.addStatement("return $L", SPEC_INSTANCE_NAME)
.build());
} else {
mClassTypeSpec.addMethod(
MethodSpec.methodBuilder("get")
.addModifiers(Modifier.PUBLIC)
.returns(className)
.addStatement("return this")
.build());
}
}
public void generateSourceDelegate(boolean initialized) {
final ClassName specClassName = ClassName.get(mSourceElement);
generateSourceDelegate(initialized, specClassName);
}
public void generateSourceDelegate(boolean initialized, TypeName specTypeName) {
final FieldSpec.Builder builder = FieldSpec
.builder(specTypeName, DELEGATE_FIELD_NAME)
.addModifiers(Modifier.PRIVATE);
if (initialized) {
builder.initializer("new $T()", specTypeName);
}
mClassTypeSpec.addField(builder.build());
}
private MethodSpec generateMakeShallowCopy(ClassName componentClassName, boolean hasDeepCopy) {
final List<String> componentsInImpl = findComponentsInImpl(componentClassName);
final List<String> interStageComponentVariables = getInterStageVariableNames();
if (componentsInImpl.isEmpty() &&
interStageComponentVariables.isEmpty() &&
mOnUpdateStateMethods.isEmpty()) {
return null;
}
final String implClassName = getImplClassName();
return new ShallowCopyMethodSpecBuilder()
.componentsInImpl(componentsInImpl)
.interStageVariables(interStageComponentVariables)
.implClassName(implClassName)
.hasDeepCopy(hasDeepCopy)
.stateContainerImplClassName(getStateContainerImplClassName())
.build();
}
private List<String> findComponentsInImpl(ClassName listComponent) {
final List<String> componentsInImpl = new ArrayList<>();
for (String key : mImplMembers.keySet()) {
final VariableElement element = mImplMembers.get(key);
final Name declaredClassName = Utils.getDeclaredClassNameWithoutGenerics(element);
if (declaredClassName != null &&
ClassName.bestGuess(declaredClassName.toString()).equals(listComponent)) {
componentsInImpl.add(element.getSimpleName().toString());
}
}
return componentsInImpl;
}
/**
* Generate a private constructor to enforce singleton-ity.
*/
public void generateConstructor() {
mClassTypeSpec.addMethod(
MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.build());
}
/**
* Generates a method to create the initial values for parameters annotated with {@link State}.
* This method also validates that the delegate method only tries to assign an initial value to
* State annotated parameters.
*/
public void generateCreateInitialState(
ExecutableElement from,
ClassName contextClass,
ClassName componentClass) {
verifyParametersForCreateInitialState(contextClass, from);
final MethodDescription methodDescription = new MethodDescription();
methodDescription.annotations = new Class[] { Override.class };
methodDescription.accessType = Modifier.PROTECTED;
methodDescription.returnType = null;
methodDescription.name = "createInitialState";
methodDescription.parameterTypes = new TypeName[] {contextClass};
generateDelegate(methodDescription, from, componentClass);
}
private void verifyParametersForCreateInitialState(
ClassName contextClass,
ExecutableElement executableElement) {
final List<VariableElement> parameters =
(List<VariableElement>) executableElement.getParameters();
if (parameters.size() < ON_CREATE_INITIAL_STATE + 1) {
throw new ComponentsProcessingException(
executableElement,
"The @OnCreateInitialState method should have an " + contextClass +
"followed by Output parameters matching state parameters.");
}
final TypeName firstParamType = ClassName.get(parameters.get(0).asType());
if (!firstParamType.equals(contextClass)) {
throw new ComponentsProcessingException(
parameters.get(0),
"The first argument of the @OnCreateInitialState method should be an " +
contextClass + ".");
}
for (int i = ON_CREATE_INITIAL_STATE, size = parameters.size(); i < size; i++) {
final VariableElement element = parameters.get(i);
final TypeMirror elementInnerClassType =
Utils.getGenericTypeArgument(element.asType(), ClassNames.OUTPUT);
if (elementInnerClassType != null) {
final String paramName = element.getSimpleName().toString();
VariableElement implParameter = mStateMap.get(paramName);
if (implParameter == null || implParameter.getAnnotation(State.class) == null) {
throw new ComponentsProcessingException(
executableElement,
"Only parameters annotated with @State can be initialized in @OnCreateInitialState," +
" parameter without annotation is: " + paramName);
}
}
}
}
/**
* Generate a method implementation that delegates to another method that takes annotated props.
*
* @param from description of method signature to be generated
* @param to method to which to delegate
* @param propsClass Component / Delegate. The base class of the inner implementation object
* @throws java.io.IOException If one of the writer methods throw
*/
public void generateDelegate(
MethodDescription from,
ExecutableElement to,
ClassName propsClass) {
generateDelegate(
from,
to,
Collections.<TypeName>emptyList(),
Collections.<String, String>emptyMap(),
propsClass);
}
public void generateDelegate(
MethodDescription from,
ExecutableElement to,
List<TypeName> expectedTypes,
ClassName propsClass) {
generateDelegate(
from,
to,
expectedTypes,
Collections.<String, String>emptyMap(),
propsClass);
}
/**
* Generate a method implementation that delegates to another method that takes annotated props.
*
* @param from description of method signature to be generated
* @param to method to which to delegate
* @param propsClass Component / Delegate. The base class of the inner implementation object
* @throws java.io.IOException If one of the writer methods throw
*/
public void generateDelegate(
MethodDescription from,
ExecutableElement to,
List<TypeName> expectedTypes,
Map<String, String> parameterTranslation,
ClassName propsClass) {
final Visibility visibility;
if (Arrays.asList(from.accessType).contains(Modifier.PRIVATE)) {
visibility = Visibility.PRIVATE;
} else if (Arrays.asList(from.accessType).contains(Modifier.PROTECTED)) {
visibility = Visibility.PROTECTED;
} else if (Arrays.asList(from.accessType).contains(Modifier.PUBLIC)) {
visibility = Visibility.PUBLIC;
} else {
visibility = Visibility.PACKAGE;
}
final List<Parameter> toParams = getParams(to);
final List<Parameter> fromParams = new ArrayList<>();
for (int i = 0; i < from.parameterTypes.length; i++) {
fromParams.add(new Parameter(from.parameterTypes[i], toParams.get(i).name));
}
final List<PrintableException> errors = new ArrayList<>();
for (int i = 0; i < expectedTypes.size(); i++) {
if (!toParams.get(i).type.equals(expectedTypes.get(i))) {
errors.add(new ComponentsProcessingException(
to.getParameters().get(i),
"Expected " + expectedTypes.get(i)));
}
}
if (!errors.isEmpty()) {
throw new MultiPrintableException(errors);
}
writeMethodSpec(new DelegateMethodSpecBuilder()
.implClassName(getImplClassName())
.abstractImplType(propsClass)
.implParameters(mImplParameters)
.checkedExceptions(
from.exceptions == null ?
new ArrayList<TypeName>() :
Arrays.asList(from.exceptions))
.overridesSuper(
from.annotations != null && Arrays.asList(from.annotations).contains(Override.class))
.parameterTranslation(parameterTranslation)
.visibility(visibility)
.fromName(from.name)
.fromReturnType(from.returnType == null ? TypeName.VOID : from.returnType)
.fromParams(fromParams)
.target(mSourceDelegateAccessorName)
.toName(to.getSimpleName().toString())
.stateParams(mStateMap.keySet())
.toReturnType(ClassName.get(to.getReturnType()))
.toParams(toParams)
.build());
}
/**
* Returns {@code true} if the given types match.
*/
public boolean isSameType(TypeMirror a, TypeMirror b) {
return mProcessingEnv.getTypeUtils().isSameType(a, b);
}
/**
* Generate an onEvent implementation that delegates to the @OnEvent-annotated method.
*/
public void generateOnEventHandlers(ClassName componentClassName, ClassName contextClassName) {
for (ExecutableElement element : mOnEventMethods) {
generateOnEventHandler(element, contextClassName);
}
}
/**
* Generate the static methods of the Component that can be called to update its state.
*/
public void generateOnStateUpdateMethods(
ClassName contextClass,
ClassName componentClassName,
ClassName stateContainerClassName,
ClassName stateUpdateInterface,
Stages.StaticFlag staticFlag) {
for (ExecutableElement element : mOnUpdateStateMethods) {
validateOnStateUpdateMethodDeclaration(element);
generateStateUpdateClass(
element,
componentClassName,
stateContainerClassName,
stateUpdateInterface,
staticFlag);
generateOnStateUpdateMethods(element, contextClass, componentClassName);
}
}
/**
* Validate that the declaration of a method annotated with {@link OnUpdateState} is correct:
* <ul>
* <li>1. Method parameters annotated with {@link Param} don't have the same name as parameters
* annotated with {@link State} or {@link Prop}.</li>
* <li>2. Method parameters not annotated with {@link Param} must be of type
* com.facebook.litho.StateValue.</li>
* <li>3. Names of method parameters not annotated with {@link Param} must match the name of
* a parameter annotated with {@link State}.</li>
* <li>4. Type of method parameters not annotated with {@link Param} must match the type of
* a parameter with the same name annotated with {@link State}.</li>
* </ul>
*/
private void validateOnStateUpdateMethodDeclaration(ExecutableElement element) {
final List<VariableElement> annotatedParams =
Utils.getParametersWithAnnotation(element, Param.class);
// Check #1
for (VariableElement annotatedParam : annotatedParams) {
if (mStateMap.get(annotatedParam.getSimpleName().toString()) != null) {
throw new ComponentsProcessingException(
annotatedParam,
"Parameters annotated with @Param should not have the same name as a parameter " +
"annotated with @State or @Prop");
}
}
final List<VariableElement> params = (List<VariableElement>) element.getParameters();
for (VariableElement param : params) {
if (annotatedParams.contains(param)) {
continue;
}
final TypeMirror paramType = param.asType();
// Check #2
if (paramType.getKind() != DECLARED) {
throw new ComponentsProcessingException(
param,
"Parameters not annotated with @Param must be of type " +
"com.facebook.litho.StateValue");
}
final DeclaredType paramDeclaredType = (DeclaredType) param.asType();
final String paramDeclaredTypeName = paramDeclaredType
.asElement()
.getSimpleName()
.toString();
if (!paramDeclaredTypeName.equals(ClassNames.STATE_VALUE.simpleName())) {
throw new ComponentsProcessingException(
"All state parameters must be of type com.facebook.litho.StateValue, " +
param.getSimpleName() + " is of type " +
param.asType());
}
VariableElement stateMatchingParam = mStateMap.get(param.getSimpleName().toString());
// Check #3
if (stateMatchingParam == null || stateMatchingParam.getAnnotation(State.class) == null) {
throw new ComponentsProcessingException(
param,
"Names of parameters of type StateValue must match the name of a parameter annotated " +
"with @State");
}
// Check #4
final List<TypeMirror> typeArguments =
(List<TypeMirror>) paramDeclaredType.getTypeArguments();
if (typeArguments.isEmpty()) {
throw new ComponentsProcessingException(
param,
"Type parameter for a parameter of type StateValue should match the type of " +
"a parameter with the same name annotated with @State");
}
final TypeMirror typeArgument = typeArguments.get(0);
final TypeName stateMatchingParamTypeName = ClassName.get(stateMatchingParam.asType());
if (stateMatchingParamTypeName.isPrimitive()) {
TypeName stateMatchingParamBoxedType = stateMatchingParamTypeName.box();
if (!stateMatchingParamBoxedType.equals(TypeName.get(typeArgument))) {
throw new ComponentsProcessingException(
param,
"Type parameter for a parameter of type StateValue should match the type of " +
"a parameter with the same name annotated with @State");
}
}
}
}
/**
* Generate an EventHandler factory methods
*/
public void generateEventHandlerFactories(
ClassName contextClassName,
ClassName componentClassName) {
for (ExecutableElement element : mOnEventMethods) {
generateEventHandlerFactory(
element,
contextClassName,
componentClassName);
}
}
// ExecutableElement.hashCode may be different in different runs of the
// processor. getElementId() is deterministic and ensures that the output is
// the same across multiple runs.
private int getElementId(ExecutableElement el) {
return (mQualifiedClassName.hashCode() * 31 + el.getSimpleName().hashCode()) * 31 +
el.asType().toString().hashCode();
}
/**
* Generate a dispatchOnEvent() implementation for the component.
*/
public void generateDispatchOnEvent(
ClassName contextClassName) {
final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("dispatchOnEvent")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.returns(TypeName.OBJECT)
.addParameter(
ParameterSpec.builder(ClassNames.EVENT_HANDLER, "eventHandler", Modifier.FINAL).build())
.addParameter(
ParameterSpec.builder(ClassNames.OBJECT, "eventState", Modifier.FINAL).build());
methodBuilder.addStatement("int id = eventHandler.id");
methodBuilder.beginControlFlow("switch($L)", "id");
final String implInstanceName = "_" + getImplInstanceName();
for (ExecutableElement element : mOnEventMethods) {
methodBuilder.beginControlFlow("case $L:", getElementId(element));
final DeclaredType eventClass = Utils.getAnnotationParameter(
mProcessingEnv,
element,
OnEvent.class,
"value");
final String eventName = eventClass.toString();
methodBuilder.addStatement(
"$L $L = ($L) $L",
eventName,
implInstanceName,
eventName,
"eventState");
final CodeBlock.Builder eventHandlerParams = CodeBlock.builder();
eventHandlerParams.indent();
int i = 0;
eventHandlerParams.add("\n($T) eventHandler.params[$L],", contextClassName, i++);
for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) {
eventHandlerParams.add(
"\n" + implInstanceName + ".$L,",
v.getSimpleName().toString());
}
for (VariableElement v : Utils.getParametersWithAnnotation(element, Param.class)) {
eventHandlerParams.add("\n($T) eventHandler.params[$L],", ClassName.get(v.asType()), i);
i++;
}
eventHandlerParams.add("\n$L", "eventHandler.mHasEventDispatcher");
eventHandlerParams.unindent();
if (element.getReturnType().getKind() != VOID) {
methodBuilder.addStatement(
"return do$L($L)",
capitalize(element.getSimpleName().toString()),
eventHandlerParams.build());
} else {
methodBuilder.addStatement(
"do$L($L)",
capitalize(element.getSimpleName().toString()),
eventHandlerParams.build());
methodBuilder.addStatement("return null");
}
methodBuilder.endControlFlow();
}
methodBuilder.addStatement("default: \nreturn null");
methodBuilder.endControlFlow();
writeMethodSpec(methodBuilder.build());
}
private void generateEventHandlerFactory(
ExecutableElement element,
ClassName contextClassName,
ClassName componentClassName) {
final List<VariableElement> eventParamElements =
Utils.getParametersWithAnnotation(element, Param.class);
final List<Parameter> eventParams = new ArrayList<>();
final List<String> typeParameters = new ArrayList<>();
for (VariableElement e : eventParamElements) {
eventParams.add(new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString()));
for (TypeMirror typeParam : getTypeVarArguments(e.asType())) {
typeParameters.add(typeParam.toString());
}
}
final DeclaredType eventClass = Utils.getAnnotationParameter(
mProcessingEnv,
element,
OnEvent.class,
"value");
final TypeName eventClassName =
ClassName.bestGuess(((TypeElement) eventClass.asElement()).getQualifiedName().toString());
writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder()
.eventId(getElementId(element))
.eventName(element.getSimpleName().toString())
.contextClass(contextClassName)
.eventHandlerClassName(
ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName))
.eventParams(eventParams)
.typeParameters(typeParameters)
.build());
writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder()
.eventId(getElementId(element))
.eventName(element.getSimpleName().toString())
.contextClass(componentClassName)
.eventHandlerClassName(
ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName))
.eventParams(eventParams)
.typeParameters(typeParameters)
.build());
}
private void generateOnEventHandler(
ExecutableElement element,
ClassName contextClassName) {
if (element.getParameters().size() == 0 ||
!ClassName.get(element.getParameters().get(0).asType()).equals(contextClassName)) {
throw new ComponentsProcessingException(
element,
"The first parameter for an onEvent method should be of type "
+contextClassName.toString());
}
final String evenHandlerName = element.getSimpleName().toString();
final List<Parameter> fromParams = new ArrayList<>();
fromParams.add(new Parameter(
contextClassName,
element.getParameters().get(0).getSimpleName().toString()));
final List<VariableElement> fromParamElements =
Utils.getParametersWithAnnotation(element, FromEvent.class);
fromParamElements.addAll(Utils.getParametersWithAnnotation(element, Param.class));
for (VariableElement v : fromParamElements) {
fromParams.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString()));
}
writeMethodSpec(new DelegateMethodSpecBuilder()
.implClassName(getImplClassName())
.abstractImplType(ClassNames.HAS_EVENT_DISPATCHER_CLASSNAME)
.implParameters(mImplParameters)
.visibility(PRIVATE)
.fromName("do" + capitalize(evenHandlerName))
.fromParams(fromParams)
.target(mSourceDelegateAccessorName)
.toName(evenHandlerName)
.toParams(getParams(element))
.fromReturnType(ClassName.get(element.getReturnType()))
.toReturnType(ClassName.get(element.getReturnType()))
.stateParams(mStateMap.keySet())
.build());
}
private void generateOnStateUpdateMethods(
ExecutableElement element,
ClassName contextClass,
ClassName componentClass) {
final String methodName = element.getSimpleName().toString();
final List<VariableElement> updateMethodParamElements =
Utils.getParametersWithAnnotation(element, Param.class);
final OnStateUpdateMethodSpecBuilder builder = new OnStateUpdateMethodSpecBuilder()
.componentClass(componentClass)
.lifecycleImplClass(mSimpleClassName)
.stateUpdateClassName(getStateUpdateClassName(element));
for (VariableElement e : updateMethodParamElements) {
builder.updateMethodParam(
new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString()));
List<TypeMirror> genericArgs = getTypeVarArguments(e.asType());
if (genericArgs != null) {
for (TypeMirror genericArg : genericArgs) {
builder.typeParameter(genericArg.toString());
}
}
}
writeMethodSpec(builder
.updateMethodName(methodName)
.async(false)
.contextClass(contextClass)
.build());
writeMethodSpec(builder
.updateMethodName(methodName + "Async")
.async(true)
.contextClass(contextClass)
.build());
}
static List<TypeMirror> getTypeVarArguments(TypeMirror diffType) {
List<TypeMirror> typeVarArguments = new ArrayList<>();
if (diffType.getKind() == DECLARED) {
final DeclaredType parameterDeclaredType = (DeclaredType) diffType;
final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments();
for (TypeMirror typeArgument : typeArguments) {
if (typeArgument.getKind() == TYPEVAR) {
typeVarArguments.add(typeArgument);
}
}
}
return typeVarArguments;
}
public static List<TypeMirror> getGenericTypeArguments(TypeMirror diffType) {
if (diffType.getKind() == DECLARED) {
final DeclaredType parameterDeclaredType = (DeclaredType) diffType;
final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments();
return (List<TypeMirror>) typeArguments;
}
return null;
}
public static List<Parameter> getParams(ExecutableElement e) {
final List<Parameter> params = new ArrayList<>();
for (VariableElement v : e.getParameters()) {
params.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString()));
}
return params;
}
/**
* Generates a class that implements {@link com.facebook.litho.ComponentLifecycle} given
* a method annotated with {@link OnUpdateState}. The class constructor takes as params all the
* params annotated with {@link Param} on the method and keeps them in class members.
* @param element The method annotated with {@link OnUpdateState}
*/
private void generateStateUpdateClass(
ExecutableElement element,
ClassName componentClassName,
ClassName stateContainerClassName,
ClassName updateStateInterface,
StaticFlag staticFlag) {
final String stateUpdateClassName = getStateUpdateClassName(element);
final TypeName implClassName = ClassName.bestGuess(getImplClassName());
final StateUpdateImplClassBuilder stateUpdateImplClassBuilder =
new StateUpdateImplClassBuilder()
.withTarget(mSourceDelegateAccessorName)
.withSpecOnUpdateStateMethodName(element.getSimpleName().toString())
.withComponentImplClassName(implClassName)
.withComponentClassName(componentClassName)
.withComponentStateUpdateInterface(updateStateInterface)
.withStateContainerClassName(stateContainerClassName)
.withStateContainerImplClassName(ClassName.bestGuess(getStateContainerImplClassName()))
.withStateUpdateImplClassName(stateUpdateClassName)
.withSpecOnUpdateStateMethodParams(getParams(element))
.withStateValueParams(getStateValueParams(element))
.withStaticFlag(staticFlag);
final List<VariableElement> parametersVarElements =
Utils.getParametersWithAnnotation(element, Param.class);
final List<Parameter> parameters = new ArrayList<>();
for (VariableElement v : parametersVarElements) {
parameters.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString()));
for (TypeMirror typeVar : getTypeVarArguments(v.asType())) {
stateUpdateImplClassBuilder.typeParameter(typeVar.toString());
}
}
stateUpdateImplClassBuilder.withParamsForStateUpdate(parameters);
writeInnerTypeSpec(stateUpdateImplClassBuilder.build());
}
/**
* Generate an onLoadStyle implementation.
*/
public void generateOnLoadStyle() {
final ExecutableElement delegateMethod = Utils.getAnnotatedMethod(
mSourceElement,
OnLoadStyle.class);
if (delegateMethod == null) {
return;
}
final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onLoadStyle")
.addAnnotation(
AnnotationSpec
.builder(SuppressWarnings.class)
.addMember("value", "$S", "unchecked").build())
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.addParameter(ClassNames.COMPONENT_CONTEXT, "_context")
.addParameter(
ParameterSpec.builder(
ParameterizedTypeName.get(
ClassNames.COMPONENT,
| litho-processor/src/main/java/com/facebook/litho/processor/Stages.java | /**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho.processor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.facebook.common.internal.ImmutableList;
import com.facebook.litho.annotations.Event;
import com.facebook.litho.annotations.FromEvent;
import com.facebook.litho.annotations.OnCreateInitialState;
import com.facebook.litho.annotations.OnCreateTreeProp;
import com.facebook.litho.annotations.OnEvent;
import com.facebook.litho.annotations.OnLoadStyle;
import com.facebook.litho.annotations.OnUpdateState;
import com.facebook.litho.annotations.Param;
import com.facebook.litho.annotations.Prop;
import com.facebook.litho.annotations.PropDefault;
import com.facebook.litho.annotations.ResType;
import com.facebook.litho.annotations.State;
import com.facebook.litho.annotations.TreeProp;
import com.facebook.litho.javapoet.JPUtil;
import com.facebook.litho.processor.GetTreePropsForChildrenMethodBuilder.CreateTreePropMethodData;
import com.facebook.litho.specmodels.model.ClassNames;
import com.facebook.litho.specmodels.model.PropDefaultModel;
import com.facebook.litho.specmodels.processor.PropDefaultsExtractor;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.TypeVariableName;
import com.squareup.javapoet.WildcardTypeName;
import static com.facebook.litho.processor.Utils.capitalize;
import static com.facebook.litho.processor.Visibility.PRIVATE;
import static com.facebook.litho.specmodels.generator.GeneratorConstants.DELEGATE_FIELD_NAME;
import static com.facebook.litho.specmodels.generator.GeneratorConstants.SPEC_INSTANCE_NAME;
import static java.util.Arrays.asList;
import static javax.lang.model.type.TypeKind.ARRAY;
import static javax.lang.model.type.TypeKind.DECLARED;
import static javax.lang.model.type.TypeKind.DOUBLE;
import static javax.lang.model.type.TypeKind.FLOAT;
import static javax.lang.model.type.TypeKind.TYPEVAR;
import static javax.lang.model.type.TypeKind.VOID;
public class Stages {
public static final String IMPL_CLASS_NAME_SUFFIX = "Impl";
private static final String INNER_IMPL_BUILDER_CLASS_NAME = "Builder";
private static final String STATE_UPDATE_IMPL_NAME_SUFFIX = "StateUpdate";
public static final String STATE_CONTAINER_IMPL_NAME_SUFFIX = "StateContainerImpl";
public static final String STATE_CONTAINER_IMPL_MEMBER = "mStateContainerImpl";
private static final String REQUIRED_PROPS_NAMES = "REQUIRED_PROPS_NAMES";
private static final String REQUIRED_PROPS_COUNT = "REQUIRED_PROPS_COUNT";
private static final int ON_STYLE_PROPS = 1;
private static final int ON_CREATE_INITIAL_STATE = 1;
private final boolean mSupportState;
public enum StaticFlag {
STATIC,
NOT_STATIC
}
public enum StyleableFlag {
STYLEABLE,
NOT_STYLEABLE
}
// Using these names in props might cause conflicts with the method names in the
// component's generated layout builder class so we trigger a more user-friendly
// error if the component tries to use them. This list should be kept in sync
// with BaseLayoutBuilder.
private static final String[] RESERVED_PROP_NAMES = new String[] {
"withLayout",
"key",
"loadingEventHandler",
};
private static final Class<Annotation>[] TREE_PROP_ANNOTATIONS = new Class[] {
TreeProp.class,
};
private static final Class<Annotation>[] PROP_ANNOTATIONS = new Class[] {
Prop.class,
};
private static final Class<Annotation>[] STATE_ANNOTATIONS = new Class[] {
State.class,
};
private final ProcessingEnvironment mProcessingEnv;
private final TypeElement mSourceElement;
private final String mQualifiedClassName;
private final Class<Annotation>[] mStageAnnotations;
private final Class<Annotation>[] mInterStagePropAnnotations;
private final Class<Annotation>[] mParameterAnnotations;
private final TypeSpec.Builder mClassTypeSpec;
private final List<TypeVariableName> mTypeVariables;
private final List<TypeElement> mEventDeclarations;
private final Map<String, String> mPropJavadocs;
private final String mSimpleClassName;
private String mSourceDelegateAccessorName = DELEGATE_FIELD_NAME;
private List<VariableElement> mProps;
private List<VariableElement> mOnCreateInitialStateDefinedProps;
private ImmutableList<PropDefaultModel> mPropDefaults;
private List<VariableElement> mTreeProps;
private final Map<String, VariableElement> mStateMap = new LinkedHashMap<>();
// Map of name to VariableElement, for members of the inner implementation class, in order
private LinkedHashMap<String, VariableElement> mImplMembers;
private List<Parameter> mImplParameters;
private final Map<String, TypeMirror> mExtraStateMembers;
// List of methods that have @OnEvent on it.
private final List<ExecutableElement> mOnEventMethods;
// List of methods annotated with @OnUpdateState.
private final List<ExecutableElement> mOnUpdateStateMethods;
private final List<ExecutableElement> mOnCreateTreePropsMethods;
// List of methods that define stages (e.g. OnCreateLayout)
private List<ExecutableElement> mStages;
public TypeElement getSourceElement() {
return mSourceElement;
}
public Stages(
ProcessingEnvironment processingEnv,
TypeElement sourceElement,
String qualifiedClassName,
Class<Annotation>[] stageAnnotations,
Class<Annotation>[] interStagePropAnnotations,
TypeSpec.Builder typeSpec,
List<TypeVariableName> typeVariables,
boolean supportState,
Map<String, TypeMirror> extraStateMembers,
List<TypeElement> eventDeclarations,
Map<String, String> propJavadocs) {
mProcessingEnv = processingEnv;
mSourceElement = sourceElement;
mQualifiedClassName = qualifiedClassName;
mStageAnnotations = stageAnnotations;
mInterStagePropAnnotations = interStagePropAnnotations;
mClassTypeSpec = typeSpec;
mTypeVariables = typeVariables;
mEventDeclarations = eventDeclarations;
mPropJavadocs = propJavadocs;
final List<Class<Annotation>> parameterAnnotations = new ArrayList<>();
parameterAnnotations.addAll(asList(PROP_ANNOTATIONS));
parameterAnnotations.addAll(asList(STATE_ANNOTATIONS));
parameterAnnotations.addAll(asList(mInterStagePropAnnotations));
parameterAnnotations.addAll(asList(TREE_PROP_ANNOTATIONS));
mParameterAnnotations = parameterAnnotations.toArray(
new Class[parameterAnnotations.size()]);
mSupportState = supportState;
mSimpleClassName = Utils.getSimpleClassName(mQualifiedClassName);
mOnEventMethods = Utils.getAnnotatedMethods(mSourceElement, OnEvent.class);
mOnUpdateStateMethods = Utils.getAnnotatedMethods(mSourceElement, OnUpdateState.class);
mOnCreateTreePropsMethods = Utils.getAnnotatedMethods(mSourceElement, OnCreateTreeProp.class);
mExtraStateMembers = extraStateMembers;
validateOnEventMethods();
populatePropDefaults();
populateStages();
validateAnnotatedParameters();
populateOnCreateInitialStateDefinedProps();
populateProps();
populateTreeProps();
if (mSupportState) {
populateStateMap();
}
validatePropDefaults();
populateImplMembers();
populateImplParameters();
validateStyleOutputs();
}
private boolean isInterStagePropAnnotationValidInStage(
Class<? extends Annotation> interStageProp,
Class<? extends Annotation> stage) {
final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp);
final int stageIndex = asList(mStageAnnotations).indexOf(stage);
if (interStagePropIndex < 0 || stageIndex < 0) {
throw new IllegalArgumentException(); // indicates bug in the annotation processor
}
// This logic relies on the fact that there are prop annotations for each stage (except for
// some number at the end)
return interStagePropIndex < stageIndex;
}
private boolean doesInterStagePropAnnotationMatchStage(
Class<? extends Annotation> interStageProp,
Class<? extends Annotation> stage) {
final int interStagePropIndex = asList(mInterStagePropAnnotations).indexOf(interStageProp);
// Null stage is allowed and indicates prop
int stageIndex = -1;
if (stage != null) {
stageIndex = asList(mStageAnnotations).indexOf(stage);
if (interStagePropIndex < 0 || stageIndex < 0) {
throw new IllegalArgumentException(); // indicates bug in the annotation processor
}
}
return interStagePropIndex == stageIndex;
}
private void validateOnEventMethods() {
final Map<String, Boolean> existsMap = new HashMap<>();
for (ExecutableElement element : mOnEventMethods) {
if (existsMap.containsKey(element.getSimpleName().toString())) {
throw new ComponentsProcessingException(
element,
"@OnEvent declared methods must have unique names");
}
final DeclaredType eventClass = Utils.getAnnotationParameter(
mProcessingEnv,
element,
OnEvent.class,
"value");
final TypeMirror returnType = Utils.getAnnotationParameter(
mProcessingEnv,
eventClass.asElement(),
Event.class,
"returnType");
if (!mProcessingEnv.getTypeUtils().isSameType(element.getReturnType(), returnType)) {
throw new ComponentsProcessingException(
element,
"Method " + element.getSimpleName() + " must return " + returnType +
", since that is what " + eventClass + " expects.");
}
final List<? extends VariableElement> parameters =
Utils.getEnclosedFields((TypeElement) eventClass.asElement());
for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) {
boolean hasMatchingParameter = false;
for (VariableElement parameter : parameters) {
if (parameter.getSimpleName().equals(v.getSimpleName()) &&
parameter.asType().toString().equals(v.asType().toString())) {
hasMatchingParameter = true;
break;
}
}
if (!hasMatchingParameter) {
throw new ComponentsProcessingException(
v,
v.getSimpleName() + " of this type is not a member of " +
eventClass);
}
return;
}
existsMap.put(element.getSimpleName().toString(), true);
}
}
/**
* Ensures that the declared events don't clash with the predefined ones.
*/
private void validateEventDeclarations() {
for (TypeElement eventDeclaration : mEventDeclarations) {
final Event eventAnnotation = eventDeclaration.getAnnotation(Event.class);
if (eventAnnotation == null) {
throw new ComponentsProcessingException(
eventDeclaration,
"Events must be declared with the @Event annotation, event is: " + eventDeclaration);
}
final List<? extends VariableElement> fields = Utils.getEnclosedFields(eventDeclaration);
for (VariableElement field : fields) {
if (!field.getModifiers().contains(Modifier.PUBLIC) ||
field.getModifiers().contains(Modifier.FINAL)) {
throw new ComponentsProcessingException(
field,
"Event fields must be declared as public non-final");
}
}
}
}
private void validateStyleOutputs() {
final ExecutableElement delegateMethod = Utils.getAnnotatedMethod(
mSourceElement,
OnLoadStyle.class);
if (delegateMethod == null) {
return;
}
final List<? extends VariableElement> parameters = delegateMethod.getParameters();
if (parameters.size() < ON_STYLE_PROPS) {
throw new ComponentsProcessingException(
delegateMethod,
"The @OnLoadStyle method should have an ComponentContext" +
"followed by Output parameters matching component create.");
}
final TypeName firstParamType = ClassName.get(parameters.get(0).asType());
if (!firstParamType.equals(ClassNames.COMPONENT_CONTEXT)) {
throw new ComponentsProcessingException(
parameters.get(0),
"The first argument of the @OnLoadStyle method should be an ComponentContext.");
}
for (int i = ON_STYLE_PROPS, size = parameters.size(); i < size; i++) {
final VariableElement v = parameters.get(i);
final TypeMirror outputType = Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT);
if (outputType == null) {
throw new ComponentsProcessingException(
parameters.get(i),
"The @OnLoadStyle method should have only have Output arguments matching " +
"component create.");
}
final Types typeUtils = mProcessingEnv.getTypeUtils();
final String name = v.getSimpleName().toString();
boolean matchesProp = false;
for (Element prop : mProps) {
if (!prop.getSimpleName().toString().equals(name)) {
continue;
}
matchesProp = true;
if (!typeUtils.isAssignable(prop.asType(), outputType)) {
throw new ComponentsProcessingException(
v,
"Searching for prop \"" + name + "\" of type " + ClassName.get(outputType) +
" but found prop with the same name of type " +
ClassName.get(prop.asType()));
}
}
if (!matchesProp) {
throw new ComponentsProcessingException(
v,
"Output named '" + v.getSimpleName() + "' does not match any prop " +
"in the component.");
}
}
}
/**
* Validate that:
* <ul>
* <li>1. Parameters are consistently typed across stages.</li>
* <li>2. Outputs for the same parameter name aren't duplicated.</li>
* <li>3. Declared inter-stage prop parameters from previous stages (i.e. not
* {@link Prop}) correspond to outputs from that stage</li>
* <li>4. Inter-stage prop parameters come from previous stages. i.e. It is illegal to declare
* a @FromMeasure parameter in @OnInflate</li>
* <li>5. Inter-stage parameters don't have duplicate annotations (and that outputs aren't
* annotated as inter-stage props)</li>
* <li>6. Ensure props don't use reserved words as names.</li>
* <li>7. Ensure required props don't have default values.</li>
* <li>8. Ensure same props are annotated identically</li>
* <li>9. Ensure props are of legal types</li>
* </ul>
*/
private void validateAnnotatedParameters() {
final List<PrintableException> exceptions = new ArrayList<>();
final Map<String, VariableElement> variableNameToElementMap = new HashMap<>();
final Map<String, Class<? extends Annotation>> outputVariableToStage = new HashMap<>();
for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) {
final ExecutableElement stage = Utils.getAnnotatedMethod(
mSourceElement,
stageAnnotation);
if (stage == null) {
continue;
}
// Enforce #5: getSpecDefinedParameters will verify that parameters don't have duplicate
// annotations
for (VariableElement v : getSpecDefinedParameters(stage)) {
try {
final String variableName = v.getSimpleName().toString();
final Annotation interStagePropAnnotation = getInterStagePropAnnotation(v);
final boolean isOutput =
Utils.getGenericTypeArgument(v.asType(), ClassNames.OUTPUT) != null;
if (isOutput) {
outputVariableToStage.put(variableName, stageAnnotation);
}
// Enforce #3
if (interStagePropAnnotation != null) {
final Class<? extends Annotation> outputStage = outputVariableToStage.get(variableName);
if (!doesInterStagePropAnnotationMatchStage(
interStagePropAnnotation.annotationType(), outputStage)) {
throw new ComponentsProcessingException(
v,
"Inter-stage prop declaration is incorrect, the same name and type must be " +
"used in every method where the inter-stage prop is declared.");
}
}
// Enforce #4
if (interStagePropAnnotation != null
&& !isInterStagePropAnnotationValidInStage(
interStagePropAnnotation.annotationType(), stageAnnotation)) {
throw new ComponentsProcessingException(
v,
"Inter-stage create must refer to previous stages.");
}
final VariableElement existingType = variableNameToElementMap.get(variableName);
if (existingType != null && !isSameType(existingType.asType(), v.asType())) {
// We have a type mis-match. This is allowed, provided that the previous type is an
// outputand the new type is an prop, and the type argument of the output matches the
// prop. In the future, we may want to allow stages to modify outputs from previous
// stages, but for now we disallow it.
// Enforce #1 and #2
if ((getInterStagePropAnnotation(v) == null ||
Utils.getGenericTypeArgument(existingType.asType(), ClassNames.OUTPUT) == null) &&
Utils.getGenericTypeArgument(existingType.asType(), ClassNames.DIFF) == null) {
throw new ComponentsProcessingException(
v,
"Inconsistent type for '" + variableName + "': '" + existingType.asType() +
"' and '" + v.asType() + "'");
}
} else if (existingType == null) {
// We haven't see a parameter with this name yet. Therefore it must be either @Prop,
// @State or an output.
final boolean isFromProp = getParameterAnnotation(v, PROP_ANNOTATIONS) != null;
final boolean isFromState = getParameterAnnotation(v, STATE_ANNOTATIONS) != null;
final boolean isFromTreeProp
= getParameterAnnotation(v, TREE_PROP_ANNOTATIONS) != null;
if (isFromState && !mSupportState) {
throw new ComponentsProcessingException(
v,
"State is not supported in this kind of Spec.");
}
if (!isFromProp && !isFromState && !isOutput && !isFromTreeProp) {
throw new ComponentsProcessingException(
v,
"Inter-stage prop declared without source.");
}
}
// Enforce #6
final Prop propAnnotation = v.getAnnotation(Prop.class);
if (propAnnotation != null) {
for (String reservedPropName : RESERVED_PROP_NAMES) {
if (reservedPropName.equals(variableName)) {
throw new ComponentsProcessingException(
v,
"'" + reservedPropName + "' is a reserved prop name used by " +
"the component's layout builder. Please use another name.");
}
}
// Enforce #7
final boolean hasDefaultValue = hasDefaultValue(v);
if (hasDefaultValue && !propAnnotation.optional()) {
throw new ComponentsProcessingException(
v,
"Prop is not optional but has a declared default value.");
}
// Enforce #8
if (existingType != null) {
final Prop existingPropAnnotation = existingType.getAnnotation(Prop.class);
if (existingPropAnnotation != null) {
if (!hasSameAnnotations(v, existingType)) {
throw new ComponentsProcessingException(
v,
"The prop '" + variableName + "' is configured differently for different " +
"methods. Ensure each instance of this prop is declared identically.");
}
}
}
// Enforce #9
TypeName typeName;
try {
typeName = ClassName.get(v.asType());
} catch (IllegalArgumentException e) {
throw new ComponentsProcessingException(
v,
"Prop type does not exist");
}
// Enforce #10
final List<ClassName> illegalPropTypes = Arrays.asList(
ClassNames.COMPONENT_LAYOUT,
ClassNames.COMPONENT_LAYOUT_BUILDER,
ClassNames.COMPONENT_LAYOUT_CONTAINER_BUILDER,
ClassNames.COMPONENT_BUILDER,
ClassNames.COMPONENT_BUILDER_WITH_LAYOUT,
ClassNames.REFERENCE_BUILDER);
if (illegalPropTypes.contains(typeName)) {
throw new ComponentsProcessingException(
v,
"Props may not be declared with the following types:" +
illegalPropTypes);
}
}
variableNameToElementMap.put(variableName, v);
} catch (PrintableException e) {
exceptions.add(e);
}
}
}
if (!exceptions.isEmpty()) {
throw new MultiPrintableException(exceptions);
}
}
private boolean hasSameAnnotations(VariableElement v1, VariableElement v2) {
final List<? extends AnnotationMirror> v1Annotations = v1.getAnnotationMirrors();
final List<? extends AnnotationMirror> v2Annotations = v2.getAnnotationMirrors();
if (v1Annotations.size() != v2Annotations.size()) {
return false;
}
final int count = v1Annotations.size();
for (int i = 0; i < count; i++) {
final AnnotationMirror a1 = v1Annotations.get(i);
final AnnotationMirror a2 = v2Annotations.get(i);
// Some object in this hierarchy don't implement equals correctly.
// They do however produce very nice strings representations which we can compare instead.
if (!a1.toString().equals(a2.toString())) {
return false;
}
}
return true;
}
public void validateStatic() {
validateStaticFields();
validateStaticMethods();
}
private void validateStaticFields() {
for (Element element : mSourceElement.getEnclosedElements()) {
if (element.getKind() == ElementKind.FIELD &&
!element.getModifiers().contains(Modifier.STATIC)) {
throw new ComponentsProcessingException(
element,
"Field " + element.getSimpleName() + " in " + mSourceElement.getQualifiedName() +
" must be static");
}
}
}
private void validateStaticMethods() {
for (Class<? extends Annotation> stageAnnotation : mStageAnnotations) {
final ExecutableElement stage = Utils.getAnnotatedMethod(
mSourceElement,
stageAnnotation);
if (stage != null && !stage.getModifiers().contains(Modifier.STATIC)) {
throw new ComponentsProcessingException(
stage,
"Method " + stage.getSimpleName() + " in " + mSourceElement.getQualifiedName() +
" must be static");
}
}
}
/**
* Gather a list of VariableElement that are the props to this component
*/
private void populateProps() {
// We use a linked hash map to guarantee iteration order
final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>();
for (ExecutableElement stage : mStages) {
for (VariableElement v : getProps(stage)) {
// Validation unnecessary - already handled by validateAnnotatedParameters
final String variableName = v.getSimpleName().toString();
variableNameToElementMap.put(variableName, v);
}
}
mProps = new ArrayList<>(variableNameToElementMap.values());
addCreateInitialStateDefinedProps(mProps);
}
/**
* Gather a list of VariableElement that are the state to this component
*/
private void populateStateMap() {
// We use a linked hash map to guarantee iteration order
final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>();
for (ExecutableElement stage : mStages) {
for (VariableElement v : getState(stage)) {
final String variableName = v.getSimpleName().toString();
if (mStateMap.containsKey(variableName)) {
VariableElement existingType = mStateMap.get(variableName);
final State existingPropAnnotation = existingType.getAnnotation(State.class);
if (existingPropAnnotation != null) {
if (!hasSameAnnotations(v, existingType)) {
throw new ComponentsProcessingException(
v,
"The state '" + variableName + "' is configured differently for different " +
"methods. Ensure each instance of this state is declared identically.");
}
}
}
mStateMap.put(
variableName,
v);
}
}
}
private void populateTreeProps() {
final LinkedHashMap<String, VariableElement> variableNameToElementMap = new LinkedHashMap<>();
for (ExecutableElement stage : mStages) {
for (VariableElement v : Utils.getParametersWithAnnotation(stage, TreeProp.class)) {
final String variableName = v.getSimpleName().toString();
variableNameToElementMap.put(variableName, v);
}
}
mTreeProps = new ArrayList<>(variableNameToElementMap.values());
}
/**
* Get the list of stages (OnInflate, OnMeasure, OnMount) that are defined for this component.
*/
private void populateStages() {
mStages = new ArrayList<>();
for (Class<Annotation> stageAnnotation : mStageAnnotations) {
final ExecutableElement stage = Utils.getAnnotatedMethod(
mSourceElement,
stageAnnotation);
if (stage != null) {
mStages.add(stage);
}
}
if (mOnEventMethods != null) {
mStages.addAll(mOnEventMethods);
}
mStages.addAll(mOnCreateTreePropsMethods);
}
/**
* @param prop The prop to determine if it has a default or not.
* @return Returns true if the prop has a default, false otherwise.
*/
private boolean hasDefaultValue(VariableElement prop) {
final String name = prop.getSimpleName().toString();
final TypeName type = TypeName.get(prop.asType());
for (PropDefaultModel propDefault : mPropDefaults) {
if (propDefault.mName.equals(name) && propDefault.mType.equals(type)) {
return true;
}
}
return false;
}
/**
* Fail if any elements that exist in mPropDefaults do not exist in mProps.
*/
private void validatePropDefaults() {
for (PropDefaultModel propDefault : mPropDefaults) {
final ImmutableList<Modifier> modifiers = propDefault.mModifiers;
if (!modifiers.contains(Modifier.STATIC)
|| !modifiers.contains(Modifier.FINAL)
|| modifiers.contains(Modifier.PRIVATE)) {
throw new RuntimeException(
"Defaults for props (fields annotated with " + PropDefault.class + ") must be " +
"non-private, static, and final. This is not the case for " + propDefault.mName);
}
if (!hasValidNameAndType(propDefault)) {
throw new RuntimeException(
"Prop defaults (fields annotated with " + PropDefault.class + ") should have the " +
"same name and type as the prop that they set the default for. This is not the " +
"case for " + propDefault.mName);
}
}
}
/**
* @return true if the given prop default matches the name and type of a prop, false otherwise.
*/
private boolean hasValidNameAndType(PropDefaultModel propDefault) {
for (VariableElement prop : mProps) {
if (prop.getSimpleName().toString().equals(propDefault.mName)
&& TypeName.get(prop.asType()).equals(propDefault.mType)) {
return true;
}
}
return false;
}
/**
* Gather a list of parameters from the given element that are props to this component.
*/
private static List<VariableElement> getProps(ExecutableElement element) {
return Utils.getParametersWithAnnotation(element, Prop.class);
}
/**
* Gather a list of parameters from the given element that are state to this component.
*/
private static List<VariableElement> getState(ExecutableElement element) {
return Utils.getParametersWithAnnotation(element, State.class);
}
/**
* Gather a list of parameters from the given element that are defined by the spec. That is, they
* aren't one of the parameters predefined for a given method. For example, OnCreateLayout has a
* predefined parameter of type LayoutContext. Spec-defined parameters are annotated with one of
* our prop annotations or are of type {@link com.facebook.litho.Output}.
*/
private List<VariableElement> getSpecDefinedParameters(ExecutableElement element) {
return getSpecDefinedParameters(element, true);
}
private List<VariableElement> getSpecDefinedParameters(
ExecutableElement element,
boolean shouldIncludeOutputs) {
final ArrayList<VariableElement> specDefinedParameters = new ArrayList<>();
for (VariableElement v : element.getParameters()) {
final boolean isAnnotatedParameter = getParameterAnnotation(v) != null;
final boolean isInterStageOutput = Utils.getGenericTypeArgument(
v.asType(),
ClassNames.OUTPUT) != null;
if (isAnnotatedParameter && isInterStageOutput) {
throw new ComponentsProcessingException(
v,
"Variables that are both prop and output are forbidden.");
} else if (isAnnotatedParameter || (shouldIncludeOutputs && isInterStageOutput)) {
specDefinedParameters.add(v);
}
}
return specDefinedParameters;
}
private void populateOnCreateInitialStateDefinedProps() {
final ExecutableElement onCreateInitialState = Utils.getAnnotatedMethod(
getSourceElement(),
OnCreateInitialState.class);
if (onCreateInitialState == null) {
mOnCreateInitialStateDefinedProps = new ArrayList<>();
} else {
mOnCreateInitialStateDefinedProps = getSpecDefinedParameters(onCreateInitialState, false);
}
}
/**
* Get the @FromLayout, @FromMeasure, etc annotation on this element (@Prop isn't
* considered - use getParameterAnnotation if you want to consider them)
*/
private Annotation getInterStagePropAnnotation(VariableElement element) {
return getParameterAnnotation(element, mInterStagePropAnnotations);
}
/**
* Get the annotation, if any, present on a parameter. Annotations are restricted to our whitelist
* of parameter annotations: e.g. {@link Prop}, {@link State} etc)
*/
private Annotation getParameterAnnotation(VariableElement element) {
return getParameterAnnotation(element, mParameterAnnotations);
}
/**
* Get the annotation, if any, present on a parameter. Annotations are restricted to the specified
* whitelist. If there is a duplicate we will issue an error.
*/
private Annotation getParameterAnnotation(
VariableElement element,
Class<Annotation>[] possibleAnnotations) {
final ArrayList<Annotation> annotations = new ArrayList<>();
for (Class<Annotation> annotationClass : possibleAnnotations) {
final Annotation annotation = element.getAnnotation(annotationClass);
if (annotation != null) {
annotations.add(annotation);
}
}
if (annotations.isEmpty()) {
return null;
} else if (annotations.size() == 1) {
return annotations.get(0);
} else {
throw new ComponentsProcessingException(
element,
"Duplicate parameter annotation: '" + annotations.get(0) + "' and '" +
annotations.get(1) + "'");
}
}
/**
* Generate javadoc block describing component props.
*/
public void generateJavadoc() {
for (VariableElement v : mProps) {
final Prop propAnnotation = v.getAnnotation(Prop.class);
final String propTag = propAnnotation.optional() ? "@prop-optional" : "@prop-required";
final String javadoc =
mPropJavadocs != null ? mPropJavadocs.get(v.getSimpleName().toString()) : "";
final String sanitizedJavadoc =
javadoc != null ? javadoc.replace('\n', ' ') : null;
// Adds javadoc with following format:
// @prop-required name type javadoc.
// This can be changed later to use clear demarcation for fields.
// This is a block tag and cannot support inline tags like "{@link something}".
mClassTypeSpec.addJavadoc(
"$L $L $L $L\n",
propTag,
v.getSimpleName().toString(),
Utils.getTypeName(v.asType()),
sanitizedJavadoc);
}
}
/**
* Generate a method for this component which either lazily instantiates a singleton reference or
* return this depending on whether this lifecycle is static or not.
*/
public void generateGetter(boolean isStatic) {
final ClassName className = ClassName.bestGuess(mQualifiedClassName);
if (isStatic) {
mClassTypeSpec.addField(
FieldSpec
.builder(className, SPEC_INSTANCE_NAME, Modifier.PRIVATE, Modifier.STATIC)
.initializer("null")
.build());
mClassTypeSpec.addMethod(
MethodSpec.methodBuilder("get")
.addModifiers(Modifier.PUBLIC)
.addModifiers(Modifier.STATIC)
.addModifiers(Modifier.SYNCHRONIZED)
.returns(className)
.beginControlFlow("if ($L == null)", SPEC_INSTANCE_NAME)
.addStatement("$L = new $T()", SPEC_INSTANCE_NAME, className)
.endControlFlow()
.addStatement("return $L", SPEC_INSTANCE_NAME)
.build());
} else {
mClassTypeSpec.addMethod(
MethodSpec.methodBuilder("get")
.addModifiers(Modifier.PUBLIC)
.returns(className)
.addStatement("return this")
.build());
}
}
public void generateSourceDelegate(boolean initialized) {
final ClassName specClassName = ClassName.get(mSourceElement);
generateSourceDelegate(initialized, specClassName);
}
public void generateSourceDelegate(boolean initialized, TypeName specTypeName) {
final FieldSpec.Builder builder = FieldSpec
.builder(specTypeName, DELEGATE_FIELD_NAME)
.addModifiers(Modifier.PRIVATE);
if (initialized) {
builder.initializer("new $T()", specTypeName);
}
mClassTypeSpec.addField(builder.build());
}
private MethodSpec generateMakeShallowCopy(ClassName componentClassName, boolean hasDeepCopy) {
final List<String> componentsInImpl = findComponentsInImpl(componentClassName);
final List<String> interStageComponentVariables = getInterStageVariableNames();
if (componentsInImpl.isEmpty() &&
interStageComponentVariables.isEmpty() &&
mOnUpdateStateMethods.isEmpty()) {
return null;
}
final String implClassName = getImplClassName();
return new ShallowCopyMethodSpecBuilder()
.componentsInImpl(componentsInImpl)
.interStageVariables(interStageComponentVariables)
.implClassName(implClassName)
.hasDeepCopy(hasDeepCopy)
.stateContainerImplClassName(getStateContainerImplClassName())
.build();
}
private List<String> findComponentsInImpl(ClassName listComponent) {
final List<String> componentsInImpl = new ArrayList<>();
for (String key : mImplMembers.keySet()) {
final VariableElement element = mImplMembers.get(key);
final Name declaredClassName = Utils.getDeclaredClassNameWithoutGenerics(element);
if (declaredClassName != null &&
ClassName.bestGuess(declaredClassName.toString()).equals(listComponent)) {
componentsInImpl.add(element.getSimpleName().toString());
}
}
return componentsInImpl;
}
/**
* Generate a private constructor to enforce singleton-ity.
*/
public void generateConstructor() {
mClassTypeSpec.addMethod(
MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.build());
}
/**
* Generates a method to create the initial values for parameters annotated with {@link State}.
* This method also validates that the delegate method only tries to assign an initial value to
* State annotated parameters.
*/
public void generateCreateInitialState(
ExecutableElement from,
ClassName contextClass,
ClassName componentClass) {
verifyParametersForCreateInitialState(contextClass, from);
final MethodDescription methodDescription = new MethodDescription();
methodDescription.annotations = new Class[] { Override.class };
methodDescription.accessType = Modifier.PROTECTED;
methodDescription.returnType = null;
methodDescription.name = "createInitialState";
methodDescription.parameterTypes = new TypeName[] {contextClass};
generateDelegate(methodDescription, from, componentClass);
}
private void verifyParametersForCreateInitialState(
ClassName contextClass,
ExecutableElement executableElement) {
final List<VariableElement> parameters =
(List<VariableElement>) executableElement.getParameters();
if (parameters.size() < ON_CREATE_INITIAL_STATE + 1) {
throw new ComponentsProcessingException(
executableElement,
"The @OnCreateInitialState method should have an " + contextClass +
"followed by Output parameters matching state parameters.");
}
final TypeName firstParamType = ClassName.get(parameters.get(0).asType());
if (!firstParamType.equals(contextClass)) {
throw new ComponentsProcessingException(
parameters.get(0),
"The first argument of the @OnCreateInitialState method should be an " +
contextClass + ".");
}
for (int i = ON_CREATE_INITIAL_STATE, size = parameters.size(); i < size; i++) {
final VariableElement element = parameters.get(i);
final TypeMirror elementInnerClassType =
Utils.getGenericTypeArgument(element.asType(), ClassNames.OUTPUT);
if (elementInnerClassType != null) {
final String paramName = element.getSimpleName().toString();
VariableElement implParameter = mStateMap.get(paramName);
if (implParameter == null || implParameter.getAnnotation(State.class) == null) {
throw new ComponentsProcessingException(
executableElement,
"Only parameters annotated with @State can be initialized in @OnCreateInitialState," +
" parameter without annotation is: " + paramName);
}
}
}
}
/**
* Generate a method implementation that delegates to another method that takes annotated props.
*
* @param from description of method signature to be generated
* @param to method to which to delegate
* @param propsClass Component / Delegate. The base class of the inner implementation object
* @throws java.io.IOException If one of the writer methods throw
*/
public void generateDelegate(
MethodDescription from,
ExecutableElement to,
ClassName propsClass) {
generateDelegate(
from,
to,
Collections.<TypeName>emptyList(),
Collections.<String, String>emptyMap(),
propsClass);
}
public void generateDelegate(
MethodDescription from,
ExecutableElement to,
List<TypeName> expectedTypes,
ClassName propsClass) {
generateDelegate(
from,
to,
expectedTypes,
Collections.<String, String>emptyMap(),
propsClass);
}
/**
* Generate a method implementation that delegates to another method that takes annotated props.
*
* @param from description of method signature to be generated
* @param to method to which to delegate
* @param propsClass Component / Delegate. The base class of the inner implementation object
* @throws java.io.IOException If one of the writer methods throw
*/
public void generateDelegate(
MethodDescription from,
ExecutableElement to,
List<TypeName> expectedTypes,
Map<String, String> parameterTranslation,
ClassName propsClass) {
final Visibility visibility;
if (Arrays.asList(from.accessType).contains(Modifier.PRIVATE)) {
visibility = Visibility.PRIVATE;
} else if (Arrays.asList(from.accessType).contains(Modifier.PROTECTED)) {
visibility = Visibility.PROTECTED;
} else if (Arrays.asList(from.accessType).contains(Modifier.PUBLIC)) {
visibility = Visibility.PUBLIC;
} else {
visibility = Visibility.PACKAGE;
}
final List<Parameter> toParams = getParams(to);
final List<Parameter> fromParams = new ArrayList<>();
for (int i = 0; i < from.parameterTypes.length; i++) {
fromParams.add(new Parameter(from.parameterTypes[i], toParams.get(i).name));
}
final List<PrintableException> errors = new ArrayList<>();
for (int i = 0; i < expectedTypes.size(); i++) {
if (!toParams.get(i).type.equals(expectedTypes.get(i))) {
errors.add(new ComponentsProcessingException(
to.getParameters().get(i),
"Expected " + expectedTypes.get(i)));
}
}
if (!errors.isEmpty()) {
throw new MultiPrintableException(errors);
}
writeMethodSpec(new DelegateMethodSpecBuilder()
.implClassName(getImplClassName())
.abstractImplType(propsClass)
.implParameters(mImplParameters)
.checkedExceptions(
from.exceptions == null ?
new ArrayList<TypeName>() :
Arrays.asList(from.exceptions))
.overridesSuper(
from.annotations != null && Arrays.asList(from.annotations).contains(Override.class))
.parameterTranslation(parameterTranslation)
.visibility(visibility)
.fromName(from.name)
.fromReturnType(from.returnType == null ? TypeName.VOID : from.returnType)
.fromParams(fromParams)
.target(mSourceDelegateAccessorName)
.toName(to.getSimpleName().toString())
.stateParams(mStateMap.keySet())
.toReturnType(ClassName.get(to.getReturnType()))
.toParams(toParams)
.build());
}
/**
* Returns {@code true} if the given types match.
*/
public boolean isSameType(TypeMirror a, TypeMirror b) {
return mProcessingEnv.getTypeUtils().isSameType(a, b);
}
/**
* Generate an onEvent implementation that delegates to the @OnEvent-annotated method.
*/
public void generateOnEventHandlers(ClassName componentClassName, ClassName contextClassName) {
for (ExecutableElement element : mOnEventMethods) {
generateOnEventHandler(element, contextClassName);
}
}
/**
* Generate the static methods of the Component that can be called to update its state.
*/
public void generateOnStateUpdateMethods(
ClassName contextClass,
ClassName componentClassName,
ClassName stateContainerClassName,
ClassName stateUpdateInterface,
Stages.StaticFlag staticFlag) {
for (ExecutableElement element : mOnUpdateStateMethods) {
validateOnStateUpdateMethodDeclaration(element);
generateStateUpdateClass(
element,
componentClassName,
stateContainerClassName,
stateUpdateInterface,
staticFlag);
generateOnStateUpdateMethods(element, contextClass, componentClassName);
}
}
/**
* Validate that the declaration of a method annotated with {@link OnUpdateState} is correct:
* <ul>
* <li>1. Method parameters annotated with {@link Param} don't have the same name as parameters
* annotated with {@link State} or {@link Prop}.</li>
* <li>2. Method parameters not annotated with {@link Param} must be of type
* com.facebook.litho.StateValue.</li>
* <li>3. Names of method parameters not annotated with {@link Param} must match the name of
* a parameter annotated with {@link State}.</li>
* <li>4. Type of method parameters not annotated with {@link Param} must match the type of
* a parameter with the same name annotated with {@link State}.</li>
* </ul>
*/
private void validateOnStateUpdateMethodDeclaration(ExecutableElement element) {
final List<VariableElement> annotatedParams =
Utils.getParametersWithAnnotation(element, Param.class);
// Check #1
for (VariableElement annotatedParam : annotatedParams) {
if (mStateMap.get(annotatedParam.getSimpleName().toString()) != null) {
throw new ComponentsProcessingException(
annotatedParam,
"Parameters annotated with @Param should not have the same name as a parameter " +
"annotated with @State or @Prop");
}
}
final List<VariableElement> params = (List<VariableElement>) element.getParameters();
for (VariableElement param : params) {
if (annotatedParams.contains(param)) {
continue;
}
final TypeMirror paramType = param.asType();
// Check #2
if (paramType.getKind() != DECLARED) {
throw new ComponentsProcessingException(
param,
"Parameters not annotated with @Param must be of type " +
"com.facebook.litho.StateValue");
}
final DeclaredType paramDeclaredType = (DeclaredType) param.asType();
final String paramDeclaredTypeName = paramDeclaredType
.asElement()
.getSimpleName()
.toString();
if (!paramDeclaredTypeName.equals(ClassNames.STATE_VALUE.simpleName())) {
throw new ComponentsProcessingException(
"All state parameters must be of type com.facebook.litho.StateValue, " +
param.getSimpleName() + " is of type " +
param.asType());
}
VariableElement stateMatchingParam = mStateMap.get(param.getSimpleName().toString());
// Check #3
if (stateMatchingParam == null || stateMatchingParam.getAnnotation(State.class) == null) {
throw new ComponentsProcessingException(
param,
"Names of parameters of type StateValue must match the name of a parameter annotated " +
"with @State");
}
// Check #4
final List<TypeMirror> typeArguments =
(List<TypeMirror>) paramDeclaredType.getTypeArguments();
if (typeArguments.isEmpty()) {
throw new ComponentsProcessingException(
param,
"Type parameter for a parameter of type StateValue should match the type of " +
"a parameter with the same name annotated with @State");
}
final TypeMirror typeArgument = typeArguments.get(0);
final TypeName stateMatchingParamTypeName = ClassName.get(stateMatchingParam.asType());
if (stateMatchingParamTypeName.isPrimitive()) {
TypeName stateMatchingParamBoxedType = stateMatchingParamTypeName.box();
if (!stateMatchingParamBoxedType.equals(TypeName.get(typeArgument))) {
throw new ComponentsProcessingException(
param,
"Type parameter for a parameter of type StateValue should match the type of " +
"a parameter with the same name annotated with @State");
}
}
}
}
/**
* Generate an EventHandler factory methods
*/
public void generateEventHandlerFactories(
ClassName contextClassName,
ClassName componentClassName) {
for (ExecutableElement element : mOnEventMethods) {
generateEventHandlerFactory(
element,
contextClassName,
componentClassName);
}
}
// ExecutableElement.hashCode may be different in different runs of the
// processor. getElementId() is deterministic and ensures that the output is
// the same across multiple runs.
private int getElementId(ExecutableElement el) {
return (mQualifiedClassName.hashCode() * 31 + el.getSimpleName().hashCode()) * 31 +
el.asType().toString().hashCode();
}
/**
* Generate a dispatchOnEvent() implementation for the component.
*/
public void generateDispatchOnEvent(
ClassName contextClassName) {
final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("dispatchOnEvent")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override.class)
.returns(TypeName.OBJECT)
.addParameter(
ParameterSpec.builder(ClassNames.EVENT_HANDLER, "eventHandler", Modifier.FINAL).build())
.addParameter(
ParameterSpec.builder(ClassNames.OBJECT, "eventState", Modifier.FINAL).build());
methodBuilder.addStatement("int id = eventHandler.id");
methodBuilder.beginControlFlow("switch($L)", "id");
final String implInstanceName = "_" + getImplInstanceName();
for (ExecutableElement element : mOnEventMethods) {
methodBuilder.beginControlFlow("case $L:", getElementId(element));
final DeclaredType eventClass = Utils.getAnnotationParameter(
mProcessingEnv,
element,
OnEvent.class,
"value");
final String eventName = eventClass.toString();
methodBuilder.addStatement(
"$L $L = ($L) $L",
eventName,
implInstanceName,
eventName,
"eventState");
final CodeBlock.Builder eventHandlerParams = CodeBlock.builder();
eventHandlerParams.indent();
int i = 0;
eventHandlerParams.add("\n($T) eventHandler.params[$L],", contextClassName, i++);
for (VariableElement v : Utils.getParametersWithAnnotation(element, FromEvent.class)) {
eventHandlerParams.add(
"\n" + implInstanceName + ".$L,",
v.getSimpleName().toString());
}
for (VariableElement v : Utils.getParametersWithAnnotation(element, Param.class)) {
eventHandlerParams.add("\n($T) eventHandler.params[$L],", ClassName.get(v.asType()), i);
i++;
}
eventHandlerParams.add("\n$L", "eventHandler.mHasEventDispatcher");
eventHandlerParams.unindent();
if (element.getReturnType().getKind() != VOID) {
methodBuilder.addStatement(
"return do$L($L)",
capitalize(element.getSimpleName().toString()),
eventHandlerParams.build());
} else {
methodBuilder.addStatement(
"do$L($L)",
capitalize(element.getSimpleName().toString()),
eventHandlerParams.build());
methodBuilder.addStatement("return null");
}
methodBuilder.endControlFlow();
}
methodBuilder.addStatement("default: \nreturn null");
methodBuilder.endControlFlow();
writeMethodSpec(methodBuilder.build());
}
private void generateEventHandlerFactory(
ExecutableElement element,
ClassName contextClassName,
ClassName componentClassName) {
final List<VariableElement> eventParamElements =
Utils.getParametersWithAnnotation(element, Param.class);
final List<Parameter> eventParams = new ArrayList<>();
final List<String> typeParameters = new ArrayList<>();
for (VariableElement e : eventParamElements) {
eventParams.add(new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString()));
for (TypeMirror typeParam : getTypeVarArguments(e.asType())) {
typeParameters.add(typeParam.toString());
}
}
final DeclaredType eventClass = Utils.getAnnotationParameter(
mProcessingEnv,
element,
OnEvent.class,
"value");
final TypeName eventClassName =
ClassName.bestGuess(((TypeElement) eventClass.asElement()).getQualifiedName().toString());
writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder()
.eventId(getElementId(element))
.eventName(element.getSimpleName().toString())
.contextClass(contextClassName)
.eventHandlerClassName(
ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName))
.eventParams(eventParams)
.typeParameters(typeParameters)
.build());
writeMethodSpec(new EventHandlerFactoryMethodSpecBuilder()
.eventId(getElementId(element))
.eventName(element.getSimpleName().toString())
.contextClass(componentClassName)
.eventHandlerClassName(
ParameterizedTypeName.get(ClassNames.EVENT_HANDLER, eventClassName))
.eventParams(eventParams)
.typeParameters(typeParameters)
.build());
}
private void generateOnEventHandler(
ExecutableElement element,
ClassName contextClassName) {
if (element.getParameters().size() == 0 ||
!ClassName.get(element.getParameters().get(0).asType()).equals(contextClassName)) {
throw new ComponentsProcessingException(
element,
"The first parameter for an onEvent method should be of type "
+contextClassName.toString());
}
final String evenHandlerName = element.getSimpleName().toString();
final List<Parameter> fromParams = new ArrayList<>();
fromParams.add(new Parameter(
contextClassName,
element.getParameters().get(0).getSimpleName().toString()));
final List<VariableElement> fromParamElements =
Utils.getParametersWithAnnotation(element, FromEvent.class);
fromParamElements.addAll(Utils.getParametersWithAnnotation(element, Param.class));
for (VariableElement v : fromParamElements) {
fromParams.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString()));
}
writeMethodSpec(new DelegateMethodSpecBuilder()
.implClassName(getImplClassName())
.abstractImplType(ClassNames.HAS_EVENT_DISPATCHER_CLASSNAME)
.implParameters(mImplParameters)
.visibility(PRIVATE)
.fromName("do" + capitalize(evenHandlerName))
.fromParams(fromParams)
.target(mSourceDelegateAccessorName)
.toName(evenHandlerName)
.toParams(getParams(element))
.fromReturnType(ClassName.get(element.getReturnType()))
.toReturnType(ClassName.get(element.getReturnType()))
.stateParams(mStateMap.keySet())
.build());
}
private void generateOnStateUpdateMethods(
ExecutableElement element,
ClassName contextClass,
ClassName componentClass) {
final String methodName = element.getSimpleName().toString();
final List<VariableElement> updateMethodParamElements =
Utils.getParametersWithAnnotation(element, Param.class);
final OnStateUpdateMethodSpecBuilder builder = new OnStateUpdateMethodSpecBuilder()
.componentClass(componentClass)
.lifecycleImplClass(mSimpleClassName)
.stateUpdateClassName(getStateUpdateClassName(element));
for (VariableElement e : updateMethodParamElements) {
builder.updateMethodParam(
new Parameter(ClassName.get(e.asType()), e.getSimpleName().toString()));
List<TypeMirror> genericArgs = getTypeVarArguments(e.asType());
if (genericArgs != null) {
for (TypeMirror genericArg : genericArgs) {
builder.typeParameter(genericArg.toString());
}
}
}
writeMethodSpec(builder
.updateMethodName(methodName)
.async(false)
.contextClass(contextClass)
.build());
writeMethodSpec(builder
.updateMethodName(methodName + "Async")
.async(true)
.contextClass(contextClass)
.build());
}
static List<TypeMirror> getTypeVarArguments(TypeMirror diffType) {
List<TypeMirror> typeVarArguments = new ArrayList<>();
if (diffType.getKind() == DECLARED) {
final DeclaredType parameterDeclaredType = (DeclaredType) diffType;
final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments();
for (TypeMirror typeArgument : typeArguments) {
if (typeArgument.getKind() == TYPEVAR) {
typeVarArguments.add(typeArgument);
}
}
}
return typeVarArguments;
}
public static List<TypeMirror> getGenericTypeArguments(TypeMirror diffType) {
if (diffType.getKind() == DECLARED) {
final DeclaredType parameterDeclaredType = (DeclaredType) diffType;
final List<? extends TypeMirror> typeArguments = parameterDeclaredType.getTypeArguments();
return (List<TypeMirror>) typeArguments;
}
return null;
}
public static List<Parameter> getParams(ExecutableElement e) {
final List<Parameter> params = new ArrayList<>();
for (VariableElement v : e.getParameters()) {
params.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString()));
}
return params;
}
/**
* Generates a class that implements {@link com.facebook.litho.ComponentLifecycle} given
* a method annotated with {@link OnUpdateState}. The class constructor takes as params all the
* params annotated with {@link Param} on the method and keeps them in class members.
* @param element The method annotated with {@link OnUpdateState}
*/
private void generateStateUpdateClass(
ExecutableElement element,
ClassName componentClassName,
ClassName stateContainerClassName,
ClassName updateStateInterface,
StaticFlag staticFlag) {
final String stateUpdateClassName = getStateUpdateClassName(element);
final TypeName implClassName = ClassName.bestGuess(getImplClassName());
final StateUpdateImplClassBuilder stateUpdateImplClassBuilder =
new StateUpdateImplClassBuilder()
.withTarget(mSourceDelegateAccessorName)
.withSpecOnUpdateStateMethodName(element.getSimpleName().toString())
.withComponentImplClassName(implClassName)
.withComponentClassName(componentClassName)
.withComponentStateUpdateInterface(updateStateInterface)
.withStateContainerClassName(stateContainerClassName)
.withStateContainerImplClassName(ClassName.bestGuess(getStateContainerImplClassName()))
.withStateUpdateImplClassName(stateUpdateClassName)
.withSpecOnUpdateStateMethodParams(getParams(element))
.withStateValueParams(getStateValueParams(element))
.withStaticFlag(staticFlag);
final List<VariableElement> parametersVarElements =
Utils.getParametersWithAnnotation(element, Param.class);
final List<Parameter> parameters = new ArrayList<>();
for (VariableElement v : parametersVarElements) {
parameters.add(new Parameter(ClassName.get(v.asType()), v.getSimpleName().toString()));
for (TypeMirror typeVar : getTypeVarArguments(v.asType())) {
stateUpdateImplClassBuilder.typeParameter(typeVar.toString());
}
}
stateUpdateImplClassBuilder.withParamsForStateUpdate(parameters);
writeInnerTypeSpec(stateUpdateImplClassBuilder.build());
}
/**
* Generate an onLoadStyle implementation.
*/
public void generateOnLoadStyle() {
final ExecutableElement delegateMethod = Utils.getAnnotatedMethod(
mSourceElement,
OnLoadStyle.class);
if (delegateMethod == null) {
return;
}
final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onLoadStyle")
.addAnnotation(
AnnotationSpec
.builder(SuppressWarnings.class)
.addMember("value", "$S", "unchecked").build())
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.addParameter(ClassNames.COMPONENT_CONTEXT, "_context")
.addParameter(
ParameterSpec.builder(
ParameterizedTypeName.get(
| Lines authored by emilsj
This commit forms part of the blame-preserving initial commit suite.
| litho-processor/src/main/java/com/facebook/litho/processor/Stages.java | Lines authored by emilsj | <ide><path>itho-processor/src/main/java/com/facebook/litho/processor/Stages.java
<ide> .addParameter(
<ide> ParameterSpec.builder(
<ide> ParameterizedTypeName.get(
<add> ClassNames.COMPONENT, |
|
Java | mit | 558b0781ce130f18c98cf9fbcfb1779e4d0ac098 | 0 | Group7-BIL481Proje/Bil481Proje | /*
*
* * The MIT License
* *
* * Copyright 2016 Shekhar Gulati <[email protected]>.
* *
* * 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.
*
*/
package strman;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining;
import static org.hamcrest.collection.IsArrayWithSize.emptyArray;
import static org.junit.Assert.*;
import static strman.Strman.*;
import static strman.Strman.endsWith;
import static strman.Strman.format;
public class StrmanTest {
@Test
public void replaceBetween_shouldReplaceSubstringsBetweenGivenIndexes() throws Exception {
assertThat(replaceBetween("elif","W",0,2), equalTo("Wif"));
assertThat(replaceBetween("elif","elif",0,4), equalTo("elif"));
assertThat(replaceBetween("elif","",0,2), equalTo("if"));
}
@Test(expected = IllegalArgumentException.class)
public void replaceBetween_shouldThrowIllegalArgumentExceptionWhenValueIsNull() throws Exception {
replaceBetween(null,null,0,4);
replaceBetween(null,"wer",0,4);
replaceBetween("werw",null,0,4);
replaceBetween("el","A",0,4);
}
@Test
public void append_shouldAppendStringsToEndOfValue() throws Exception {
assertThat(append("f", "o", "o", "b", "a", "r"), equalTo("foobar"));
assertThat(append("foobar"), equalTo("foobar"));
assertThat(append("", "foobar"), equalTo("foobar"));
}
@Test(expected = IllegalArgumentException.class)
public void append_shouldThrowIllegalArgumentExceptionWhenValueIsNull() throws Exception {
append(null);
}
@Test
public void appendArray_shouldAppendStringArrayToEndOfValue() throws Exception {
assertThat(appendArray("f", new String[]{"o", "o", "b", "a", "r"}), equalTo("foobar"));
assertThat(appendArray("foobar", new String[]{}), equalTo("foobar"));
assertThat(appendArray("", new String[]{"foobar"}), equalTo("foobar"));
}
@Test(expected = IllegalArgumentException.class)
public void appendArray_ShouldThrowIllegalArgumentExceptionWhenValueIsNull() throws Exception {
appendArray(null, new String[]{});
}
@Test
public void at_shouldFindCharacterAtIndex() throws Exception {
assertThat(at("foobar", 0), equalTo(Optional.of("f")));
assertThat(at("foobar", 1), equalTo(Optional.of("o")));
assertThat(at("foobar", -1), equalTo(Optional.of("r")));
assertThat(at("foobar", -2), equalTo(Optional.of("a")));
assertThat(at("foobar", 10), equalTo(Optional.empty()));
assertThat(at("foobar", -10), equalTo(Optional.empty()));
}
@Test
public void between_shouldReturnArrayWithStringsBetweenStartAndEnd() throws Exception {
assertThat(between("[abc][def]", "[", "]"), arrayContaining("abc", "def"));
assertThat(between("<span>foo</span>", "<span>", "</span>"), arrayContaining("foo"));
assertThat(between("<span>foo</span><span>bar</span>", "<span>", "</span>"), arrayContaining("foo", "bar"));
}
@Test
public void between_shouldReturnFullStringWhenStartAndEndDoesNotExist() throws Exception {
assertThat(between("[abc][def]", "{", "}"), arrayContaining("[abc][def]"));
assertThat(between("", "{", "}"), arrayContaining(""));
}
@Test
public void chars_shouldReturnAllCharactersInString() throws Exception {
final String title = "title";
assertThat(chars(title), equalTo(new String[]{"t", "i", "t", "l", "e"}));
}
@Test
public void collapseWhitespace_shouldReplaceConsecutiveWhitespaceWithSingleSpace() throws Exception {
String[] fixture = {
"foo bar",
" foo bar ",
" foo bar ",
" foo bar "
};
Arrays.stream(fixture).forEach(el -> assertThat(collapseWhitespace(el), equalTo("foo bar")));
}
@Test
public void collapseWhitespace_shouldReplaceConsecutiveWhitespaceBetweenMultipleStrings() throws Exception {
String input = " foo bar bazz hello world ";
assertThat(collapseWhitespace(input), equalTo("foo bar bazz hello world"));
}
@Test
public void containsWithCaseSensitiveFalse_shouldReturnTrueWhenStringContainsNeedle() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
"foo"
};
Arrays.stream(fixture).forEach(el -> assertTrue(contains(el, "FOO")));
}
@Test
public void containsWithCaseSensitiveTrue_shouldReturnTrueWhenStringContainsNeedle() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
"foo"
};
Arrays.stream(fixture).forEach(el -> assertFalse(contains(el, "FOO", true)));
}
@Test
public void containsAll_shouldReturnTrueOnlyWhenAllNeedlesAreContainedInValue() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
};
Arrays.stream(fixture).forEach(el -> assertTrue(containsAll(el, new String[]{"foo", "bar"})));
}
@Test
public void containsAll_shouldReturnFalseOnlyWhenAllNeedlesAreNotContainedInValue() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
};
Arrays.stream(fixture).forEach(el -> assertFalse(containsAll(el, new String[]{"FOO", "bar"}, true)));
}
@Test
public void containsAny_shouldReturnTrueWhenAnyOfSearchNeedleExistInInputValue() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
};
Arrays.stream(fixture).forEach(el -> assertTrue(containsAny(el, new String[]{"foo", "bar", "test"})));
}
@Test
public void containsAny_shouldReturnFalseWhenNoneOfSearchNeedleExistInInputValue() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
};
Arrays.stream(fixture).forEach(el -> assertFalse(containsAny(el, new String[]{"FOO", "BAR", "Test"}, true)));
}
@Test
public void countSubstr_shouldCountSubStrCountCaseInsensitiveWithoutOverlapInValue() throws Exception {
assertThat(countSubstr("aaaAAAaaa", "aaa", false, false), equalTo(3L));
}
@Test
public void countSubstr_shouldCountSubStrCountCaseSensitiveWithoutOverlapInValue() throws Exception {
assertThat(countSubstr("aaaAAAaaa", "aaa"), equalTo(2L));
}
@Test
public void countSubstr_shouldCountSubStrCountCaseInsensitiveWithOverlapInValue() throws Exception {
assertThat(countSubstr("aaaAAAaaa", "aaa", false, true), equalTo(7L));
}
@Test
public void countSubstr_shouldCountSubStrCountCaseSensitiveWithOverlapInValue() throws Exception {
assertThat(countSubstr("aaaAAAaaa", "AAA", true, true), equalTo(1L));
}
@Test
public void countSubstrTestFixture_caseSensitiveTrueAndOverlappingFalse() throws Exception {
String[] fixture = {
"aaaaaAaaAA",
"faaaAAaaaaAA",
"aaAAaaaaafA",
"AAaaafaaaaAAAA"
};
Arrays.stream(fixture).forEach(el -> assertThat(countSubstr(el, "a", true, false), equalTo(7L)));
}
@Test
public void countSubstrTestFixture_caseSensitiveFalseAndOverlappingFalse() throws Exception {
String[] fixture = {
"aaaaaaa",
"faaaaaaa",
"aaaaaaaf",
"aaafaaaa"
};
Arrays.stream(fixture).forEach(el -> assertThat(countSubstr(el, "A", false, false), equalTo(7L)));
}
@Test
public void countSubstrTestFixture_caseSensitiveTrueAndOverlappingTrue() throws Exception {
assertThat(countSubstr("aaa", "aa", true, true), equalTo(2L));
}
@Test
public void endsWith_caseSensitive_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {
String[] fixture = {
"foo bar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "bar")));
}
@Test
public void endsWith_notCaseSensitive_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {
String[] fixture = {
"foo bar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "BAR", false)));
}
@Test
public void endsWith_caseSensitiveAtPosition_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {
String[] fixture = {
"foo barr",
"barr"
};
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "bar", el.length() - 1, true)));
}
@Test
public void endsWith_notCaseSensitiveAtPosition_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {
String[] fixture = {
"foo barr",
"barr"
};
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "BAR", el.length() - 1, false)));
}
@Test
public void ensureLeft_shouldEnsureValueStartsWithFoo() throws Exception {
String[] fixture = {
"foobar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(ensureLeft(el, "foo"), equalTo("foobar")));
}
@Test
public void ensureLeft_notCaseSensitive_shouldEnsureValueStartsWithFoo() throws Exception {
assertThat(ensureLeft("foobar", "FOO", false), equalTo("foobar"));
assertThat(ensureLeft("bar", "FOO", false), equalTo("FOObar"));
}
@Test
public void base64Decode_shouldDecodeABase64DecodedValueToString() throws Exception {
assertThat(base64Decode("c3RybWFu"), equalTo("strman"));
assertThat(base64Decode("Zm9v"), equalTo("foo"));
assertThat(base64Decode("YmFy"), equalTo("bar"));
assertThat(base64Decode("YsOhciE="), equalTo("bár!"));
assertThat(base64Decode("5ryi"), equalTo("漢"));
}
@Test
public void base64Encode_shouldEncodeAString() throws Exception {
assertThat(base64Encode("strman"), equalTo("c3RybWFu"));
assertThat(base64Encode("foo"), equalTo("Zm9v"));
assertThat(base64Encode("bar"), equalTo("YmFy"));
assertThat(base64Encode("bár!"), equalTo("YsOhciE="));
assertThat(base64Encode("漢"), equalTo("5ryi"));
}
@Test
public void binDecode_shouldDecodeABinaryStringToAValue() throws Exception {
assertThat(
binDecode("000000000111001100000000011101000000000001110010000000000110110100000000011000010000000001101110"),
equalTo("strman"));
assertThat(binDecode("0110111100100010"), equalTo("漢"));
assertThat(binDecode("0000000001000001"), equalTo("A"));
assertThat(binDecode("0000000011000001"), equalTo("Á"));
assertThat(binDecode("00000000010000010000000001000001"), equalTo("AA"));
}
@Test
public void binEncode_shouldEncodeAStringToBinaryFormat() throws Exception {
assertThat(binEncode("漢"), equalTo("0110111100100010"));
assertThat(binEncode("A"), equalTo("0000000001000001"));
assertThat(binEncode("Á"), equalTo("0000000011000001"));
assertThat(binEncode("AA"), equalTo("00000000010000010000000001000001"));
}
@Test
public void decDecode_shouldDecodeDecimalStringToString() throws Exception {
assertThat(decDecode("28450"), equalTo("漢"));
assertThat(decDecode("00065"), equalTo("A"));
assertThat(decDecode("00193"), equalTo("Á"));
assertThat(decDecode("0006500065"), equalTo("AA"));
}
@Test
public void decEncode_shouldEncodeStringToDecimal() throws Exception {
assertThat(decEncode("漢"), equalTo("28450"));
assertThat(decEncode("A"), equalTo("00065"));
assertThat(decEncode("Á"), equalTo("00193"));
assertThat(decEncode("AA"), equalTo("0006500065"));
}
@Test
public void ensureRight_shouldEnsureStringEndsWithBar() throws Exception {
final String[] fixture = {
"foo", "foobar", "fooBAR"
};
assertThat(Arrays.stream(fixture).map(el -> ensureRight(el, "bar", false)).collect(toList()), hasItems("foobar", "foobar", "fooBAR"));
assertThat(Arrays.stream(fixture).map(el -> ensureRight(el, "bar")).collect(toList()), hasItems("foobar", "foobar", "fooBARbar"));
}
@Test
public void first_shouldReturnFirstThreeCharsOfString() throws Exception {
final String[] fixture = {
"foo", "foobar"
};
Arrays.stream(fixture).forEach(el -> assertThat(first(el, 3), equalTo(Optional.of("foo"))));
}
@Test
public void head_shouldReturnFirstCharOfString() throws Exception {
final String[] fixture = {
"foo", "foobar"
};
Arrays.stream(fixture).forEach(el -> assertThat(head(el), equalTo(Optional.of("f"))));
}
@Test
public void format_shouldFormatStringsToFooBar() throws Exception {
assertThat(format("{0} bar", "foo"), equalTo("foo bar"));
assertThat(format("foo {0}", "bar"), equalTo("foo bar"));
assertThat(format("foo {0}", "bar", "foo"), equalTo("foo bar"));
assertThat(format("{0} {1}", "foo", "bar"), equalTo("foo bar"));
assertThat(format("{1} {0}", "bar", "foo"), equalTo("foo bar"));
}
@Test(expected = IllegalArgumentException.class)
public void format_shouldThrowExceptionWhenValueDoesNotExist() throws Exception {
assertThat(format("{1} {0}"), equalTo("{1} {0}"));
}
@Test
public void hexDecode_shouldDecodeHexCodeToString() throws Exception {
assertThat(hexDecode("6f22"), equalTo("漢"));
assertThat(hexDecode("0041"), equalTo("A"));
assertThat(hexDecode("00c1"), equalTo("Á"));
assertThat(hexDecode("00410041"), equalTo("AA"));
}
@Test
public void hexEncode_shouldEncodeStringToHexadecimalFormat() throws Exception {
assertThat(hexEncode("漢"), equalTo("6f22"));
assertThat(hexEncode("A"), equalTo("0041"));
assertThat(hexEncode("Á"), equalTo("00c1"));
assertThat(hexEncode("AA"), equalTo("00410041"));
}
@Test
public void indexOf_shouldBeTrueWhenNeedleExists() throws Exception {
final String value = "foobar";
assertThat(indexOf(value, "f", 0, true), equalTo(0));
assertThat(indexOf(value, "o", 0, true), equalTo(1));
assertThat(indexOf(value, "b", 0, true), equalTo(3));
assertThat(indexOf(value, "a", 0, true), equalTo(4));
assertThat(indexOf(value, "r", 0, true), equalTo(5));
assertThat(indexOf(value, "t", 0, true), equalTo(-1));
}
@Test
public void indexOf_shouldBeTrueWhenNeedleExistCaseSensitive() throws Exception {
final String value = "foobar";
assertThat(indexOf(value, "F", 0, false), equalTo(0));
assertThat(indexOf(value, "O", 0, false), equalTo(1));
assertThat(indexOf(value, "B", 0, false), equalTo(3));
assertThat(indexOf(value, "A", 0, false), equalTo(4));
assertThat(indexOf(value, "R", 0, false), equalTo(5));
assertThat(indexOf(value, "T", 0, false), equalTo(-1));
}
@Test
public void inequal_shouldTestInequalityOfStrings() throws Exception {
assertThat(unequal("a", "b"), equalTo(true));
assertThat(unequal("a", "a"), equalTo(false));
assertThat(unequal("0", "1"), equalTo(true));
}
@Test
public void insert_shouldInsertStringAtIndex() throws Exception {
assertThat(insert("fbar", "oo", 1), equalTo("foobar"));
assertThat(insert("foo", "bar", 3), equalTo("foobar"));
assertThat(insert("foobar", "x", 5), equalTo("foobaxr"));
assertThat(insert("foobar", "x", 6), equalTo("foobarx"));
assertThat(insert("foo bar", "asadasd", 100), equalTo("foo bar"));
}
@Test
public void isLowerCase_shouldBeTrueWhenStringIsLowerCase() throws Exception {
assertThat(isLowerCase(""), equalTo(true));
assertThat(isLowerCase("foo"), equalTo(true));
assertThat(isLowerCase("foobarfoo"), equalTo(true));
}
@Test
public void isLowerCase_shouldBeFalseWhenStringIsNotLowerCase() throws Exception {
assertThat(isLowerCase("Foo"), equalTo(false));
assertThat(isLowerCase("foobarfooA"), equalTo(false));
}
@Test
public void isUpperCase_shouldBeTrueWhenStringIsUpperCase() throws Exception {
assertThat(isUpperCase(""), equalTo(true));
assertThat(isUpperCase("FOO"), equalTo(true));
assertThat(isUpperCase("FOOBARFOO"), equalTo(true));
}
@Test
public void isUpperCase_shouldBeFalseWhenStringIsNotUpperCase() throws Exception {
assertThat(isUpperCase("Foo"), equalTo(false));
assertThat(isUpperCase("foobarfooA"), equalTo(false));
}
@Test
public void last_shouldReturnLastNChars() throws Exception {
assertThat(last("foo", 3), equalTo("foo"));
assertThat(last("foobarfoo", 3), equalTo("foo"));
assertThat(last("", 3), equalTo(""));
assertThat(last("f", 3), equalTo("f"));
}
@Test
public void leftPad_shouldAddPaddingOnTheLeft() throws Exception {
assertThat(leftPad("1", "0", 5), equalTo("00001"));
assertThat(leftPad("01", "0", 5), equalTo("00001"));
assertThat(leftPad("001", "0", 5), equalTo("00001"));
assertThat(leftPad("0001", "0", 5), equalTo("00001"));
assertThat(leftPad("00001", "0", 5), equalTo("00001"));
}
@Test
public void isString_shouldBeFalseWhenValueIsNotString() throws Exception {
assertFalse(isString(1));
assertFalse(isString(false));
assertFalse(isString(1.2));
assertFalse(isString(new String[]{}));
}
@Test
public void isString_shouldBeTrueWhenValueIsString() throws Exception {
assertTrue(isString("string"));
assertTrue(isString(""));
}
@Test
public void lastIndexOf_shouldFindIndexOfNeedle() throws Exception {
final String value = "foobarfoobar";
assertThat(lastIndexOf(value, "f"), equalTo(6));
assertThat(lastIndexOf(value, "o"), equalTo(8));
assertThat(lastIndexOf(value, "b"), equalTo(9));
assertThat(lastIndexOf(value, "a"), equalTo(10));
assertThat(lastIndexOf(value, "r"), equalTo(11));
assertThat(lastIndexOf(value, "t"), equalTo(-1));
}
@Test
public void lastIndexOf_shouldFindIndexOfNeedleCaseInsensitive() throws Exception {
final String value = "foobarfoobar";
assertThat(lastIndexOf(value, "F", false), equalTo(6));
assertThat(lastIndexOf(value, "O", false), equalTo(8));
assertThat(lastIndexOf(value, "B", false), equalTo(9));
assertThat(lastIndexOf(value, "A", false), equalTo(10));
assertThat(lastIndexOf(value, "R", false), equalTo(11));
assertThat(lastIndexOf(value, "T", false), equalTo(-1));
}
@Test
public void leftTrim_shouldRemoveSpacesOnLeft() throws Exception {
assertThat(leftTrim(" strman"), equalTo("strman"));
assertThat(leftTrim(" strman "), equalTo("strman "));
}
@Test
public void prepend_shouldPrependStrings() throws Exception {
assertThat(prepend("r", "f", "o", "o", "b", "a"), equalTo("foobar"));
assertThat(prepend("foobar"), equalTo("foobar"));
assertThat(prepend("", "foobar"), equalTo("foobar"));
assertThat(prepend("bar", "foo"), equalTo("foobar"));
}
@Test
public void prependArray_shouldPrependStrings() throws Exception {
assertThat(prependArray("r", new String[]{"f", "o", "o", "b", "a"}), equalTo("foobar"));
assertThat(prependArray("foobar", new String[0]), equalTo("foobar"));
assertThat(prependArray("", new String[]{"foobar"}), equalTo("foobar"));
assertThat(prependArray("bar", new String[]{"foo"}), equalTo("foobar"));
}
@Test
public void removeEmptyStrings_shouldRemoveEmptyStrings() throws Exception {
assertThat(removeEmptyStrings(new String[]{"aa", "", " ", "bb", "cc", null}), arrayContaining("aa", "bb", "cc"));
assertThat(removeEmptyStrings(new String[0]), emptyArray());
}
@Test
public void removeLeft_shouldRemoveStringFromLeft() throws Exception {
final String[] fixture = {
"foobar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeLeft(el, "foo"), equalTo("bar")));
assertThat(removeLeft("barfoo", "foo"), equalTo("barfoo"));
assertThat(removeLeft("foofoo", "foo"), equalTo("foo"));
}
@Test
public void removeLeft_shouldRemoveStringFromLeftCaseInSensitive() throws Exception {
final String[] fixture = {
"foobar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeLeft(el, "FOO", false), equalTo("bar")));
}
@Test
public void removeNonWords_shouldRemoveAllNonWordsFromInputString() throws Exception {
final String[] fixture = {
"foo bar",
"foo&bar-",
"foobar"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeNonWords(el), equalTo("foobar")));
}
@Test
public void removeRight_shouldRemoveStringFromRight() throws Exception {
final String[] fixture = {
"foobar",
"foo"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeRight(el, "bar"), equalTo("foo")));
assertThat(removeRight("barfoo", "bar"), equalTo("barfoo"));
assertThat(removeRight("barbar", "bar"), equalTo("bar"));
}
@Test
public void removeRight_shouldRemoveStringFromRightCaseInSensitive() throws Exception {
final String[] fixture = {
"foobar",
"foo"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeRight(el, "BAR", false), equalTo("foo")));
}
@Test
public void removeSpaces_shouldRemoveSpacesInTheString() throws Exception {
final String[] fixture = {
"foo bar",
"foo bar ",
" foo bar",
" foo bar "
};
Arrays.stream(fixture).forEach(el -> assertThat(removeSpaces(el), equalTo("foobar")));
}
@Test
public void repeat_shouldRepeatAStringNTimes() throws Exception {
assertThat(repeat("1", 1), equalTo("1"));
assertThat(repeat("1", 2), equalTo("11"));
assertThat(repeat("1", 3), equalTo("111"));
assertThat(repeat("1", 4), equalTo("1111"));
assertThat(repeat("1", 5), equalTo("11111"));
}
@Test
public void replace_shouldReplaceAllOccurrencesOfString() throws Exception {
assertThat(replace("foo bar", "foo", "bar", true), equalTo("bar bar"));
assertThat(replace("foo bar foo", "foo", "bar", true), equalTo("bar bar bar"));
}
@Test
public void replace_shouldReplaceAllOccurrencesOfStringCaseSensitive() throws Exception {
assertThat(replace("FOO bar", "foo", "bar", false), equalTo("bar bar"));
assertThat(replace("FOO bar foo", "foo", "bar", false), equalTo("bar bar bar"));
}
@Test
public void reverse_shouldReverseInputString() throws Exception {
assertThat(reverse(""), equalTo(""));
assertThat(reverse("foo"), equalTo("oof"));
assertThat(reverse("shekhar"), equalTo("rahkehs"));
assertThat(reverse("bar"), equalTo("rab"));
assertThat(reverse("foo_"), equalTo("_oof"));
assertThat(reverse("f"), equalTo("f"));
}
@Test
public void rightPad_shouldRightPadAString() throws Exception {
assertThat(rightPad("1", "0", 5), equalTo("10000"));
assertThat(rightPad("10", "0", 5), equalTo("10000"));
assertThat(rightPad("100", "0", 5), equalTo("10000"));
assertThat(rightPad("1000", "0", 5), equalTo("10000"));
assertThat(rightPad("10000", "0", 5), equalTo("10000"));
assertThat(rightPad("10000000", "0", 5), equalTo("10000000"));
}
@Test
public void rightTrim_shouldRemoveSpacesFromTheRight() throws Exception {
assertThat(rightTrim("strman "), equalTo("strman"));
assertThat(rightTrim(" strman"), equalTo(" strman"));
assertThat(rightTrim("strman"), equalTo("strman"));
}
@Test
public void safeTruncate_shouldSafelyTruncateStrings() throws Exception {
assertThat(safeTruncate("foo bar", 0, "."), equalTo(""));
assertThat(safeTruncate("foo bar", 4, "."), equalTo("foo."));
assertThat(safeTruncate("foo bar", 3, "."), equalTo("."));
assertThat(safeTruncate("foo bar", 2, "."), equalTo("."));
assertThat(safeTruncate("foo bar", 7, "."), equalTo("foo bar"));
assertThat(safeTruncate("foo bar", 8, "."), equalTo("foo bar"));
assertThat(safeTruncate("A Javascript string manipulation library.", 16, "..."), equalTo("A Javascript..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 15, "..."), equalTo("A Javascript..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 14, "..."), equalTo("A..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 13, "..."), equalTo("A..."));
}
@Test
public void truncate_shouldTruncateString() throws Exception {
assertThat(truncate("foo bar", 0, "."), equalTo(""));
assertThat(truncate("foo bar", 3, "."), equalTo("fo."));
assertThat(truncate("foo bar", 2, "."), equalTo("f."));
assertThat(truncate("foo bar", 4, "."), equalTo("foo."));
assertThat(truncate("foo bar", 7, "."), equalTo("foo bar"));
assertThat(truncate("foo bar", 8, "."), equalTo("foo bar"));
assertThat(truncate("A Javascript string manipulation library.", 16, "..."), equalTo("A Javascript ..."));
assertThat(truncate("A Javascript string manipulation library.", 15, "..."), equalTo("A Javascript..."));
assertThat(truncate("A Javascript string manipulation library.", 14, "..."), equalTo("A Javascrip..."));
}
@Test
public void htmlDecode_shouldDecodeToHtml() throws Exception {
assertThat(htmlDecode("á"), equalTo("\u00E1"));
assertThat(htmlDecode("Ш"), equalTo("Ш"));
assertThat(htmlDecode("Ж"), equalTo("Ж"));
assertThat(htmlDecode("┐"), equalTo("┐"));
}
@Test
public void htmlEncode_shouldBeEncodedToHtmlEntities() throws Exception {
assertThat(htmlEncode("á"), equalTo("á"));
assertThat(htmlEncode("áéíóú"), equalTo("áéíóú"));
assertThat(htmlEncode("Ш"), equalTo("Ш"));
assertThat(htmlEncode("Ж"), equalTo("Ж"));
assertThat(htmlEncode("┐"), equalTo("┐"));
}
@Test
public void shuffle_shouldShuffleAString() throws Exception {
assertThat(shuffle("shekhar"), not(equalTo("shekhar")));
assertThat(shuffle("strman"), not(equalTo("strman")));
assertThat(shuffle(""), equalTo(""));
assertThat(shuffle("s"), equalTo("s"));
}
@Test
public void slugify_shouldBeFooBar() throws Exception {
String[] fixture = {
"foo bar",
"foo bar.",
"foo bar ",
" foo bar",
" foo bar ",
"foo------bar",
"fóõ bár",
"foo ! bar",
"foo ~~ bar",
"foo bar",
"FOO bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("slugify(%s) should be foo-bar ", el), slugify(el), equalTo("foo-bar")));
}
@Test
public void slugify_shouldBeFooAndBar() throws Exception {
String[] fixture = {
"foo&bar",
"foo&bar.",
"foo&bar ",
" foo&bar",
" foo&bar ",
"foo&bar",
"fóõ-and---bár",
"foo & bar",
"FOO & bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("slugify(%s) should be foo-and-bar ", el), slugify(el), equalTo("foo-and-bar")));
}
@Test
public void transliterate_shouldTransliterateTheText() throws Exception {
assertThat(transliterate("fóõ bár"), equalTo("foo bar"));
}
@Test
public void surround_shouldSurroundStringWithPrefixAndSuffix() throws Exception {
assertThat(surround("foo", "bar", null), equalTo("barfoobar"));
assertThat(surround("shekhar", "***", null), equalTo("***shekhar***"));
assertThat(surround("", ">", null), equalTo(">>"));
assertThat(surround("bar", "", null), equalTo("bar"));
assertThat(surround("f", null, null), equalTo("f"));
assertThat(surround("div", "<", ">"), equalTo("<div>"));
}
@Test
public void toCamelCase_shouldConvertStringToCamelCase() throws Exception {
String[] fixture = {
"CamelCase",
"camelCase",
"Camel case",
"Camel case",
"camel Case",
"camel-case",
"-camel--case",
"camel_case",
" camel_case",
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("toCameCase(%s) should be camelCase", el), toCamelCase(el), equalTo("camelCase")));
assertThat(toCamelCase("c"), equalTo("c"));
}
@Test
public void toDeCamelCase_shouldDeCamelCaseAString() throws Exception {
String[] fixture = {
"deCamelize",
"de-Camelize",
"de camelize",
"de camelize",
"de Camelize",
"de-camelize",
"-de--camelize",
"de_camelize",
" de_camelize"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("toDecamelize(%s) should be de-camelize", el), toDecamelize(el, null), equalTo("de camelize")));
assertThat(toDecamelize("camelCase", "_"), equalTo("camel_case"));
}
@Test
public void toKebabCase_shouldKebabCaseAString() throws Exception {
String[] fixture = {
"deCamelize",
"de-Camelize",
"de camelize",
"de camelize",
"de Camelize",
"de-camelize",
"-de--camelize",
"de_camelize",
" de_camelize"
};
Arrays.stream(fixture).forEach(el ->
assertThat(String.format("toKebabCase(%s) should be de-camelize", el), toKebabCase(el), equalTo("de-camelize")));
}
@Test
public void toSnakeCase_shouldSnakeCaseAString() throws Exception {
String[] fixture = {
"deCamelize",
"de-Camelize",
"de camelize",
"de camelize",
"de Camelize",
"de-camelize",
"-de--camelize",
"de_camelize",
" de_camelize"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("toSnakeCase(%s) should be de_camelize", el), toSnakeCase(el), equalTo("de_camelize")));
}
@Test
public void unequal_shouldTestInequalityOfStrings() throws Exception {
assertThat(unequal("a", "b"), equalTo(true));
assertThat(unequal("a", "a"), equalTo(false));
assertThat(unequal("0", "1"), equalTo(true));
}
@Test
public void removeLeft_shouldNotLowercaseWhenCaseInsensitive() throws Exception {
String result = removeLeft("This HAS A THIS IN FRONT", "THIS ", false);
assertThat(result, is("HAS A THIS IN FRONT"));
}
@Test
public void replace_shouldNotLowercaseWhenCaseInsensitive() throws Exception {
String result = replace("One and two and THREE and Four", "and", "&", false);
assertThat(result, is("One & two & THREE & Four"));
}
@Test
public void removeRight_shouldNotLowercaseWhenCaseInsensitive() throws Exception {
String result = removeRight("Remove the END at the end", " END", false);
assertThat(result, is("Remove the END at the"));
}
@Test
public void transliterate_shouldDeburrTheString() throws Exception {
String result = transliterate("déjà vu");
assertThat(result, is(equalTo("deja vu")));
}
@Ignore
public void htmlEncode_shouldConvertCharactersToTheirHtmlEntities() throws Exception {
String result = htmlEncode("fred, barney, & pebbles");
assertThat(result, is(equalTo("fred, barney, & pebbles")));
}
@Ignore
public void kebabCase_shouldConvertAStringToKebabCase() throws Exception {
String[] input = {
"Foo Bar",
"fooBar",
"__FOO_BAR__"
};
Arrays.stream(input).forEach(el ->
assertThat(String.format("%s should be foo-bar", el), toKebabCase(el), is(equalTo("foo-bar"))));
}
@Ignore
public void snakeCase_shouldConvertAStringToSnakecase() throws Exception {
String[] input = {
"Foo Bar",
"fooBar",
"--FOO-BAR--"
};
Arrays.stream(input).forEach(el ->
assertThat(String.format("%s should be foo_bar", el), toSnakeCase(el), is(equalTo("foo_bar"))));
}
@Test
public void join_shouldJoinArrayOfStringIntoASingleString() throws Exception {
String[] strings = {
"hello",
"world",
"123"
};
assertThat(join(strings, ";"), is(equalTo("hello;world;123")));
}
@Test(expected = IllegalArgumentException.class)
public void join_shouldThrowIllegalArgumentExceptionWhenSeparatorIsNull() throws Exception {
String[] strings = {
"hello",
"world",
"123"
};
join(strings, null);
}
@Test
public void join_shouldReturnEmptyStringWhenInputArrayIsEmpty() throws Exception {
String[] emptyArray = {};
assertThat(join(emptyArray, ","), is(equalTo("")));
}
@Test
public void capitalize_shouldCapitalizeFirstCharacterOfString() throws Exception {
String[] strings = {
"FRED",
"fRED",
"fred"
};
Arrays.stream(strings).forEach(el -> assertThat(String.format("%s should be Fred", el), capitalize(el), equalTo("Fred")));
}
@Test
public void lowerFirst_shouldLowercasedFirstCharacterOfString() throws Exception {
assertThat(lowerFirst("FRED"), is(equalTo("fRED")));
assertThat(lowerFirst("fred"), is(equalTo("fred")));
assertThat(lowerFirst("Fred"), is(equalTo("fred")));
}
@Test
public void isEnclosedBetween_shouldChekcWhetherStringIsEnclosed() throws Exception {
assertThat(isEnclosedBetween("{{shekhar}}", "{{", "}}"), is(true));
assertThat(isEnclosedBetween("shekhar", "{{", "}}"), is(false));
assertThat(isEnclosedBetween("*shekhar*", "*"), is(true));
assertThat(isEnclosedBetween("shekhar", "*"), is(false));
}
@Test(expected = IllegalArgumentException.class)
public void isEnclosedBetween_shouldThrowIllegalArgumentExceptionWhenEncloserIsNull() throws Exception {
assertThat(isEnclosedBetween("shekhar", null), is(false));
}
@Test
public void words_shouldConvertTextToWords() throws Exception {
final String line = "This is a string, with words!";
assertThat(words(line), is(new String[]{"This", "is", "a", "string", "with", "words"}));
}
@Test
public void upperFirst_shouldConvertFirstCharToUpperCase() throws Exception {
assertThat(upperFirst("fred"), is("Fred"));
}
@Test
public void upperFirst_shouldReturnSameStringIfFirstCharIsUpperCase() throws Exception {
assertThat(upperFirst("FRED"), is("FRED"));
}
@Test
public void trimStart_shouldRemoveAllWhitespaceAtStart() throws Exception {
assertThat(trimStart(" abc "), is(Optional.of("abc ")));
assertThat(trimStart("abc "), is(Optional.of("abc ")));
assertThat(trimStart("abc"), is(Optional.of("abc")));
assertThat(trimStart(""), is(Optional.empty()));
assertThat(trimStart(null), is(Optional.empty()));
}
@Test
public void trimStart_shouldRemoveSpecialCharactersAtStart() throws Exception {
assertThat(trimStart("-_-abc-_-", "_", "-"), is(Optional.of("abc-_-")));
assertThat(trimStart("-_-!abc-_-", "_", "-", "!"), is(Optional.of("abc-_-")));
assertThat(trimStart("-_-#abc-_-", "_", "-", "!", "#"), is(Optional.of("abc-_-")));
}
@Test
public void trimEnd_shouldRemoveAllTrailingWhitespace() throws Exception {
assertThat(trimEnd(" abc "), is(Optional.of(" abc")));
assertThat(trimEnd("abc "), is(Optional.of("abc")));
assertThat(trimEnd("abc"), is(Optional.of("abc")));
assertThat(trimEnd(""), is(Optional.empty()));
assertThat(trimEnd(null), is(Optional.empty()));
}
@Test
public void trimEnd_shouldRemoveAllTrailingSpecialCharacters() throws Exception {
assertThat(trimEnd("-_-abc-_-", "_", "-"), is(Optional.of("-_-abc")));
assertThat(trimEnd("-_-abc!-_-", "_", "-", "!"), is(Optional.of("-_-abc")));
assertThat(trimEnd("-_-abc#-_-", "_", "-", "!", "#"), is(Optional.of("-_-abc")));
}
} | src/test/java/strman/StrmanTest.java | /*
*
* * The MIT License
* *
* * Copyright 2016 Shekhar Gulati <[email protected]>.
* *
* * 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.
*
*/
package strman;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsArrayContainingInOrder.arrayContaining;
import static org.hamcrest.collection.IsArrayWithSize.emptyArray;
import static org.junit.Assert.*;
import static strman.Strman.*;
import static strman.Strman.endsWith;
import static strman.Strman.format;
public class StrmanTest {
@Test
public void append_shouldAppendStringsToEndOfValue() throws Exception {
assertThat(append("f", "o", "o", "b", "a", "r"), equalTo("foobar"));
assertThat(append("foobar"), equalTo("foobar"));
assertThat(append("", "foobar"), equalTo("foobar"));
}
@Test(expected = IllegalArgumentException.class)
public void append_shouldThrowIllegalArgumentExceptionWhenValueIsNull() throws Exception {
append(null);
}
@Test
public void appendArray_shouldAppendStringArrayToEndOfValue() throws Exception {
assertThat(appendArray("f", new String[]{"o", "o", "b", "a", "r"}), equalTo("foobar"));
assertThat(appendArray("foobar", new String[]{}), equalTo("foobar"));
assertThat(appendArray("", new String[]{"foobar"}), equalTo("foobar"));
}
@Test(expected = IllegalArgumentException.class)
public void appendArray_ShouldThrowIllegalArgumentExceptionWhenValueIsNull() throws Exception {
appendArray(null, new String[]{});
}
@Test
public void at_shouldFindCharacterAtIndex() throws Exception {
assertThat(at("foobar", 0), equalTo(Optional.of("f")));
assertThat(at("foobar", 1), equalTo(Optional.of("o")));
assertThat(at("foobar", -1), equalTo(Optional.of("r")));
assertThat(at("foobar", -2), equalTo(Optional.of("a")));
assertThat(at("foobar", 10), equalTo(Optional.empty()));
assertThat(at("foobar", -10), equalTo(Optional.empty()));
}
@Test
public void between_shouldReturnArrayWithStringsBetweenStartAndEnd() throws Exception {
assertThat(between("[abc][def]", "[", "]"), arrayContaining("abc", "def"));
assertThat(between("<span>foo</span>", "<span>", "</span>"), arrayContaining("foo"));
assertThat(between("<span>foo</span><span>bar</span>", "<span>", "</span>"), arrayContaining("foo", "bar"));
}
@Test
public void between_shouldReturnFullStringWhenStartAndEndDoesNotExist() throws Exception {
assertThat(between("[abc][def]", "{", "}"), arrayContaining("[abc][def]"));
assertThat(between("", "{", "}"), arrayContaining(""));
}
@Test
public void chars_shouldReturnAllCharactersInString() throws Exception {
final String title = "title";
assertThat(chars(title), equalTo(new String[]{"t", "i", "t", "l", "e"}));
}
@Test
public void collapseWhitespace_shouldReplaceConsecutiveWhitespaceWithSingleSpace() throws Exception {
String[] fixture = {
"foo bar",
" foo bar ",
" foo bar ",
" foo bar "
};
Arrays.stream(fixture).forEach(el -> assertThat(collapseWhitespace(el), equalTo("foo bar")));
}
@Test
public void collapseWhitespace_shouldReplaceConsecutiveWhitespaceBetweenMultipleStrings() throws Exception {
String input = " foo bar bazz hello world ";
assertThat(collapseWhitespace(input), equalTo("foo bar bazz hello world"));
}
@Test
public void containsWithCaseSensitiveFalse_shouldReturnTrueWhenStringContainsNeedle() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
"foo"
};
Arrays.stream(fixture).forEach(el -> assertTrue(contains(el, "FOO")));
}
@Test
public void containsWithCaseSensitiveTrue_shouldReturnTrueWhenStringContainsNeedle() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
"foo"
};
Arrays.stream(fixture).forEach(el -> assertFalse(contains(el, "FOO", true)));
}
@Test
public void containsAll_shouldReturnTrueOnlyWhenAllNeedlesAreContainedInValue() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
};
Arrays.stream(fixture).forEach(el -> assertTrue(containsAll(el, new String[]{"foo", "bar"})));
}
@Test
public void containsAll_shouldReturnFalseOnlyWhenAllNeedlesAreNotContainedInValue() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
};
Arrays.stream(fixture).forEach(el -> assertFalse(containsAll(el, new String[]{"FOO", "bar"}, true)));
}
@Test
public void containsAny_shouldReturnTrueWhenAnyOfSearchNeedleExistInInputValue() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
};
Arrays.stream(fixture).forEach(el -> assertTrue(containsAny(el, new String[]{"foo", "bar", "test"})));
}
@Test
public void containsAny_shouldReturnFalseWhenNoneOfSearchNeedleExistInInputValue() throws Exception {
String[] fixture = {
"foo bar",
"bar foo",
"foobar",
};
Arrays.stream(fixture).forEach(el -> assertFalse(containsAny(el, new String[]{"FOO", "BAR", "Test"}, true)));
}
@Test
public void countSubstr_shouldCountSubStrCountCaseInsensitiveWithoutOverlapInValue() throws Exception {
assertThat(countSubstr("aaaAAAaaa", "aaa", false, false), equalTo(3L));
}
@Test
public void countSubstr_shouldCountSubStrCountCaseSensitiveWithoutOverlapInValue() throws Exception {
assertThat(countSubstr("aaaAAAaaa", "aaa"), equalTo(2L));
}
@Test
public void countSubstr_shouldCountSubStrCountCaseInsensitiveWithOverlapInValue() throws Exception {
assertThat(countSubstr("aaaAAAaaa", "aaa", false, true), equalTo(7L));
}
@Test
public void countSubstr_shouldCountSubStrCountCaseSensitiveWithOverlapInValue() throws Exception {
assertThat(countSubstr("aaaAAAaaa", "AAA", true, true), equalTo(1L));
}
@Test
public void countSubstrTestFixture_caseSensitiveTrueAndOverlappingFalse() throws Exception {
String[] fixture = {
"aaaaaAaaAA",
"faaaAAaaaaAA",
"aaAAaaaaafA",
"AAaaafaaaaAAAA"
};
Arrays.stream(fixture).forEach(el -> assertThat(countSubstr(el, "a", true, false), equalTo(7L)));
}
@Test
public void countSubstrTestFixture_caseSensitiveFalseAndOverlappingFalse() throws Exception {
String[] fixture = {
"aaaaaaa",
"faaaaaaa",
"aaaaaaaf",
"aaafaaaa"
};
Arrays.stream(fixture).forEach(el -> assertThat(countSubstr(el, "A", false, false), equalTo(7L)));
}
@Test
public void countSubstrTestFixture_caseSensitiveTrueAndOverlappingTrue() throws Exception {
assertThat(countSubstr("aaa", "aa", true, true), equalTo(2L));
}
@Test
public void endsWith_caseSensitive_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {
String[] fixture = {
"foo bar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "bar")));
}
@Test
public void endsWith_notCaseSensitive_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {
String[] fixture = {
"foo bar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "BAR", false)));
}
@Test
public void endsWith_caseSensitiveAtPosition_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {
String[] fixture = {
"foo barr",
"barr"
};
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "bar", el.length() - 1, true)));
}
@Test
public void endsWith_notCaseSensitiveAtPosition_ShouldBeTrueWhenStringEndsWithSearchStr() throws Exception {
String[] fixture = {
"foo barr",
"barr"
};
Arrays.stream(fixture).forEach(el -> assertTrue(endsWith(el, "BAR", el.length() - 1, false)));
}
@Test
public void ensureLeft_shouldEnsureValueStartsWithFoo() throws Exception {
String[] fixture = {
"foobar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(ensureLeft(el, "foo"), equalTo("foobar")));
}
@Test
public void ensureLeft_notCaseSensitive_shouldEnsureValueStartsWithFoo() throws Exception {
assertThat(ensureLeft("foobar", "FOO", false), equalTo("foobar"));
assertThat(ensureLeft("bar", "FOO", false), equalTo("FOObar"));
}
@Test
public void base64Decode_shouldDecodeABase64DecodedValueToString() throws Exception {
assertThat(base64Decode("c3RybWFu"), equalTo("strman"));
assertThat(base64Decode("Zm9v"), equalTo("foo"));
assertThat(base64Decode("YmFy"), equalTo("bar"));
assertThat(base64Decode("YsOhciE="), equalTo("bár!"));
assertThat(base64Decode("5ryi"), equalTo("漢"));
}
@Test
public void base64Encode_shouldEncodeAString() throws Exception {
assertThat(base64Encode("strman"), equalTo("c3RybWFu"));
assertThat(base64Encode("foo"), equalTo("Zm9v"));
assertThat(base64Encode("bar"), equalTo("YmFy"));
assertThat(base64Encode("bár!"), equalTo("YsOhciE="));
assertThat(base64Encode("漢"), equalTo("5ryi"));
}
@Test
public void binDecode_shouldDecodeABinaryStringToAValue() throws Exception {
assertThat(
binDecode("000000000111001100000000011101000000000001110010000000000110110100000000011000010000000001101110"),
equalTo("strman"));
assertThat(binDecode("0110111100100010"), equalTo("漢"));
assertThat(binDecode("0000000001000001"), equalTo("A"));
assertThat(binDecode("0000000011000001"), equalTo("Á"));
assertThat(binDecode("00000000010000010000000001000001"), equalTo("AA"));
}
@Test
public void binEncode_shouldEncodeAStringToBinaryFormat() throws Exception {
assertThat(binEncode("漢"), equalTo("0110111100100010"));
assertThat(binEncode("A"), equalTo("0000000001000001"));
assertThat(binEncode("Á"), equalTo("0000000011000001"));
assertThat(binEncode("AA"), equalTo("00000000010000010000000001000001"));
}
@Test
public void decDecode_shouldDecodeDecimalStringToString() throws Exception {
assertThat(decDecode("28450"), equalTo("漢"));
assertThat(decDecode("00065"), equalTo("A"));
assertThat(decDecode("00193"), equalTo("Á"));
assertThat(decDecode("0006500065"), equalTo("AA"));
}
@Test
public void decEncode_shouldEncodeStringToDecimal() throws Exception {
assertThat(decEncode("漢"), equalTo("28450"));
assertThat(decEncode("A"), equalTo("00065"));
assertThat(decEncode("Á"), equalTo("00193"));
assertThat(decEncode("AA"), equalTo("0006500065"));
}
@Test
public void ensureRight_shouldEnsureStringEndsWithBar() throws Exception {
final String[] fixture = {
"foo", "foobar", "fooBAR"
};
assertThat(Arrays.stream(fixture).map(el -> ensureRight(el, "bar", false)).collect(toList()), hasItems("foobar", "foobar", "fooBAR"));
assertThat(Arrays.stream(fixture).map(el -> ensureRight(el, "bar")).collect(toList()), hasItems("foobar", "foobar", "fooBARbar"));
}
@Test
public void first_shouldReturnFirstThreeCharsOfString() throws Exception {
final String[] fixture = {
"foo", "foobar"
};
Arrays.stream(fixture).forEach(el -> assertThat(first(el, 3), equalTo(Optional.of("foo"))));
}
@Test
public void head_shouldReturnFirstCharOfString() throws Exception {
final String[] fixture = {
"foo", "foobar"
};
Arrays.stream(fixture).forEach(el -> assertThat(head(el), equalTo(Optional.of("f"))));
}
@Test
public void format_shouldFormatStringsToFooBar() throws Exception {
assertThat(format("{0} bar", "foo"), equalTo("foo bar"));
assertThat(format("foo {0}", "bar"), equalTo("foo bar"));
assertThat(format("foo {0}", "bar", "foo"), equalTo("foo bar"));
assertThat(format("{0} {1}", "foo", "bar"), equalTo("foo bar"));
assertThat(format("{1} {0}", "bar", "foo"), equalTo("foo bar"));
}
@Test(expected = IllegalArgumentException.class)
public void format_shouldThrowExceptionWhenValueDoesNotExist() throws Exception {
assertThat(format("{1} {0}"), equalTo("{1} {0}"));
}
@Test
public void hexDecode_shouldDecodeHexCodeToString() throws Exception {
assertThat(hexDecode("6f22"), equalTo("漢"));
assertThat(hexDecode("0041"), equalTo("A"));
assertThat(hexDecode("00c1"), equalTo("Á"));
assertThat(hexDecode("00410041"), equalTo("AA"));
}
@Test
public void hexEncode_shouldEncodeStringToHexadecimalFormat() throws Exception {
assertThat(hexEncode("漢"), equalTo("6f22"));
assertThat(hexEncode("A"), equalTo("0041"));
assertThat(hexEncode("Á"), equalTo("00c1"));
assertThat(hexEncode("AA"), equalTo("00410041"));
}
@Test
public void indexOf_shouldBeTrueWhenNeedleExists() throws Exception {
final String value = "foobar";
assertThat(indexOf(value, "f", 0, true), equalTo(0));
assertThat(indexOf(value, "o", 0, true), equalTo(1));
assertThat(indexOf(value, "b", 0, true), equalTo(3));
assertThat(indexOf(value, "a", 0, true), equalTo(4));
assertThat(indexOf(value, "r", 0, true), equalTo(5));
assertThat(indexOf(value, "t", 0, true), equalTo(-1));
}
@Test
public void indexOf_shouldBeTrueWhenNeedleExistCaseSensitive() throws Exception {
final String value = "foobar";
assertThat(indexOf(value, "F", 0, false), equalTo(0));
assertThat(indexOf(value, "O", 0, false), equalTo(1));
assertThat(indexOf(value, "B", 0, false), equalTo(3));
assertThat(indexOf(value, "A", 0, false), equalTo(4));
assertThat(indexOf(value, "R", 0, false), equalTo(5));
assertThat(indexOf(value, "T", 0, false), equalTo(-1));
}
@Test
public void inequal_shouldTestInequalityOfStrings() throws Exception {
assertThat(unequal("a", "b"), equalTo(true));
assertThat(unequal("a", "a"), equalTo(false));
assertThat(unequal("0", "1"), equalTo(true));
}
@Test
public void insert_shouldInsertStringAtIndex() throws Exception {
assertThat(insert("fbar", "oo", 1), equalTo("foobar"));
assertThat(insert("foo", "bar", 3), equalTo("foobar"));
assertThat(insert("foobar", "x", 5), equalTo("foobaxr"));
assertThat(insert("foobar", "x", 6), equalTo("foobarx"));
assertThat(insert("foo bar", "asadasd", 100), equalTo("foo bar"));
}
@Test
public void isLowerCase_shouldBeTrueWhenStringIsLowerCase() throws Exception {
assertThat(isLowerCase(""), equalTo(true));
assertThat(isLowerCase("foo"), equalTo(true));
assertThat(isLowerCase("foobarfoo"), equalTo(true));
}
@Test
public void isLowerCase_shouldBeFalseWhenStringIsNotLowerCase() throws Exception {
assertThat(isLowerCase("Foo"), equalTo(false));
assertThat(isLowerCase("foobarfooA"), equalTo(false));
}
@Test
public void isUpperCase_shouldBeTrueWhenStringIsUpperCase() throws Exception {
assertThat(isUpperCase(""), equalTo(true));
assertThat(isUpperCase("FOO"), equalTo(true));
assertThat(isUpperCase("FOOBARFOO"), equalTo(true));
}
@Test
public void isUpperCase_shouldBeFalseWhenStringIsNotUpperCase() throws Exception {
assertThat(isUpperCase("Foo"), equalTo(false));
assertThat(isUpperCase("foobarfooA"), equalTo(false));
}
@Test
public void last_shouldReturnLastNChars() throws Exception {
assertThat(last("foo", 3), equalTo("foo"));
assertThat(last("foobarfoo", 3), equalTo("foo"));
assertThat(last("", 3), equalTo(""));
assertThat(last("f", 3), equalTo("f"));
}
@Test
public void leftPad_shouldAddPaddingOnTheLeft() throws Exception {
assertThat(leftPad("1", "0", 5), equalTo("00001"));
assertThat(leftPad("01", "0", 5), equalTo("00001"));
assertThat(leftPad("001", "0", 5), equalTo("00001"));
assertThat(leftPad("0001", "0", 5), equalTo("00001"));
assertThat(leftPad("00001", "0", 5), equalTo("00001"));
}
@Test
public void isString_shouldBeFalseWhenValueIsNotString() throws Exception {
assertFalse(isString(1));
assertFalse(isString(false));
assertFalse(isString(1.2));
assertFalse(isString(new String[]{}));
}
@Test
public void isString_shouldBeTrueWhenValueIsString() throws Exception {
assertTrue(isString("string"));
assertTrue(isString(""));
}
@Test
public void lastIndexOf_shouldFindIndexOfNeedle() throws Exception {
final String value = "foobarfoobar";
assertThat(lastIndexOf(value, "f"), equalTo(6));
assertThat(lastIndexOf(value, "o"), equalTo(8));
assertThat(lastIndexOf(value, "b"), equalTo(9));
assertThat(lastIndexOf(value, "a"), equalTo(10));
assertThat(lastIndexOf(value, "r"), equalTo(11));
assertThat(lastIndexOf(value, "t"), equalTo(-1));
}
@Test
public void lastIndexOf_shouldFindIndexOfNeedleCaseInsensitive() throws Exception {
final String value = "foobarfoobar";
assertThat(lastIndexOf(value, "F", false), equalTo(6));
assertThat(lastIndexOf(value, "O", false), equalTo(8));
assertThat(lastIndexOf(value, "B", false), equalTo(9));
assertThat(lastIndexOf(value, "A", false), equalTo(10));
assertThat(lastIndexOf(value, "R", false), equalTo(11));
assertThat(lastIndexOf(value, "T", false), equalTo(-1));
}
@Test
public void leftTrim_shouldRemoveSpacesOnLeft() throws Exception {
assertThat(leftTrim(" strman"), equalTo("strman"));
assertThat(leftTrim(" strman "), equalTo("strman "));
}
@Test
public void prepend_shouldPrependStrings() throws Exception {
assertThat(prepend("r", "f", "o", "o", "b", "a"), equalTo("foobar"));
assertThat(prepend("foobar"), equalTo("foobar"));
assertThat(prepend("", "foobar"), equalTo("foobar"));
assertThat(prepend("bar", "foo"), equalTo("foobar"));
}
@Test
public void prependArray_shouldPrependStrings() throws Exception {
assertThat(prependArray("r", new String[]{"f", "o", "o", "b", "a"}), equalTo("foobar"));
assertThat(prependArray("foobar", new String[0]), equalTo("foobar"));
assertThat(prependArray("", new String[]{"foobar"}), equalTo("foobar"));
assertThat(prependArray("bar", new String[]{"foo"}), equalTo("foobar"));
}
@Test
public void removeEmptyStrings_shouldRemoveEmptyStrings() throws Exception {
assertThat(removeEmptyStrings(new String[]{"aa", "", " ", "bb", "cc", null}), arrayContaining("aa", "bb", "cc"));
assertThat(removeEmptyStrings(new String[0]), emptyArray());
}
@Test
public void removeLeft_shouldRemoveStringFromLeft() throws Exception {
final String[] fixture = {
"foobar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeLeft(el, "foo"), equalTo("bar")));
assertThat(removeLeft("barfoo", "foo"), equalTo("barfoo"));
assertThat(removeLeft("foofoo", "foo"), equalTo("foo"));
}
@Test
public void removeLeft_shouldRemoveStringFromLeftCaseInSensitive() throws Exception {
final String[] fixture = {
"foobar",
"bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeLeft(el, "FOO", false), equalTo("bar")));
}
@Test
public void removeNonWords_shouldRemoveAllNonWordsFromInputString() throws Exception {
final String[] fixture = {
"foo bar",
"foo&bar-",
"foobar"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeNonWords(el), equalTo("foobar")));
}
@Test
public void removeRight_shouldRemoveStringFromRight() throws Exception {
final String[] fixture = {
"foobar",
"foo"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeRight(el, "bar"), equalTo("foo")));
assertThat(removeRight("barfoo", "bar"), equalTo("barfoo"));
assertThat(removeRight("barbar", "bar"), equalTo("bar"));
}
@Test
public void removeRight_shouldRemoveStringFromRightCaseInSensitive() throws Exception {
final String[] fixture = {
"foobar",
"foo"
};
Arrays.stream(fixture).forEach(el -> assertThat(removeRight(el, "BAR", false), equalTo("foo")));
}
@Test
public void removeSpaces_shouldRemoveSpacesInTheString() throws Exception {
final String[] fixture = {
"foo bar",
"foo bar ",
" foo bar",
" foo bar "
};
Arrays.stream(fixture).forEach(el -> assertThat(removeSpaces(el), equalTo("foobar")));
}
@Test
public void repeat_shouldRepeatAStringNTimes() throws Exception {
assertThat(repeat("1", 1), equalTo("1"));
assertThat(repeat("1", 2), equalTo("11"));
assertThat(repeat("1", 3), equalTo("111"));
assertThat(repeat("1", 4), equalTo("1111"));
assertThat(repeat("1", 5), equalTo("11111"));
}
@Test
public void replace_shouldReplaceAllOccurrencesOfString() throws Exception {
assertThat(replace("foo bar", "foo", "bar", true), equalTo("bar bar"));
assertThat(replace("foo bar foo", "foo", "bar", true), equalTo("bar bar bar"));
}
@Test
public void replace_shouldReplaceAllOccurrencesOfStringCaseSensitive() throws Exception {
assertThat(replace("FOO bar", "foo", "bar", false), equalTo("bar bar"));
assertThat(replace("FOO bar foo", "foo", "bar", false), equalTo("bar bar bar"));
}
@Test
public void reverse_shouldReverseInputString() throws Exception {
assertThat(reverse(""), equalTo(""));
assertThat(reverse("foo"), equalTo("oof"));
assertThat(reverse("shekhar"), equalTo("rahkehs"));
assertThat(reverse("bar"), equalTo("rab"));
assertThat(reverse("foo_"), equalTo("_oof"));
assertThat(reverse("f"), equalTo("f"));
}
@Test
public void rightPad_shouldRightPadAString() throws Exception {
assertThat(rightPad("1", "0", 5), equalTo("10000"));
assertThat(rightPad("10", "0", 5), equalTo("10000"));
assertThat(rightPad("100", "0", 5), equalTo("10000"));
assertThat(rightPad("1000", "0", 5), equalTo("10000"));
assertThat(rightPad("10000", "0", 5), equalTo("10000"));
assertThat(rightPad("10000000", "0", 5), equalTo("10000000"));
}
@Test
public void rightTrim_shouldRemoveSpacesFromTheRight() throws Exception {
assertThat(rightTrim("strman "), equalTo("strman"));
assertThat(rightTrim(" strman"), equalTo(" strman"));
assertThat(rightTrim("strman"), equalTo("strman"));
}
@Test
public void safeTruncate_shouldSafelyTruncateStrings() throws Exception {
assertThat(safeTruncate("foo bar", 0, "."), equalTo(""));
assertThat(safeTruncate("foo bar", 4, "."), equalTo("foo."));
assertThat(safeTruncate("foo bar", 3, "."), equalTo("."));
assertThat(safeTruncate("foo bar", 2, "."), equalTo("."));
assertThat(safeTruncate("foo bar", 7, "."), equalTo("foo bar"));
assertThat(safeTruncate("foo bar", 8, "."), equalTo("foo bar"));
assertThat(safeTruncate("A Javascript string manipulation library.", 16, "..."), equalTo("A Javascript..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 15, "..."), equalTo("A Javascript..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 14, "..."), equalTo("A..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 13, "..."), equalTo("A..."));
}
@Test
public void truncate_shouldTruncateString() throws Exception {
assertThat(truncate("foo bar", 0, "."), equalTo(""));
assertThat(truncate("foo bar", 3, "."), equalTo("fo."));
assertThat(truncate("foo bar", 2, "."), equalTo("f."));
assertThat(truncate("foo bar", 4, "."), equalTo("foo."));
assertThat(truncate("foo bar", 7, "."), equalTo("foo bar"));
assertThat(truncate("foo bar", 8, "."), equalTo("foo bar"));
assertThat(truncate("A Javascript string manipulation library.", 16, "..."), equalTo("A Javascript ..."));
assertThat(truncate("A Javascript string manipulation library.", 15, "..."), equalTo("A Javascript..."));
assertThat(truncate("A Javascript string manipulation library.", 14, "..."), equalTo("A Javascrip..."));
}
@Test
public void htmlDecode_shouldDecodeToHtml() throws Exception {
assertThat(htmlDecode("á"), equalTo("\u00E1"));
assertThat(htmlDecode("Ш"), equalTo("Ш"));
assertThat(htmlDecode("Ж"), equalTo("Ж"));
assertThat(htmlDecode("┐"), equalTo("┐"));
}
@Test
public void htmlEncode_shouldBeEncodedToHtmlEntities() throws Exception {
assertThat(htmlEncode("á"), equalTo("á"));
assertThat(htmlEncode("áéíóú"), equalTo("áéíóú"));
assertThat(htmlEncode("Ш"), equalTo("Ш"));
assertThat(htmlEncode("Ж"), equalTo("Ж"));
assertThat(htmlEncode("┐"), equalTo("┐"));
}
@Test
public void shuffle_shouldShuffleAString() throws Exception {
assertThat(shuffle("shekhar"), not(equalTo("shekhar")));
assertThat(shuffle("strman"), not(equalTo("strman")));
assertThat(shuffle(""), equalTo(""));
assertThat(shuffle("s"), equalTo("s"));
}
@Test
public void slugify_shouldBeFooBar() throws Exception {
String[] fixture = {
"foo bar",
"foo bar.",
"foo bar ",
" foo bar",
" foo bar ",
"foo------bar",
"fóõ bár",
"foo ! bar",
"foo ~~ bar",
"foo bar",
"FOO bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("slugify(%s) should be foo-bar ", el), slugify(el), equalTo("foo-bar")));
}
@Test
public void slugify_shouldBeFooAndBar() throws Exception {
String[] fixture = {
"foo&bar",
"foo&bar.",
"foo&bar ",
" foo&bar",
" foo&bar ",
"foo&bar",
"fóõ-and---bár",
"foo & bar",
"FOO & bar"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("slugify(%s) should be foo-and-bar ", el), slugify(el), equalTo("foo-and-bar")));
}
@Test
public void transliterate_shouldTransliterateTheText() throws Exception {
assertThat(transliterate("fóõ bár"), equalTo("foo bar"));
}
@Test
public void surround_shouldSurroundStringWithPrefixAndSuffix() throws Exception {
assertThat(surround("foo", "bar", null), equalTo("barfoobar"));
assertThat(surround("shekhar", "***", null), equalTo("***shekhar***"));
assertThat(surround("", ">", null), equalTo(">>"));
assertThat(surround("bar", "", null), equalTo("bar"));
assertThat(surround("f", null, null), equalTo("f"));
assertThat(surround("div", "<", ">"), equalTo("<div>"));
}
@Test
public void toCamelCase_shouldConvertStringToCamelCase() throws Exception {
String[] fixture = {
"CamelCase",
"camelCase",
"Camel case",
"Camel case",
"camel Case",
"camel-case",
"-camel--case",
"camel_case",
" camel_case",
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("toCameCase(%s) should be camelCase", el), toCamelCase(el), equalTo("camelCase")));
assertThat(toCamelCase("c"), equalTo("c"));
}
@Test
public void toDeCamelCase_shouldDeCamelCaseAString() throws Exception {
String[] fixture = {
"deCamelize",
"de-Camelize",
"de camelize",
"de camelize",
"de Camelize",
"de-camelize",
"-de--camelize",
"de_camelize",
" de_camelize"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("toDecamelize(%s) should be de-camelize", el), toDecamelize(el, null), equalTo("de camelize")));
assertThat(toDecamelize("camelCase", "_"), equalTo("camel_case"));
}
@Test
public void toKebabCase_shouldKebabCaseAString() throws Exception {
String[] fixture = {
"deCamelize",
"de-Camelize",
"de camelize",
"de camelize",
"de Camelize",
"de-camelize",
"-de--camelize",
"de_camelize",
" de_camelize"
};
Arrays.stream(fixture).forEach(el ->
assertThat(String.format("toKebabCase(%s) should be de-camelize", el), toKebabCase(el), equalTo("de-camelize")));
}
@Test
public void toSnakeCase_shouldSnakeCaseAString() throws Exception {
String[] fixture = {
"deCamelize",
"de-Camelize",
"de camelize",
"de camelize",
"de Camelize",
"de-camelize",
"-de--camelize",
"de_camelize",
" de_camelize"
};
Arrays.stream(fixture).forEach(el -> assertThat(String.format("toSnakeCase(%s) should be de_camelize", el), toSnakeCase(el), equalTo("de_camelize")));
}
@Test
public void unequal_shouldTestInequalityOfStrings() throws Exception {
assertThat(unequal("a", "b"), equalTo(true));
assertThat(unequal("a", "a"), equalTo(false));
assertThat(unequal("0", "1"), equalTo(true));
}
@Test
public void removeLeft_shouldNotLowercaseWhenCaseInsensitive() throws Exception {
String result = removeLeft("This HAS A THIS IN FRONT", "THIS ", false);
assertThat(result, is("HAS A THIS IN FRONT"));
}
@Test
public void replace_shouldNotLowercaseWhenCaseInsensitive() throws Exception {
String result = replace("One and two and THREE and Four", "and", "&", false);
assertThat(result, is("One & two & THREE & Four"));
}
@Test
public void removeRight_shouldNotLowercaseWhenCaseInsensitive() throws Exception {
String result = removeRight("Remove the END at the end", " END", false);
assertThat(result, is("Remove the END at the"));
}
@Test
public void transliterate_shouldDeburrTheString() throws Exception {
String result = transliterate("déjà vu");
assertThat(result, is(equalTo("deja vu")));
}
@Ignore
public void htmlEncode_shouldConvertCharactersToTheirHtmlEntities() throws Exception {
String result = htmlEncode("fred, barney, & pebbles");
assertThat(result, is(equalTo("fred, barney, & pebbles")));
}
@Ignore
public void kebabCase_shouldConvertAStringToKebabCase() throws Exception {
String[] input = {
"Foo Bar",
"fooBar",
"__FOO_BAR__"
};
Arrays.stream(input).forEach(el ->
assertThat(String.format("%s should be foo-bar", el), toKebabCase(el), is(equalTo("foo-bar"))));
}
@Ignore
public void snakeCase_shouldConvertAStringToSnakecase() throws Exception {
String[] input = {
"Foo Bar",
"fooBar",
"--FOO-BAR--"
};
Arrays.stream(input).forEach(el ->
assertThat(String.format("%s should be foo_bar", el), toSnakeCase(el), is(equalTo("foo_bar"))));
}
@Test
public void join_shouldJoinArrayOfStringIntoASingleString() throws Exception {
String[] strings = {
"hello",
"world",
"123"
};
assertThat(join(strings, ";"), is(equalTo("hello;world;123")));
}
@Test(expected = IllegalArgumentException.class)
public void join_shouldThrowIllegalArgumentExceptionWhenSeparatorIsNull() throws Exception {
String[] strings = {
"hello",
"world",
"123"
};
join(strings, null);
}
@Test
public void join_shouldReturnEmptyStringWhenInputArrayIsEmpty() throws Exception {
String[] emptyArray = {};
assertThat(join(emptyArray, ","), is(equalTo("")));
}
@Test
public void capitalize_shouldCapitalizeFirstCharacterOfString() throws Exception {
String[] strings = {
"FRED",
"fRED",
"fred"
};
Arrays.stream(strings).forEach(el -> assertThat(String.format("%s should be Fred", el), capitalize(el), equalTo("Fred")));
}
@Test
public void lowerFirst_shouldLowercasedFirstCharacterOfString() throws Exception {
assertThat(lowerFirst("FRED"), is(equalTo("fRED")));
assertThat(lowerFirst("fred"), is(equalTo("fred")));
assertThat(lowerFirst("Fred"), is(equalTo("fred")));
}
@Test
public void isEnclosedBetween_shouldChekcWhetherStringIsEnclosed() throws Exception {
assertThat(isEnclosedBetween("{{shekhar}}", "{{", "}}"), is(true));
assertThat(isEnclosedBetween("shekhar", "{{", "}}"), is(false));
assertThat(isEnclosedBetween("*shekhar*", "*"), is(true));
assertThat(isEnclosedBetween("shekhar", "*"), is(false));
}
@Test(expected = IllegalArgumentException.class)
public void isEnclosedBetween_shouldThrowIllegalArgumentExceptionWhenEncloserIsNull() throws Exception {
assertThat(isEnclosedBetween("shekhar", null), is(false));
}
@Test
public void words_shouldConvertTextToWords() throws Exception {
final String line = "This is a string, with words!";
assertThat(words(line), is(new String[]{"This", "is", "a", "string", "with", "words"}));
}
@Test
public void upperFirst_shouldConvertFirstCharToUpperCase() throws Exception {
assertThat(upperFirst("fred"), is("Fred"));
}
@Test
public void upperFirst_shouldReturnSameStringIfFirstCharIsUpperCase() throws Exception {
assertThat(upperFirst("FRED"), is("FRED"));
}
@Test
public void trimStart_shouldRemoveAllWhitespaceAtStart() throws Exception {
assertThat(trimStart(" abc "), is(Optional.of("abc ")));
assertThat(trimStart("abc "), is(Optional.of("abc ")));
assertThat(trimStart("abc"), is(Optional.of("abc")));
assertThat(trimStart(""), is(Optional.empty()));
assertThat(trimStart(null), is(Optional.empty()));
}
@Test
public void trimStart_shouldRemoveSpecialCharactersAtStart() throws Exception {
assertThat(trimStart("-_-abc-_-", "_", "-"), is(Optional.of("abc-_-")));
assertThat(trimStart("-_-!abc-_-", "_", "-", "!"), is(Optional.of("abc-_-")));
assertThat(trimStart("-_-#abc-_-", "_", "-", "!", "#"), is(Optional.of("abc-_-")));
}
@Test
public void trimEnd_shouldRemoveAllTrailingWhitespace() throws Exception {
assertThat(trimEnd(" abc "), is(Optional.of(" abc")));
assertThat(trimEnd("abc "), is(Optional.of("abc")));
assertThat(trimEnd("abc"), is(Optional.of("abc")));
assertThat(trimEnd(""), is(Optional.empty()));
assertThat(trimEnd(null), is(Optional.empty()));
}
@Test
public void trimEnd_shouldRemoveAllTrailingSpecialCharacters() throws Exception {
assertThat(trimEnd("-_-abc-_-", "_", "-"), is(Optional.of("-_-abc")));
assertThat(trimEnd("-_-abc!-_-", "_", "-", "!"), is(Optional.of("-_-abc")));
assertThat(trimEnd("-_-abc#-_-", "_", "-", "!", "#"), is(Optional.of("-_-abc")));
}
} | Close #1 | src/test/java/strman/StrmanTest.java | Close #1 | <ide><path>rc/test/java/strman/StrmanTest.java
<ide> import static strman.Strman.format;
<ide>
<ide> public class StrmanTest {
<add>
<add> @Test
<add> public void replaceBetween_shouldReplaceSubstringsBetweenGivenIndexes() throws Exception {
<add> assertThat(replaceBetween("elif","W",0,2), equalTo("Wif"));
<add> assertThat(replaceBetween("elif","elif",0,4), equalTo("elif"));
<add> assertThat(replaceBetween("elif","",0,2), equalTo("if"));
<add> }
<add>
<add> @Test(expected = IllegalArgumentException.class)
<add> public void replaceBetween_shouldThrowIllegalArgumentExceptionWhenValueIsNull() throws Exception {
<add> replaceBetween(null,null,0,4);
<add> replaceBetween(null,"wer",0,4);
<add> replaceBetween("werw",null,0,4);
<add> replaceBetween("el","A",0,4);
<add> }
<ide>
<ide> @Test
<ide> public void append_shouldAppendStringsToEndOfValue() throws Exception { |
|
Java | lgpl-2.1 | ae48d62cbb4ad4e41b8d1af322344e33e8879212 | 0 | juanmjacobs/kettle,cwarden/kettle,cwarden/kettle,juanmjacobs/kettle,juanmjacobs/kettle,cwarden/kettle | /*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
/**********************************************************************
** **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package org.pentaho.di.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.DBCacheEntry;
import org.pentaho.di.core.ProgressMonitorListener;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.map.DatabaseConnectionMap;
import org.pentaho.di.core.database.util.DatabaseUtil;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleDatabaseBatchException;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database implements VariableSpace
{
public static final String LOG_STATUS_START = "start"; //$NON-NLS-1$
public static final String LOG_STATUS_END = "end"; //$NON-NLS-1$
public static final String LOG_STATUS_STOP = "stop"; //$NON-NLS-1$
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
// private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private RowMetaInterface rowMeta;
private int written;
private LogWriter log;
/**
* Number of times a connection was opened using this object.
* Only used in the context of a database connection map
*/
private int opened;
/**
* The copy is equal to opened at the time of creation.
*/
private int copy;
private String connectionGroup;
private String partitionId;
private VariableSpace variables = new Variables();
/**
* Construct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
shareVariablesWith(inf);
pstmt = null;
rowMeta = null;
dbmd = null;
rowlimit=0;
written=0;
if(log.isDetailed()) log.logDetailed(toString(), "New database connection defined");
}
public boolean equals(Object obj)
{
Database other = (Database) obj;
return other.databaseMeta.equals(other.databaseMeta);
}
/**
* Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle.
* @param connection
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect() throws KettleDatabaseException
{
connect(null);
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect(String partitionId) throws KettleDatabaseException
{
connect(null, partitionId);
}
public synchronized void connect(String group, String partitionId) throws KettleDatabaseException
{
// Before anything else, let's see if we already have a connection defined for this group/partition!
// The group is called after the thread-name of the transformation or job that is running
// The name of that threadname is expected to be unique (it is in Kettle)
// So the deal is that if there is another thread using that, we go for it.
//
if (!Const.isEmpty(group))
{
this.connectionGroup = group;
this.partitionId = partitionId;
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
// Try to find the conection for the group
Database lookup = map.getDatabase(group, partitionId, this);
if (lookup==null) // We already opened this connection for the partition & database in this group
{
// Do a normal connect and then store this database object for later re-use.
normalConnect(partitionId);
opened++;
copy = opened;
map.storeDatabase(group, partitionId, this);
}
else
{
connection = lookup.getConnection();
lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection.
copy = lookup.getOpened();
}
}
else
{
// Proceed with a normal connect
normalConnect(partitionId);
}
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void normalConnect(String partitionId) throws KettleDatabaseException
{
if (databaseMeta==null)
{
throw new KettleDatabaseException("No valid database connection defined!");
}
try
{
// First see if we use connection pooling...
//
if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility
databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own.
)
{
try
{
this.connection = ConnectionPoolUtil.getConnection(databaseMeta, partitionId);
}
catch (Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
else
{
connectUsingClass(databaseMeta.getDriverClass(), partitionId );
if(log.isDetailed()) log.logDetailed(toString(), "Connected to database.");
// See if we need to execute extra SQL statemtent...
String sql = environmentSubstitute( databaseMeta.getConnectSQL() );
// only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc.
if (!Const.isEmpty(sql) && !Const.onlySpaces(sql))
{
execStatements(sql);
if(log.isDetailed()) log.logDetailed(toString(), "Executed connect time SQL statements:"+Const.CR+sql);
}
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
private void initWithJNDI(String jndiName) throws KettleDatabaseException {
connection = null;
try {
DataSource dataSource = DatabaseUtil.getDataSourceFromJndi(jndiName);
if (dataSource != null) {
connection = dataSource.getConnection();
if (connection == null) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} else {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} catch (Exception e) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName + " : " + e.getMessage()); //$NON-NLS-1$
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException
{
// Install and load the jdbc Driver
// first see if this is a JNDI connection
if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) {
initWithJNDI( environmentSubstitute(databaseMeta.getDatabaseName()) );
return;
}
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
String url;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
url = environmentSubstitute(databaseMeta.getURL(partitionId));
}
else
{
url = environmentSubstitute(databaseMeta.getURL());
}
String clusterUsername=null;
String clusterPassword=null;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId);
if (partition!=null)
{
clusterUsername = partition.getUsername();
clusterPassword = Encr.decryptPasswordOptionallyEncrypted(partition.getPassword());
}
}
String username;
String password;
if (!Const.isEmpty(clusterUsername))
{
username = clusterUsername;
password = clusterPassword;
}
else
{
username = environmentSubstitute(databaseMeta.getUsername());
password = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(databaseMeta.getPassword()));
}
if (databaseMeta.supportsOptionsInURL())
{
if (!Const.isEmpty(username) || !Const.isEmpty(password))
{
// also allow for empty username with given password, in this case username must be given with one space
connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, ""));
}
else
{
// Perhaps the username is in the URL or no username is required...
connection = DriverManager.getConnection(url);
}
}
else
{
Properties properties = databaseMeta.getConnectionProperties();
if (!Const.isEmpty(username)) properties.put("user", username);
if (!Const.isEmpty(password)) properties.put("password", password);
connection = DriverManager.getConnection(url, properties);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public synchronized void disconnect()
{
try
{
if (connection==null)
{
return ; // Nothing to do...
}
if (connection.isClosed())
{
return ; // Nothing to do...
}
if (pstmt !=null)
{
pstmt.close();
pstmt=null;
}
if (prepStatementLookup!=null)
{
prepStatementLookup.close();
prepStatementLookup=null;
}
if (prepStatementInsert!=null)
{
prepStatementInsert.close();
prepStatementInsert=null;
}
if (prepStatementUpdate!=null)
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
if (pstmt_seq!=null)
{
pstmt_seq.close();
pstmt_seq=null;
}
// See if there are other steps using this connection in a connection group.
// If so, we will hold commit & connection close until then.
//
if (!Const.isEmpty(connectionGroup))
{
return;
}
else
{
if (!isAutoCommit()) // Do we really still need this commit??
{
commit();
}
}
closeConnectionOnly();
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
log.logError(toString(), Const.getStackTracker(ex));
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
log.logError(toString(), Const.getStackTracker(dbe));
}
}
/**
* Only for unique connections usage, typically you use disconnect() to disconnect() from the database.
* @throws KettleDatabaseException in case there is an error during connection close.
*/
public synchronized void closeConnectionOnly() throws KettleDatabaseException {
try
{
if (connection!=null)
{
connection.close();
if (!databaseMeta.isUsingConnectionPool())
{
connection=null;
}
}
if(log.isDetailed()) log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException e) {
throw new KettleDatabaseException("Error disconnecting from database '"+toString()+"'", e);
}
}
/**
* Cancel the open/running queries on the database connection
* @throws KettleDatabaseException
*/
public void cancelQuery() throws KettleDatabaseException
{
cancelStatement(pstmt);
cancelStatement(sel_stmt);
}
/**
* Cancel an open/running SQL statement
* @param statement the statement to cancel
* @throws KettleDatabaseException
*/
public void cancelStatement(Statement statement) throws KettleDatabaseException
{
try
{
if (statement!=null)
{
statement.cancel();
}
if(log.isDebug()) log.logDebug(toString(), "Statement canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling statement", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
if(log.isDetailed()) log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
public void setAutoCommit(boolean useAutoCommit) throws KettleDatabaseException {
try {
connection.setAutoCommit(useAutoCommit);
} catch (SQLException e) {
if (useAutoCommit) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToEnableAutoCommit", toString()));
} else {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToDisableAutoCommit", toString()));
}
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit() throws KettleDatabaseException
{
commit(false);
}
public void commit(boolean force) throws KettleDatabaseException
{
try
{
// Don't do the commit, wait until the end of the transformation.
// When the last database copy (opened counter) is about to be closed, we do a commit
// There is one catch, we need to catch the rollback
// The transformation will stop everything and then we'll do the rollback.
// The flag is in "performRollback", private only
//
if (!Const.isEmpty(connectionGroup) && !force)
{
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
if (log.isDebug()) log.logDebug(toString(), "Commit on database connection ["+toString()+"]");
connection.commit();
}
else
{
if(log.isDetailed()) log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback() throws KettleDatabaseException
{
rollback(false);
}
public void rollback(boolean force) throws KettleDatabaseException
{
try
{
if (!Const.isEmpty(connectionGroup) && !force)
{
return; // Will be handled by Trans --> endProcessing()
}
if (getDatabaseMetaData().supportsTransactions())
{
if (connection!=null) {
if (log.isDebug()) log.logDebug(toString(), "Rollback on database connection ["+toString()+"]");
connection.rollback();
}
}
else
{
if(log.isDetailed()) log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The row metadata to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException
{
prepareInsert(rowMeta, null, tableName);
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The metadata row to determine which values need to be inserted
* @param schemaName The name of the schema in which we want to insert rows
* @param tableName The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException
{
if (rowMeta.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(schemaName, tableName, rowMeta);
if(log.isDetailed()) log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database. (does not return generated keys)
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
return prepareSQL(sql, false);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @param returnKeys set to true if you want to return generated keys from an insert statement
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException
{
try
{
if (returnKeys)
{
return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
pstmt=null;
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, pstmt);
}
public void setValues(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData());
}
public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementInsert);
}
public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), prepStatementInsert);
}
public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementUpdate);
}
public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementLookup);
}
public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException
{
int pos;
if (result) pos=2; else pos=1;
for (int i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT"))
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]);
Object value = data[argnrs[i]];
setValue(cstmt, valueMeta, value, pos);
pos++;
} else {
pos++; //next parameter when OUT
}
}
}
public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case ValueMetaInterface.TYPE_NUMBER :
if (!v.isNull(object))
{
debug="Number, not null, getting number from value";
double num = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
debug="Number, rounding to precision ["+v.getPrecision()+"]";
num = Const.round(num, v.getPrecision());
}
debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement";
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case ValueMetaInterface.TYPE_INTEGER:
debug="Integer";
if (!v.isNull(object))
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, v.getInteger(object).longValue() );
}
else
{
double d = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, d );
}
else
{
ps.setDouble(pos, Const.round( d, v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.INTEGER);
}
break;
case ValueMetaInterface.TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (!v.isNull(object))
{
ps.setString(pos, v.getString(object));
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (!v.isNull(object))
{
String string = v.getString(object);
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = string.length();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = string.substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
debug="Date";
if (!v.isNull(object))
{
long dat = v.getInteger(object).longValue(); // converts using Date.getTime()
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case ValueMetaInterface.TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (!v.isNull(object))
{
ps.setBoolean(pos, v.getBoolean(object).booleanValue());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (!v.isNull(object))
{
ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
debug="BigNumber";
if (!v.isNull(object))
{
ps.setBigDecimal(pos, v.getBigNumber(object));
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case ValueMetaInterface.TYPE_BINARY:
debug="Binary";
if (!v.isNull(object))
{
ps.setBytes(pos, v.getBinary(object));
}
else
{
ps.setNull(pos, java.sql.Types.BINARY);
}
break;
default:
debug="default";
// placeholder
ps.setNull(pos, java.sql.Types.VARCHAR);
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), ps);
}
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException
{
// now set the values in the row!
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
/**
* Sets the values of the preparedStatement pstmt.
* @param rowMeta
* @param data
*/
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException
{
// now set the values in the row!
int index=0;
for (int i=0;i<rowMeta.size();i++)
{
if (i!=ignoreThisValueIndex)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, index+1);
index++;
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
}
/**
* @param ps The prepared insert statement to use
* @return The generated keys in auto-increment fields
* @throws KettleDatabaseException in case something goes wrong retrieving the keys.
*/
public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException
{
ResultSet keys = null;
try
{
keys=ps.getGeneratedKeys(); // 1 row of keys
ResultSetMetaData resultSetMetaData = keys.getMetaData();
RowMetaInterface rowMeta = getRowInfo(resultSetMetaData, false, false);
return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta));
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex);
}
finally
{
if (keys!=null)
{
try
{
keys.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e);
}
}
}
}
public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException
{
return getNextSequenceValue(null, sequenceName, keyfield);
}
public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException
{
Long retval=null;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence)));
}
ResultSet rs=null;
try
{
rs = pstmt_seq.executeQuery();
if (rs.next())
{
retval = Long.valueOf( rs.getLong(1) );
}
}
finally
{
if ( rs != null ) rs.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex);
}
return retval;
}
public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields, data);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, RowMetaInterface fields)
{
return getInsertStatement(null, tableName, fields);
}
public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields)
{
StringBuffer ins=new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append(" (");
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
ins.append(" ?");
}
ins.append(')');
return ins.toString();
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
return insertRow(ps, false, true);
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @param handleCommit True if you want to handle the commit here after the commit size (False e.g. in case the step handles this, see TableOutput)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch, boolean handleCommit) throws KettleDatabaseException
{
String debug="insertRow start";
boolean rowsAreSafe=false;
try
{
// Unique connections and Batch inserts don't mix when you want to roll back on certain databases.
// That's why we disable the batch insert in that case.
//
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup);
//
// Add support for batch inserts...
//
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
ps.addBatch(); // Add the batch, but don't forget to run the batch
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (handleCommit) { // some steps handle the commit themselves (see e.g. TableOutput step)
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
}
else
{
debug="insertRow normal commit";
commit();
}
rowsAreSafe=true;
}
}
return rowsAreSafe;
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
// 'seed' the loop with the root exception
SQLException nextException = ex;
do
{
exceptions.add(nextException);
// while current exception has next exception, add to list
}
while ((nextException = nextException.getNextException())!=null);
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
// log.logError(toString(), Const.getStackTracker(ex));
throw new KettleDatabaseException("Error inserting/updating row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting/updating row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
/**
* Close the prepared statement of the insert statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*/
public void emptyAndCommit(PreparedStatement ps, boolean batch, int batchCounter) throws KettleDatabaseException {
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Execute the batch or just perform a commit.
//
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0)
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
//
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
//
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to empty ps and commit connection.", ex);
}
}
/**
* Close the prepared statement of the insert statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing (typically true for this method)
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*
* @deprecated use emptyAndCommit() instead (pass in the number of rows left in the batch)
*/
public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Execute the batch or just perform a commit.
//
if (batch && getDatabaseMetaData().supportsBatchUpdates())
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
//
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
//
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql) throws KettleDatabaseException
{
return execStatement(sql, null, null);
}
public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, data, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
String sqlStripped = databaseMeta.stripCR(sql);
// log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]");
Statement stmt = connection.createStatement();
resultSet = stmt.execute(sqlStripped);
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count);
}
}
// See if a cache needs to be cleared...
if (sql.toUpperCase().startsWith("ALTER TABLE") ||
sql.toUpperCase().startsWith("DROP TABLE") ||
sql.toUpperCase().startsWith("CREATE TABLE")
)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script) throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat;
if (to<=length) stat = all.substring(from, to);
else stat = all.substring(from);
// If it ends with a ; remove that ;
// Oracle for example can't stand it when this happens...
if (stat.length()>0 && stat.charAt(stat.length()-1)==';')
{
stat = stat.substring(0,stat.length()-1);
}
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
if(log.isDetailed()) log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = null;
try
{
rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs);
while (row!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
if (log.isDetailed()) log.logDetailed(toString(), rowMeta.getString(row));
row = getRow(rs);
}
}
else
{
if (log.isDebug()) log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
} catch (KettleValueException e) {
throw new KettleDatabaseException(e); // just pass the error upwards.
}
finally
{
try
{
if ( rs != null ) rs.close();
}
catch (SQLException ex )
{
if (log.isDebug()) log.logDebug(toString(), "Error closing query: "+Const.CR+sql);
}
}
}
else // any kind of statement
{
if(log.isDetailed()) log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
if(log.isDetailed()) log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql) throws KettleDatabaseException
{
return openQuery(sql, null, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @data the parameter data to open the query with
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
return openQuery(sql, params, data, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException
{
return openQuery(sql, params, data, fetch_mode, false);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params, data); // set the dates etc!
if (canWeSetFetchSize(pstmt) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
pstmt.setFetchSize(Integer.MIN_VALUE);
}
else
pstmt.setFetchSize(fs);
}
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (canWeSetFetchSize(sel_stmt))
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(fs);
}
debug = "Set fetch direction";
sel_stmt.setFetchDirection(fetch_mode);
}
debug = "Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get rowinfo";
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
//
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, lazyConversion);
}
catch(SQLException ex)
{
// log.logError(toString(), "ERROR executing ["+sql+"]");
// log.logError(toString(), "ERROR in part: ["+debug+"]");
// printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
private boolean canWeSetFetchSize(Statement statement) throws SQLException
{
return databaseMeta.isFetchSizeSupported() &&
( statement.getMaxRows()>0 ||
databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES ||
( databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults() )
);
}
public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, data, ps); // set the parameters!
if (canWeSetFetchSize(ps))
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
ps.setFetchSize(Integer.MIN_VALUE);
}
else
{
ps.setFetchSize(fs);
}
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ getRowInfo()";
// rowinfo = getRowInfo(res.getMetaData());
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
//
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, false);
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException
{
return getQueryFields(sql, param, null, null);
}
/**
* See if the table specified exists by reading
* @param tablename The name of the table to check.<br>
* This is supposed to be the properly quoted name of the table or the complete schema-table name combination.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename) throws KettleDatabaseException
{
try
{
if(log.isDebug()) log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
// Just try to read from the table.
String sql = databaseMeta.getSQLTableExists(tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
/*
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
*/
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* See if the column specified exists by reading
* @param columnname The name of the column to check.
* @param tablename The name of the table to check.<br>
* This is supposed to be the properly quoted name of the table or the complete schema-table name combination.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkColumnExists(String columnname, String tablename) throws KettleDatabaseException
{
try
{
if(log.isDebug()) log.logDebug(toString(), "Checking if column [" + columnname + "] exists in table ["+tablename+"] !");
// Just try to read from the table.
String sql = databaseMeta.getSQLColumnExists(columnname,tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if column [" + columnname + "] exists in table ["+tablename+"] on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException
{
return checkSequenceExists(null, sequenceName);
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
//
// Get the info from the data dictionary...
//
String sql = databaseMeta.getSQLSequenceExists(schemaSequence);
ResultSet res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tableName The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException
{
return checkIndexExists(null, tableName, idx_fields);
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException
{
String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
if (!checkTableExists(tablename)) return false;
if(log.isDebug()) log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
//
// Get the info from the data dictionary...
//
StringBuffer sql = new StringBuffer(128);
sql.append("select i.name table_name, c.name column_name ");
sql.append("from sysindexes i, sysindexkeys k, syscolumns c ");
sql.append("where i.name = '"+tablename+"' ");
sql.append("AND i.id = k.id ");
sql.append("AND i.id = c.id ");
sql.append("AND k.colid = c.colid ");
ResultSet res = null;
try
{
res = openQuery(sql.toString());
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
//
// Get the info from the data dictionary...
//
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tableName+"'";
ResultSet res = null;
try {
res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
log.logError(toString(), Const.getStackTracker(e));
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon);
}
public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" ";
cr_index += "ON ";
// assume table has already been quoted (and possibly includes schema)
cr_index += tablename;
cr_index += Const.CR + "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace());
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String sequence, String start_at, String increment_by, String max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(schemaName, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequenceName, String start_at, String increment_by, String max_value, boolean semi_colon)
{
String cr_seq="";
if (Const.isEmpty(sequenceName)) return cr_seq;
if (databaseMeta.supportsSequences())
{
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value != null) {
//"-1" means there is no maxvalue, must be handles different by DB2 / AS400
if ((databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_DB2 ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_AS400 ) &&
max_value.trim().equals("-1")) {
cr_seq += "NOMAXVALUE"+Const.CR;
} else {
// set the max value
cr_seq += "MAXVALUE "+max_value+Const.CR;
}
}
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
//
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
// The new method of retrieving the query fields fails on Oracle because
// they failed to implement the getMetaData method on a prepared statement. (!!!)
// Even recent drivers like 10.2 fail because of it.
//
// There might be other databases that don't support it (we have no knowledge of this at the time of writing).
// If we discover other RDBMSs, we will create an interface for it.
// For now, we just try to get the field layout on the re-bound in the exception block below.
//
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_H2 ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GENERIC)
{
fields=getQueryFieldsFallback(sql, param, inform, data);
}
else
{
// On with the regular program.
//
PreparedStatement preparedStatement = null;
try
{
preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSetMetaData rsmd = preparedStatement.getMetaData();
fields = getRowInfo(rsmd, false, false);
}
catch(Exception e)
{
fields = getQueryFieldsFallback(sql, param, inform, data);
}
finally
{
if (preparedStatement!=null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e);
}
}
}
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
private RowMetaInterface getQueryFieldsFallback(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
try
{
if (inform==null
// Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214)
&& databaseMeta.getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_MSSQL
)
{
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(1);
}
}
if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1);
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
fields = getRowInfo(r.getMetaData(), false, false);
r.close();
sel_stmt.close();
sel_stmt=null;
}
else
{
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
RowMetaInterface par = inform;
if (par==null || par.isEmpty()) par = getParameterMetaData(ps);
if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data);
setValues(par, data, ps);
}
ResultSet r = ps.executeQuery();
fields=getRowInfo(ps.getMetaData(), false, false);
r.close();
ps.close();
}
}
catch(Exception ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex);
}
return fields;
}
public void closeQuery(ResultSet res) throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
/**
* Build the row using ResultSetMetaData rsmd
* @param rm The resultset metadata to inquire
* @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem)
* @param lazyConversion true if lazy conversion needs to be enabled where possible
*/
private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException
{
if (rm==null) return null;
rowMeta = new RowMeta();
try
{
// TODO If we do lazy conversion, we need to find out about the encoding
//
int fieldNr = 1;
int nrcols=rm.getColumnCount();
for (int i=1;i<=nrcols;i++)
{
String name=new String(rm.getColumnName(i));
// Check the name, sometimes it's empty.
//
if (Const.isEmpty(name) || Const.onlySpaces(name))
{
name = "Field"+fieldNr;
fieldNr++;
}
ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion);
rowMeta.addValueMeta(v);
}
return rowMeta;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException
{
int length=-1;
int precision=-1;
int valtype=ValueMetaInterface.TYPE_NONE;
boolean isClob = false;
int type = rm.getColumnType(index);
boolean signed = rm.isSigned(index);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=ValueMetaInterface.TYPE_STRING;
if (!ignoreLength) length=rm.getColumnDisplaySize(index);
break;
case java.sql.Types.CLOB:
valtype=ValueMetaInterface.TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
isClob=true;
break;
case java.sql.Types.BIGINT:
// verify Unsigned BIGINT overflow!
//
if (signed)
{
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
}
else
{
valtype=ValueMetaInterface.TYPE_BIGNUMBER;
precision=0; // Max 18.446.744.073.709.551.615
length=16;
}
break;
case java.sql.Types.INTEGER:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=ValueMetaInterface.TYPE_NUMBER;
length=rm.getPrecision(index);
precision=rm.getScale(index);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
{
if (precision==0)
{
precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
}
// If we're dealing with PostgreSQL and double precision types
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16)
{
precision=-1;
length=-1;
}
// MySQL: max resolution is double precision floating point (double)
// The (12,31) that is given back is not correct
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
if (precision >= length) {
precision=-1;
length=-1;
}
}
}
else
{
if (precision==0 && length<18 && length>0) // Among others Oracle is affected here.
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
}
if (length>18 || precision>18) valtype=ValueMetaInterface.TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision == 0 && length == 38 )
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
if (precision<=0 && length<=0) // undefined size: BIGNUMBER, precision on Oracle can be 38, too big for a Number type
{
valtype=ValueMetaInterface.TYPE_BIGNUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_TERADATA) {
precision = 1;
}
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=ValueMetaInterface.TYPE_DATE;
//
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL) {
String property = databaseMeta.getConnectionProperties().getProperty("yearIsDateType");
if (property != null && property.equalsIgnoreCase("false")
&& rm.getColumnTypeName(index).equalsIgnoreCase("YEAR")) {
valtype = ValueMetaInterface.TYPE_INTEGER;
precision = 0;
length = 4;
break;
}
}
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
valtype=ValueMetaInterface.TYPE_BOOLEAN;
break;
case java.sql.Types.BINARY:
case java.sql.Types.BLOB:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
valtype=ValueMetaInterface.TYPE_BINARY;
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 &&
(2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index))
{
// set the length for "CHAR(X) FOR BIT DATA"
length = rm.getPrecision(index);
}
else
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_ORACLE &&
( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY )
)
{
// set the length for Oracle "RAW" or "LONGRAW" data types
valtype = ValueMetaInterface.TYPE_STRING;
length = rm.getColumnDisplaySize(index);
}
else
{
length=-1;
}
precision=-1;
break;
default:
valtype=ValueMetaInterface.TYPE_STRING;
precision=rm.getScale(index);
break;
}
// Grab the comment as a description to the field as well.
String comments=rm.getColumnLabel(index);
// get & store more result set meta data for later use
int originalColumnType=rm.getColumnType(index);
String originalColumnTypeName=rm.getColumnTypeName(index);
int originalPrecision=-1;
if (!ignoreLength) rm.getPrecision(index); // Throws exception on MySQL
int originalScale=rm.getScale(index);
// boolean originalAutoIncrement=rm.isAutoIncrement(index); DISABLED FOR PERFORMANCE REASONS : PDI-1788
// int originalNullable=rm.isNullable(index); DISABLED FOR PERFORMANCE REASONS : PDI-1788
boolean originalSigned=rm.isSigned(index);
ValueMetaInterface v=new ValueMeta(name, valtype);
v.setLength(length);
v.setPrecision(precision);
v.setComments(comments);
v.setLargeTextField(isClob);
v.setOriginalColumnType(originalColumnType);
v.setOriginalColumnTypeName(originalColumnTypeName);
v.setOriginalPrecision(originalPrecision);
v.setOriginalScale(originalScale);
// v.setOriginalAutoIncrement(originalAutoIncrement); DISABLED FOR PERFORMANCE REASONS : PDI-1788
// v.setOriginalNullable(originalNullable); DISABLED FOR PERFORMANCE REASONS : PDI-1788
v.setOriginalSigned(originalSigned);
// See if we need to enable lazy conversion...
//
if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) {
v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// TODO set some encoding to go with this.
// Also set the storage metadata. a copy of the parent, set to String too.
//
ValueMetaInterface storageMetaData = v.clone();
storageMetaData.setType(ValueMetaInterface.TYPE_STRING);
storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
v.setStorageMetadata(storageMetaData);
}
return v;
}
public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs) throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset. Do not use lazy conversion
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs) throws KettleDatabaseException
{
return getRow(rs, false);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @param lazyConversion set to true if strings need to have lazy conversion enabled
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException
{
if (rowMeta==null)
{
ResultSetMetaData rsmd = null;
try
{
rsmd = rs.getMetaData();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e);
}
rowMeta = getRowInfo(rsmd, false, lazyConversion);
}
return getRow(rs, null, rowMeta);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException
{
try
{
int nrcols=rowInfo.size();
Object[] data = RowDataUtil.allocateRowData(nrcols);
if (rs.next())
{
for (int i=0;i<nrcols;i++)
{
ValueMetaInterface val = rowInfo.getValueMeta(i);
switch(val.getType())
{
case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break;
case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break;
case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break;
case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break;
case ValueMetaInterface.TYPE_STRING :
{
if (val.isStorageBinaryString()) {
data[i] = rs.getBytes(i+1);
}
else {
data[i] = rs.getString(i+1);
}
}
break;
case ValueMetaInterface.TYPE_BINARY :
{
if (databaseMeta.supportsGetBlob())
{
Blob blob = rs.getBlob(i+1);
if (blob!=null)
{
data[i] = blob.getBytes(1L, (int)blob.length());
}
else
{
data[i] = null;
}
}
else
{
data[i] = rs.getBytes(i+1);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW && val.getOriginalColumnType()==java.sql.Types.TIME)
{
// Neoview can not handle getDate / getTimestamp for a Time column
data[i] = rs.getTime(i+1); break; // Time is a subclass of java.util.Date, the default date will be 1970-01-01
}
else if (val.getPrecision()!=1 && databaseMeta.supportsTimeStampToDateConversion())
{
data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date
}
else
{
data[i] = rs.getDate(i+1); break;
}
default: break;
}
if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too.
}
}
else
{
data=null;
}
return data;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String schema, String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(schema, table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults);
}
// Lookup certain fields in a table
public void setLookup(String schemaName, String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String sql = "SELECT ";
for (int i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(gets[i]);
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+databaseMeta.quoteField(rename[i]);
}
}
sql += " FROM "+table+" WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(codes[i]);
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
if(log.isDetailed()) log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows())
{
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
return prepareUpdate(null, table, codes, condition, sets);
}
// Lookup certain fields in a table
public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[])
{
StringBuffer sql = new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET ");
for (int i=0;i<sets.length;i++)
{
if (i!=0) sql.append(", ");
sql.append(databaseMeta.quoteField(sets[i]));
sql.append(" = ?").append(Const.CR);
}
sql.append("WHERE ");
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql.append("AND ");
sql.append(databaseMeta.quoteField(codes[i]));
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql.append(" BETWEEN ? AND ? ");
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql.append(' ').append(condition[i]).append(' ');
}
else
{
sql.append(' ').append(condition[i]).append(" ? ");
}
}
try
{
String s = sql.toString();
if(log.isDetailed()) log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param table The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String table, String codes[], String condition[])
{
return prepareDelete(null, table, codes, condition);
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param schemaName the schema-name to delete in
* @param tableName The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[])
{
String sql;
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql = "DELETE FROM "+table+Const.CR;
sql+= "WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
if(log.isDetailed()) log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (int i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
if(log.isDetailed()) log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (!Const.isEmpty(returnvalue))
{
switch(returntype)
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
public Object[] getLookup() throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException
{
return getLookup(prepStatementLookup, failOnMultipleResults);
}
public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException
{
return getLookup(ps, false);
}
public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException
{
ResultSet res = null;
try
{
res = ps.executeQuery();
rowMeta = getRowInfo(res.getMetaData(), false, false);
Object[] ret = getRow(res);
if (failOnMultipleResults)
{
if (ret != null && res.next())
{
// if the previous row was null, there's no reason to try res.next() again.
// on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver).
throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!");
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database", ex);
}
finally
{
try
{
if (res!=null) res.close(); // close resultset!
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset after looking up data", e);
}
}
}
public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null;
if (checkTableExists(tableName))
{
retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
return retval;
}
/**
* Generates SQL
* @param tableName the table name or schema/table combination: this needs to be quoted properly in advance.
* @param fields the fields
* @param tk the name of the technical key field
* @param use_autoinc true if we need to use auto-increment fields for a primary key
* @param pk the name of the primary/technical key field
* @param semicolon append semicolon to the statement
* @return the SQL needed to create the specified table and fields.
*/
public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tableName+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
ValueMetaInterface v=fields.getValueMeta(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (pk==null && tk==null && databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW)
{
retval+="NO PARTITION"; // use this as a default when no pk/tk is there, otherwise you get an error
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
RowMetaInterface tabFields = getTableFields(tableName);
// Don't forget to quote these as well...
databaseMeta.quoteReservedWords(tabFields);
// Find the missing fields
RowMetaInterface missing = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
// Not found?
if (tabFields.searchValueMeta( v.getName() )==null )
{
missing.addValueMeta(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
ValueMetaInterface v=missing.getValueMeta(i);
retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
RowMetaInterface surplus = new RowMeta();
for (int i=0;i<tabFields.size();i++)
{
ValueMetaInterface v = tabFields.getValueMeta(i);
// Found in table, not in input ?
if (fields.searchValueMeta( v.getName() )==null )
{
surplus.addValueMeta(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
ValueMetaInterface v=surplus.getValueMeta(i);
retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
//
// OK, see if there are fields for wich we need to modify the type... (length, precision)
//
RowMetaInterface modify = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface desiredField = fields.getValueMeta(i);
ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
// TODO: this is not an optimal way of finding out changes.
// Perhaps we should just generate the data types strings for existing and new data type and see if anything changed.
//
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValueMeta(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
ValueMetaInterface v=modify.getValueMeta(i);
retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(null, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.quoteField(tablename));
}
}
public void truncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return new RowMetaAndData(rowMeta, row);
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException {
RowMeta meta = new RowMeta();
for( int i=0; i<md.getColumnCount(); i++ ) {
String name = md.getColumnName(i+1);
ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false );
meta.addValueMeta( valueMeta );
}
return meta;
}
public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param, data);
if (rs!=null)
{
Object[] row = getRow(rs); // One value: a number;
rowMeta=null;
RowMeta tmpMeta = null;
try {
ResultSetMetaData md = rs.getMetaData();
tmpMeta = getMetaFromRow( row, md );
} catch (Exception e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
}
return new RowMetaAndData(tmpMeta, row);
}
else
{
return null;
}
}
public RowMetaInterface getParameterMetaData(PreparedStatement ps)
{
RowMetaInterface par = new RowMeta();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<=pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
ValueMeta val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN);
break;
default:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER);
}
par.addValueMeta(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data)
{
// The database couldn't handle it: try manually!
int q=countParameters(sql);
RowMetaInterface par=new RowMeta();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
ValueMetaInterface inf=inform.getValueMeta(i);
ValueMetaInterface v = inf.clone();
par.addValueMeta(v);
}
}
else
{
for (int i=0;i<q;i++)
{
ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER);
par.addValueMeta(v);
}
}
return par;
}
public static final RowMetaInterface getTransLogrecordFields(boolean update, boolean use_batchid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_batchid && !update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING, 255, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING , 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_batchid && update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public static final RowMetaInterface getJobLogrecordFields(boolean update, boolean use_jobid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_jobid && !update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING,255, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING, 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_jobid && update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public void writeLogRecord(String logtable, boolean use_id, long id, boolean job, String name, String status, long read, long written, long updated, long input, long output, long errors, java.util.Date startdate, java.util.Date enddate, java.util.Date logdate, java.util.Date depdate, java.util.Date replayDate, String log_string) throws KettleDatabaseException {
boolean update = use_id && log_string != null && !status.equalsIgnoreCase(LOG_STATUS_START);
RowMetaInterface rowMeta;
if (job) {
rowMeta = getJobLogrecordFields(update, use_id, !Const.isEmpty(log_string));
} else {
rowMeta = getTransLogrecordFields(update, use_id, !Const.isEmpty(log_string));
}
if (update) {
String sql = "UPDATE " + logtable + " SET ";
for (int i = 0; i < rowMeta.size() - 1; i++) // Without ID_JOB or ID_BATCH
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
if (i > 0) {
sql += ", ";
}
sql += databaseMeta.quoteField(valueMeta.getName()) + "=? ";
}
sql += "WHERE ";
if (job) {
sql += databaseMeta.quoteField("ID_JOB") + "=? ";
} else {
sql += databaseMeta.quoteField("ID_BATCH") + "=? ";
}
Object[] data = new Object[] {
status,
Long.valueOf(read), Long.valueOf(written),
Long.valueOf(input), Long.valueOf(output),
Long.valueOf(updated), Long.valueOf(errors),
startdate, enddate, logdate, depdate, replayDate,
log_string,
Long.valueOf(id),
};
execStatement(sql, rowMeta, data);
} else {
String sql = "INSERT INTO " + logtable + " ( ";
for (int i = 0; i < rowMeta.size(); i++) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
if (i > 0)
sql += ", ";
sql += databaseMeta.quoteField(valueMeta.getName());
}
sql += ") VALUES(";
for (int i = 0; i < rowMeta.size(); i++) {
if (i > 0)
sql += ", ";
sql += "?";
}
sql += ")";
try {
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
List<Object> data = new ArrayList<Object>();
if (job) {
if (use_id) {
data.add(Long.valueOf(id));
}
data.add(name);
} else {
if (use_id) {
data.add(Long.valueOf(id));
}
data.add(name);
}
data.add(status);
data.add(Long.valueOf(read));
data.add(Long.valueOf(written));
data.add(Long.valueOf(updated));
data.add(Long.valueOf(input));
data.add(Long.valueOf(output));
data.add(Long.valueOf(errors));
data.add(startdate);
data.add(enddate);
data.add(logdate);
data.add(depdate);
data.add(replayDate);
if (!Const.isEmpty(log_string)) {
data.add(log_string);
}
setValues(rowMeta, data.toArray(new Object[data.size()]));
pstmt.executeUpdate();
pstmt.close();
pstmt = null;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to write log record to log table " + logtable, ex);
}
}
}
public static final RowMetaInterface getStepPerformanceLogrecordFields()
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
v=new ValueMeta("SEQ_NR", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING ,255, 0); r.addValueMeta(v);
v=new ValueMeta("STEPNAME", ValueMetaInterface.TYPE_STRING ,255, 0); r.addValueMeta(v);
v=new ValueMeta("STEP_COPY", ValueMetaInterface.TYPE_INTEGER, 3, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_REJECTED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("INPUT_BUFFER_ROWS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("OUTPUT_BUFFER_ROWS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
return r;
}
public Object[] getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException
{
Object[] row = null;
String jobtrans = job?databaseMeta.quoteField("JOBNAME"):databaseMeta.quoteField("TRANSNAME");
String sql = "";
sql+=" SELECT "+databaseMeta.quoteField("ENDDATE")+", "+databaseMeta.quoteField("DEPDATE")+", "+databaseMeta.quoteField("STARTDATE");
sql+=" FROM "+logtable;
sql+=" WHERE "+databaseMeta.quoteField("ERRORS")+" = 0";
sql+=" AND "+databaseMeta.quoteField("STATUS")+" = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY "+databaseMeta.quoteField("LOGDATE")+" DESC, "+databaseMeta.quoteField("ENDDATE")+" DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface r = new RowMeta();
r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
setValues(r, new Object[] { name });
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rowMeta = getRowInfo(res.getMetaData(), false, false);
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException
{
return getNextValue(counters, null, tableName, val_key);
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException
{
Long nextValue = null;
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String lookup = schemaTable+"."+databaseMeta.quoteField(val_key);
// Try to find the previous sequence value...
Counter counter = null;
if (counters!=null) counter=counters.get(lookup);
if (counter==null)
{
RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable);
if (rmad!=null)
{
long previous;
try
{
Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0);
// A "select max(x)" on a table with no matching rows will return null.
if ( tmp != null )
previous = tmp.longValue();
else
previous = 0L;
}
catch (KettleValueException e)
{
throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable);
}
counter = new Counter(previous+1, 1);
nextValue = Long.valueOf( counter.next() );
if (counters!=null) counters.put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable);
}
}
else
{
nextValue = Long.valueOf( counter.next() );
}
return nextValue;
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
return getRows(rset, limit, monitor);
}
/** Reads the result of a ResultSet into an ArrayList
*
* @param rset the ResultSet to read out
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(ResultSet rset, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
try
{
List<Object[]> result = new ArrayList<Object[]>();
boolean stop=false;
int i=0;
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Object[] row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e);
}
}
public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
/**
* Get the first rows from a table (for preview)
* @param table_name The table name (or schema/table combination): this needs to be quoted properly
* @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException in case something goes wrong
*/
public List<Object[]> getFirstRows(String table_name, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
String sql = "SELECT";
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW)
{
sql+=" [FIRST " + limit +"]";
}
sql += " * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public RowMetaInterface getReturnRowMeta()
{
return rowMeta;
}
public String[] getTableTypes() throws KettleDatabaseException
{
try
{
ArrayList<String> types = new ArrayList<String>();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames() throws KettleDatabaseException
{
return getTablenames(false);
}
public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
List<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getViews() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getViews(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getSynonyms() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
List<Object[]> procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Object[])procs.get(i))[0].toString();
}
return str;
}
else
{
ResultSet rs = null;
try
{
DatabaseMetaData dbmd = getDatabaseMetaData();
rs = dbmd.getProcedures(null, null, null);
List<Object[]> rows = getRows(rs, 0, null);
String result[] = new String[rows.size()];
for (int i=0;i<rows.size();i++)
{
Object[] row = (Object[])rows.get(i);
String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null);
String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null);
String procName = rowMeta.getString(row, "PROCEDURE_NAME", "");
String name = "";
if (procCatalog!=null) name+=procCatalog+".";
else if (procSchema!=null) name+=procSchema+".";
name+=procName;
result[i] = name;
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e);
}
finally
{
if (rs!=null) try { rs.close(); } catch(Exception e) {}
}
}
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
//
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to lock the (quoted) tables
//
String sql = databaseMeta.getSQLLockTables(quotedTableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
//
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to unlock the (quoted) tables
//
String sql = databaseMeta.getSQLUnlockTables(quotedTableNames);
if (sql!=null)
{
execStatement(sql);
}
}
/**
* @return the opened
*/
public int getOpened()
{
return opened;
}
/**
* @param opened the opened to set
*/
public void setOpened(int opened)
{
this.opened = opened;
}
/**
* @return the connectionGroup
*/
public String getConnectionGroup()
{
return connectionGroup;
}
/**
* @param connectionGroup the connectionGroup to set
*/
public void setConnectionGroup(String connectionGroup)
{
this.connectionGroup = connectionGroup;
}
/**
* @return the partitionId
*/
public String getPartitionId()
{
return partitionId;
}
/**
* @param partitionId the partitionId to set
*/
public void setPartitionId(String partitionId)
{
this.partitionId = partitionId;
}
/**
* @return the copy
*/
public int getCopy()
{
return copy;
}
/**
* @param copy the copy to set
*/
public void setCopy(int copy)
{
this.copy = copy;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
// Also share the variables with the meta data object
// Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case.
//
if (space!=databaseMeta) databaseMeta.shareVariablesWith(space);
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype) throws KettleDatabaseException {
RowMetaAndData ret;
try {
cstmt.execute();
ret = new RowMetaAndData();
int pos = 1;
if (resultname != null && resultname.length() != 0) {
ValueMeta vMeta = new ValueMeta(resultname, resulttype);
Object v =null;
switch (resulttype) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getDate(pos);
break;
}
ret.addValue(vMeta, v);
pos++;
}
for (int i = 0; i < arg.length; i++) {
if (argdir[i].equalsIgnoreCase("OUT")
|| argdir[i].equalsIgnoreCase("INOUT")) {
ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]);
Object v=null;
switch (argtype[i]) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos + i));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos + i));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos + i);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos + i));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos + i);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getTimestamp(pos + i);
break;
}
ret.addValue(vMeta, v);
}
}
return ret;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
/**
* Return SQL CREATION statement for a Table
* @param tableName The table to create
* @throws KettleDatabaseException
*/
public String getDDLCreationTable(String tableName, RowMetaInterface fields) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk=databaseMeta.quoteField(null);
retval=getCreateTableStatement(tableName, fields, quotedTk, false, null, true);
return retval;
}
/**
* Return SQL TRUNCATE statement for a Table
* @param schema The schema
* @param tableNameWithSchema The table to create
* @throws KettleDatabaseException
*/
public String getDDLTruncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
return(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
return("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Return SQL statement (INSERT INTO TableName ...
* @param schemaName tableName The schema
* @param tableName
* @param fields
* @param dateFormat date format of field
* @throws KettleDatabaseException
*/
public String getSQLOutput(String schemaName, String tableName, RowMetaInterface fields, Object[] r,String dateFormat) throws KettleDatabaseException
{
StringBuffer ins=new StringBuffer(128);
try{
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append('(');
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// new add values ...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(",");
{
if (fields.getValueMeta(i).getType()==ValueMeta.TYPE_STRING)
ins.append("'" + fields.getString(r,i) + "'") ;
else if (fields.getValueMeta(i).getType()==ValueMeta.TYPE_DATE)
{
if (Const.isEmpty(dateFormat))
ins.append("'" + fields.getString(r,i)+ "'") ;
else
{
try
{
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(dateFormat);
ins.append("'" + formatter.format(fields.getDate(r,i))+ "'") ;
}
catch(Exception e)
{
throw new KettleDatabaseException("Error : ", e);
}
}
}
else
{
ins.append( fields.getString(r,i)) ;
}
}
}
ins.append(')');
}catch (Exception e)
{
throw new KettleDatabaseException(e);
}
return ins.toString();
}
public Savepoint setSavepoint() throws KettleDatabaseException {
try {
return connection.setSavepoint();
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToSetSavepoint"), e);
}
}
public Savepoint setSavepoint(String savePointName) throws KettleDatabaseException {
try {
return connection.setSavepoint(savePointName);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToSetSavepointName", savePointName), e);
}
}
public void releaseSavepoint(Savepoint savepoint) throws KettleDatabaseException {
try {
connection.releaseSavepoint(savepoint);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToReleaseSavepoint"), e);
}
}
public void rollback(Savepoint savepoint) throws KettleDatabaseException {
try {
connection.rollback(savepoint);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToRollbackToSavepoint"), e);
}
}
}
| src-core/org/pentaho/di/core/database/Database.java | /*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
/**********************************************************************
** **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package org.pentaho.di.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Counter;
import org.pentaho.di.core.DBCache;
import org.pentaho.di.core.DBCacheEntry;
import org.pentaho.di.core.ProgressMonitorListener;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.map.DatabaseConnectionMap;
import org.pentaho.di.core.database.util.DatabaseUtil;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.exception.KettleDatabaseBatchException;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.variables.Variables;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database implements VariableSpace
{
public static final String LOG_STATUS_START = "start"; //$NON-NLS-1$
public static final String LOG_STATUS_END = "end"; //$NON-NLS-1$
public static final String LOG_STATUS_STOP = "stop"; //$NON-NLS-1$
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
// private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private RowMetaInterface rowMeta;
private int written;
private LogWriter log;
/*
* Counts the number of rows written to a batch for a certain PreparedStatement.
*
private Map<PreparedStatement, Integer> batchCounterMap;
*/
/**
* Number of times a connection was opened using this object.
* Only used in the context of a database connection map
*/
private int opened;
/**
* The copy is equal to opened at the time of creation.
*/
private int copy;
private String connectionGroup;
private String partitionId;
private VariableSpace variables = new Variables();
/**
* Construct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
shareVariablesWith(inf);
pstmt = null;
rowMeta = null;
dbmd = null;
rowlimit=0;
written=0;
if(log.isDetailed()) log.logDetailed(toString(), "New database connection defined");
}
public boolean equals(Object obj)
{
Database other = (Database) obj;
return other.databaseMeta.equals(other.databaseMeta);
}
/**
* Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle.
* @param connection
*/
public void setConnection(Connection connection) {
this.connection = connection;
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect() throws KettleDatabaseException
{
connect(null);
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect(String partitionId) throws KettleDatabaseException
{
connect(null, partitionId);
}
public synchronized void connect(String group, String partitionId) throws KettleDatabaseException
{
// Before anything else, let's see if we already have a connection defined for this group/partition!
// The group is called after the thread-name of the transformation or job that is running
// The name of that threadname is expected to be unique (it is in Kettle)
// So the deal is that if there is another thread using that, we go for it.
//
if (!Const.isEmpty(group))
{
this.connectionGroup = group;
this.partitionId = partitionId;
DatabaseConnectionMap map = DatabaseConnectionMap.getInstance();
// Try to find the conection for the group
Database lookup = map.getDatabase(group, partitionId, this);
if (lookup==null) // We already opened this connection for the partition & database in this group
{
// Do a normal connect and then store this database object for later re-use.
normalConnect(partitionId);
opened++;
copy = opened;
map.storeDatabase(group, partitionId, this);
}
else
{
connection = lookup.getConnection();
lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection.
copy = lookup.getOpened();
}
}
else
{
// Proceed with a normal connect
normalConnect(partitionId);
}
}
/**
* Open the database connection.
* @param partitionId the partition ID in the cluster to connect to.
* @throws KettleDatabaseException if something went wrong.
*/
public void normalConnect(String partitionId) throws KettleDatabaseException
{
if (databaseMeta==null)
{
throw new KettleDatabaseException("No valid database connection defined!");
}
try
{
// First see if we use connection pooling...
//
if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility
databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own.
)
{
try
{
this.connection = ConnectionPoolUtil.getConnection(databaseMeta, partitionId);
}
catch (Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
else
{
connectUsingClass(databaseMeta.getDriverClass(), partitionId );
if(log.isDetailed()) log.logDetailed(toString(), "Connected to database.");
// See if we need to execute extra SQL statemtent...
String sql = environmentSubstitute( databaseMeta.getConnectSQL() );
// only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc.
if (!Const.isEmpty(sql) && !Const.onlySpaces(sql))
{
execStatements(sql);
if(log.isDetailed()) log.logDetailed(toString(), "Executed connect time SQL statements:"+Const.CR+sql);
}
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
private void initWithJNDI(String jndiName) throws KettleDatabaseException {
connection = null;
try {
DataSource dataSource = DatabaseUtil.getDataSourceFromJndi(jndiName);
if (dataSource != null) {
connection = dataSource.getConnection();
if (connection == null) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} else {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$
}
} catch (Exception e) {
throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName + " : " + e.getMessage()); //$NON-NLS-1$
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException
{
// Install and load the jdbc Driver
// first see if this is a JNDI connection
if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) {
initWithJNDI( environmentSubstitute(databaseMeta.getDatabaseName()) );
return;
}
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
String url;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
url = environmentSubstitute(databaseMeta.getURL(partitionId));
}
else
{
url = environmentSubstitute(databaseMeta.getURL());
}
String clusterUsername=null;
String clusterPassword=null;
if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId))
{
// Get the cluster information...
PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId);
if (partition!=null)
{
clusterUsername = partition.getUsername();
clusterPassword = Encr.decryptPasswordOptionallyEncrypted(partition.getPassword());
}
}
String username;
String password;
if (!Const.isEmpty(clusterUsername))
{
username = clusterUsername;
password = clusterPassword;
}
else
{
username = environmentSubstitute(databaseMeta.getUsername());
password = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(databaseMeta.getPassword()));
}
if (databaseMeta.supportsOptionsInURL())
{
if (!Const.isEmpty(username) || !Const.isEmpty(password))
{
// also allow for empty username with given password, in this case username must be given with one space
connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, ""));
}
else
{
// Perhaps the username is in the URL or no username is required...
connection = DriverManager.getConnection(url);
}
}
else
{
Properties properties = databaseMeta.getConnectionProperties();
if (!Const.isEmpty(username)) properties.put("user", username);
if (!Const.isEmpty(password)) properties.put("password", password);
connection = DriverManager.getConnection(url, properties);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public synchronized void disconnect()
{
try
{
if (connection==null)
{
return ; // Nothing to do...
}
if (connection.isClosed())
{
return ; // Nothing to do...
}
if (pstmt !=null)
{
pstmt.close();
pstmt=null;
}
if (prepStatementLookup!=null)
{
prepStatementLookup.close();
prepStatementLookup=null;
}
if (prepStatementInsert!=null)
{
prepStatementInsert.close();
prepStatementInsert=null;
}
if (prepStatementUpdate!=null)
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
if (pstmt_seq!=null)
{
pstmt_seq.close();
pstmt_seq=null;
}
// See if there are other steps using this connection in a connection group.
// If so, we will hold commit & connection close until then.
//
if (!Const.isEmpty(connectionGroup))
{
return;
}
else
{
if (!isAutoCommit()) // Do we really still need this commit??
{
commit();
}
}
closeConnectionOnly();
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
log.logError(toString(), Const.getStackTracker(ex));
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
log.logError(toString(), Const.getStackTracker(dbe));
}
}
/**
* Only for unique connections usage, typically you use disconnect() to disconnect() from the database.
* @throws KettleDatabaseException in case there is an error during connection close.
*/
public synchronized void closeConnectionOnly() throws KettleDatabaseException {
try
{
if (connection!=null)
{
connection.close();
if (!databaseMeta.isUsingConnectionPool())
{
connection=null;
}
}
if(log.isDetailed()) log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException e) {
throw new KettleDatabaseException("Error disconnecting from database '"+toString()+"'", e);
}
}
/**
* Cancel the open/running queries on the database connection
* @throws KettleDatabaseException
*/
public void cancelQuery() throws KettleDatabaseException
{
cancelStatement(pstmt);
cancelStatement(sel_stmt);
}
/**
* Cancel an open/running SQL statement
* @param statement the statement to cancel
* @throws KettleDatabaseException
*/
public void cancelStatement(Statement statement) throws KettleDatabaseException
{
try
{
if (statement!=null)
{
statement.cancel();
}
if(log.isDebug()) log.logDebug(toString(), "Statement canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling statement", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
if(log.isDetailed()) log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
public void setAutoCommit(boolean useAutoCommit) throws KettleDatabaseException {
try {
connection.setAutoCommit(useAutoCommit);
} catch (SQLException e) {
if (useAutoCommit) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToEnableAutoCommit", toString()));
} else {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToDisableAutoCommit", toString()));
}
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit() throws KettleDatabaseException
{
commit(false);
}
public void commit(boolean force) throws KettleDatabaseException
{
try
{
// Don't do the commit, wait until the end of the transformation.
// When the last database copy (opened counter) is about to be closed, we do a commit
// There is one catch, we need to catch the rollback
// The transformation will stop everything and then we'll do the rollback.
// The flag is in "performRollback", private only
//
if (!Const.isEmpty(connectionGroup) && !force)
{
return;
}
if (getDatabaseMetaData().supportsTransactions())
{
if (log.isDebug()) log.logDebug(toString(), "Commit on database connection ["+toString()+"]");
connection.commit();
}
else
{
if(log.isDetailed()) log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions())
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback() throws KettleDatabaseException
{
rollback(false);
}
public void rollback(boolean force) throws KettleDatabaseException
{
try
{
if (!Const.isEmpty(connectionGroup) && !force)
{
return; // Will be handled by Trans --> endProcessing()
}
if (getDatabaseMetaData().supportsTransactions())
{
if (connection!=null) {
if (log.isDebug()) log.logDebug(toString(), "Rollback on database connection ["+toString()+"]");
connection.rollback();
}
}
else
{
if(log.isDetailed()) log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The row metadata to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException
{
prepareInsert(rowMeta, null, tableName);
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param rowMeta The metadata row to determine which values need to be inserted
* @param schemaName The name of the schema in which we want to insert rows
* @param tableName The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException
{
if (rowMeta.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(schemaName, tableName, rowMeta);
if(log.isDetailed()) log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database. (does not return generated keys)
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
return prepareSQL(sql, false);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @param returnKeys set to true if you want to return generated keys from an insert statement
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException
{
try
{
if (returnKeys)
{
return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
pstmt=null;
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
prepStatementUpdate=null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, pstmt);
}
public void setValues(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData());
}
public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementInsert);
}
public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), prepStatementInsert);
}
public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementUpdate);
}
public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException
{
setValues(rowMeta, data, prepStatementLookup);
}
public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException
{
int pos;
if (result) pos=2; else pos=1;
for (int i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT"))
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]);
Object value = data[argnrs[i]];
setValue(cstmt, valueMeta, value, pos);
pos++;
} else {
pos++; //next parameter when OUT
}
}
}
public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case ValueMetaInterface.TYPE_NUMBER :
if (!v.isNull(object))
{
debug="Number, not null, getting number from value";
double num = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
debug="Number, rounding to precision ["+v.getPrecision()+"]";
num = Const.round(num, v.getPrecision());
}
debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement";
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case ValueMetaInterface.TYPE_INTEGER:
debug="Integer";
if (!v.isNull(object))
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, v.getInteger(object).longValue() );
}
else
{
double d = v.getNumber(object).doubleValue();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, d );
}
else
{
ps.setDouble(pos, Const.round( d, v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.INTEGER);
}
break;
case ValueMetaInterface.TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (!v.isNull(object))
{
ps.setString(pos, v.getString(object));
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (!v.isNull(object))
{
String string = v.getString(object);
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = string.length();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = string.substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
debug="Date";
if (!v.isNull(object))
{
long dat = v.getInteger(object).longValue(); // converts using Date.getTime()
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIMESTAMP);
}
}
break;
case ValueMetaInterface.TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (!v.isNull(object))
{
ps.setBoolean(pos, v.getBoolean(object).booleanValue());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (!v.isNull(object))
{
ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
debug="BigNumber";
if (!v.isNull(object))
{
ps.setBigDecimal(pos, v.getBigNumber(object));
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case ValueMetaInterface.TYPE_BINARY:
debug="Binary";
if (!v.isNull(object))
{
ps.setBytes(pos, v.getBinary(object));
}
else
{
ps.setNull(pos, java.sql.Types.BINARY);
}
break;
default:
debug="default";
// placeholder
ps.setNull(pos, java.sql.Types.VARCHAR);
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException
{
setValues(row.getRowMeta(), row.getData(), ps);
}
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException
{
// now set the values in the row!
for (int i=0;i<rowMeta.size();i++)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
/**
* Sets the values of the preparedStatement pstmt.
* @param rowMeta
* @param data
*/
public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException
{
// now set the values in the row!
int index=0;
for (int i=0;i<rowMeta.size();i++)
{
if (i!=ignoreThisValueIndex)
{
ValueMetaInterface v = rowMeta.getValueMeta(i);
Object object = data[i];
try
{
setValue(ps, v, object, index+1);
index++;
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+rowMeta, e);
}
}
}
}
/**
* @param ps The prepared insert statement to use
* @return The generated keys in auto-increment fields
* @throws KettleDatabaseException in case something goes wrong retrieving the keys.
*/
public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException
{
ResultSet keys = null;
try
{
keys=ps.getGeneratedKeys(); // 1 row of keys
ResultSetMetaData resultSetMetaData = keys.getMetaData();
RowMetaInterface rowMeta = getRowInfo(resultSetMetaData, false, false);
return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta));
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex);
}
finally
{
if (keys!=null)
{
try
{
keys.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e);
}
}
}
}
public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException
{
return getNextSequenceValue(null, sequenceName, keyfield);
}
public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException
{
Long retval=null;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence)));
}
ResultSet rs=null;
try
{
rs = pstmt_seq.executeQuery();
if (rs.next())
{
retval = Long.valueOf( rs.getLong(1) );
}
}
finally
{
if ( rs != null ) rs.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex);
}
return retval;
}
public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields, data);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, RowMetaInterface fields)
{
return getInsertStatement(null, tableName, fields);
}
public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields)
{
StringBuffer ins=new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append(" (");
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
ins.append(" ?");
}
ins.append(')');
return ins.toString();
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commit size)
* @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
* @throws KettleDatabaseException
*/
public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
String debug="insertRow start";
boolean rowsAreSafe=false;
try
{
// Unique connections and Batch inserts don't mix when you want to roll back on certain databases.
// That's why we disable the batch insert in that case.
//
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup);
//
// Add support for batch inserts...
//
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
ps.addBatch(); // Add the batch, but don't forget to run the batch
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
/*
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
batchCounterMap.put(ps, Integer.valueOf(0));
}
else
{
debug="insertRow normal commit";
commit();
}
rowsAreSafe=true;
}
*/
return rowsAreSafe;
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
// 'seed' the loop with the root exception
SQLException nextException = ex;
do
{
exceptions.add(nextException);
// while current exception has next exception, add to list
}
while ((nextException = nextException.getNextException())!=null);
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
// log.logError(toString(), Const.getStackTracker(ex));
throw new KettleDatabaseException("Error inserting/updating row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting/updating row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
/**
* Close the prepared statement of the insert statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*/
public void emptyAndCommit(PreparedStatement ps, boolean batch, int batchCounter) throws KettleDatabaseException {
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Execute the batch or just perform a commit.
//
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0)
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
//
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
//
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to empty ps and commit connection.", ex);
}
}
/**
* Close the prepared statement of the insert statement.
*
* @param ps The prepared statement to empty and close.
* @param batch true if you are using batch processing (typically true for this method)
* @param psBatchCounter The number of rows on the batch queue
* @throws KettleDatabaseException
*
* @deprecated use emptyAndCommit() instead (pass in the number of rows left in the batch)
*/
public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
// Execute the batch or just perform a commit.
//
if (batch && getDatabaseMetaData().supportsBatchUpdates())
{
// The problem with the batch counters is that you can't just execute the current batch.
// Certain databases have a problem if you execute the batch and if there are no statements in it.
// You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything.
// That leaves the task of keeping track of the number of rows up to our responsibility.
//
ps.executeBatch();
commit();
}
else
{
commit();
}
}
// Let's not forget to close the prepared statement.
//
ps.close();
}
}
catch(BatchUpdateException ex)
{
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
List<Exception> exceptions = new ArrayList<Exception>();
SQLException nextException = ex.getNextException();
SQLException oldException = null;
// This construction is specifically done for some JDBC drivers, these drivers
// always return the same exception on getNextException() (and thus go into an infinite loop).
// So it's not "equals" but != (comments from Sven Boden).
while ( (nextException != null) && (oldException != nextException) )
{
exceptions.add(nextException);
oldException = nextException;
nextException = nextException.getNextException();
}
kdbe.setExceptionsList(exceptions);
throw kdbe;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql) throws KettleDatabaseException
{
return execStatement(sql, null, null);
}
public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, data, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
String sqlStripped = databaseMeta.stripCR(sql);
// log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]");
Statement stmt = connection.createStatement();
resultSet = stmt.execute(sqlStripped);
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count);
}
}
// See if a cache needs to be cleared...
if (sql.toUpperCase().startsWith("ALTER TABLE") ||
sql.toUpperCase().startsWith("DROP TABLE") ||
sql.toUpperCase().startsWith("CREATE TABLE")
)
{
DBCache.getInstance().clear(databaseMeta.getName());
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script) throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat;
if (to<=length) stat = all.substring(from, to);
else stat = all.substring(from);
// If it ends with a ; remove that ;
// Oracle for example can't stand it when this happens...
if (stat.length()>0 && stat.charAt(stat.length()-1)==';')
{
stat = stat.substring(0,stat.length()-1);
}
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
if(log.isDetailed()) log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = null;
try
{
rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs);
while (row!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
if (log.isDetailed()) log.logDetailed(toString(), rowMeta.getString(row));
row = getRow(rs);
}
}
else
{
if (log.isDebug()) log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
} catch (KettleValueException e) {
throw new KettleDatabaseException(e); // just pass the error upwards.
}
finally
{
try
{
if ( rs != null ) rs.close();
}
catch (SQLException ex )
{
if (log.isDebug()) log.logDebug(toString(), "Error closing query: "+Const.CR+sql);
}
}
}
else // any kind of statement
{
if(log.isDetailed()) log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
if(log.isDetailed()) log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql) throws KettleDatabaseException
{
return openQuery(sql, null, null);
}
/**
* Open a query on the database with a set of parameters stored in a Kettle Row
* @param sql The SQL to launch with question marks (?) as placeholders for the parameters
* @param params The parameters or null if no parameters are used.
* @data the parameter data to open the query with
* @return A JDBC ResultSet
* @throws KettleDatabaseException when something goes wrong with the query.
*/
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
return openQuery(sql, params, data, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException
{
return openQuery(sql, params, data, fetch_mode, false);
}
public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params, data); // set the dates etc!
if (canWeSetFetchSize(pstmt) )
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
pstmt.setFetchSize(Integer.MIN_VALUE);
}
else
pstmt.setFetchSize(fs);
}
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (canWeSetFetchSize(sel_stmt))
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(fs);
}
debug = "Set fetch direction";
sel_stmt.setFetchDirection(fetch_mode);
}
debug = "Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "openQuery : get rowinfo";
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
//
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, lazyConversion);
}
catch(SQLException ex)
{
// log.logError(toString(), "ERROR executing ["+sql+"]");
// log.logError(toString(), "ERROR in part: ["+debug+"]");
// printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
private boolean canWeSetFetchSize(Statement statement) throws SQLException
{
return databaseMeta.isFetchSizeSupported() &&
( statement.getMaxRows()>0 ||
databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES ||
( databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults() )
);
}
public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, data, ps); // set the parameters!
if (canWeSetFetchSize(ps))
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults())
{
ps.setFetchSize(Integer.MIN_VALUE);
}
else
{
ps.setFetchSize(fs);
}
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ getRowInfo()";
// rowinfo = getRowInfo(res.getMetaData());
// MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened
// to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows.
//
rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, false);
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException
{
return getQueryFields(sql, param, null, null);
}
/**
* See if the table specified exists by reading
* @param tablename The name of the table to check.<br>
* This is supposed to be the properly quoted name of the table or the complete schema-table name combination.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename) throws KettleDatabaseException
{
try
{
if(log.isDebug()) log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
// Just try to read from the table.
String sql = databaseMeta.getSQLTableExists(tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
/*
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
*/
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* See if the column specified exists by reading
* @param columnname The name of the column to check.
* @param tablename The name of the table to check.<br>
* This is supposed to be the properly quoted name of the table or the complete schema-table name combination.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkColumnExists(String columnname, String tablename) throws KettleDatabaseException
{
try
{
if(log.isDebug()) log.logDebug(toString(), "Checking if column [" + columnname + "] exists in table ["+tablename+"] !");
// Just try to read from the table.
String sql = databaseMeta.getSQLColumnExists(columnname,tablename);
try
{
getOneRow(sql);
return true;
}
catch(KettleDatabaseException e)
{
return false;
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if column [" + columnname + "] exists in table ["+tablename+"] on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException
{
return checkSequenceExists(null, sequenceName);
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
try
{
//
// Get the info from the data dictionary...
//
String sql = databaseMeta.getSQLSequenceExists(schemaSequence);
ResultSet res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tableName The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException
{
return checkIndexExists(null, tableName, idx_fields);
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException
{
String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
if (!checkTableExists(tablename)) return false;
if(log.isDebug()) log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
//
// Get the info from the data dictionary...
//
StringBuffer sql = new StringBuffer(128);
sql.append("select i.name table_name, c.name column_name ");
sql.append("from sysindexes i, sysindexkeys k, syscolumns c ");
sql.append("where i.name = '"+tablename+"' ");
sql.append("AND i.id = k.id ");
sql.append("AND i.id = c.id ");
sql.append("AND k.colid = c.colid ");
ResultSet res = null;
try
{
res = openQuery(sql.toString());
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
//
// Get the info from the data dictionary...
//
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tableName+"'";
ResultSet res = null;
try {
res = openQuery(sql);
if (res!=null)
{
Object[] row = getRow(res);
while (row!=null)
{
String column = rowMeta.getString(row, "COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
}
else
{
return false;
}
}
finally
{
if ( res != null ) closeQuery(res);
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = null;
try
{
indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
}
finally
{
if ( indexList != null ) indexList.close();
}
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
log.logError(toString(), Const.getStackTracker(e));
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon);
}
public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" ";
cr_index += "ON ";
// assume table has already been quoted (and possibly includes schema)
cr_index += tablename;
cr_index += Const.CR + "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace());
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String sequence, String start_at, String increment_by, String max_value, boolean semi_colon)
{
return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
return getCreateSequenceStatement(schemaName, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon);
}
public String getCreateSequenceStatement(String schemaName, String sequenceName, String start_at, String increment_by, String max_value, boolean semi_colon)
{
String cr_seq="";
if (Const.isEmpty(sequenceName)) return cr_seq;
if (databaseMeta.supportsSequences())
{
String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName);
cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value != null) {
//"-1" means there is no maxvalue, must be handles different by DB2 / AS400
if ((databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_DB2 ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_AS400 ) &&
max_value.trim().equals("-1")) {
cr_seq += "NOMAXVALUE"+Const.CR;
} else {
// set the max value
cr_seq += "MAXVALUE "+max_value+Const.CR;
}
}
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
//
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
// The new method of retrieving the query fields fails on Oracle because
// they failed to implement the getMetaData method on a prepared statement. (!!!)
// Even recent drivers like 10.2 fail because of it.
//
// There might be other databases that don't support it (we have no knowledge of this at the time of writing).
// If we discover other RDBMSs, we will create an interface for it.
// For now, we just try to get the field layout on the re-bound in the exception block below.
//
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_H2 ||
databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GENERIC)
{
fields=getQueryFieldsFallback(sql, param, inform, data);
}
else
{
// On with the regular program.
//
PreparedStatement preparedStatement = null;
try
{
preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSetMetaData rsmd = preparedStatement.getMetaData();
fields = getRowInfo(rsmd, false, false);
}
catch(Exception e)
{
fields = getQueryFieldsFallback(sql, param, inform, data);
}
finally
{
if (preparedStatement!=null)
{
try
{
preparedStatement.close();
}
catch (SQLException e)
{
throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e);
}
}
}
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
private RowMetaInterface getQueryFieldsFallback(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException
{
RowMetaInterface fields;
try
{
if (inform==null
// Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214)
&& databaseMeta.getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_MSSQL
)
{
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
sel_stmt.setFetchSize(Integer.MIN_VALUE);
}
else
{
sel_stmt.setFetchSize(1);
}
}
if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1);
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
fields = getRowInfo(r.getMetaData(), false, false);
r.close();
sel_stmt.close();
sel_stmt=null;
}
else
{
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
RowMetaInterface par = inform;
if (par==null || par.isEmpty()) par = getParameterMetaData(ps);
if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data);
setValues(par, data, ps);
}
ResultSet r = ps.executeQuery();
fields=getRowInfo(ps.getMetaData(), false, false);
r.close();
ps.close();
}
}
catch(Exception ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex);
}
return fields;
}
public void closeQuery(ResultSet res) throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
/**
* Build the row using ResultSetMetaData rsmd
* @param rm The resultset metadata to inquire
* @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem)
* @param lazyConversion true if lazy conversion needs to be enabled where possible
*/
private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException
{
if (rm==null) return null;
rowMeta = new RowMeta();
try
{
// TODO If we do lazy conversion, we need to find out about the encoding
//
int fieldNr = 1;
int nrcols=rm.getColumnCount();
for (int i=1;i<=nrcols;i++)
{
String name=new String(rm.getColumnName(i));
// Check the name, sometimes it's empty.
//
if (Const.isEmpty(name) || Const.onlySpaces(name))
{
name = "Field"+fieldNr;
fieldNr++;
}
ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion);
rowMeta.addValueMeta(v);
}
return rowMeta;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException
{
int length=-1;
int precision=-1;
int valtype=ValueMetaInterface.TYPE_NONE;
boolean isClob = false;
int type = rm.getColumnType(index);
boolean signed = rm.isSigned(index);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=ValueMetaInterface.TYPE_STRING;
if (!ignoreLength) length=rm.getColumnDisplaySize(index);
break;
case java.sql.Types.CLOB:
valtype=ValueMetaInterface.TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
isClob=true;
break;
case java.sql.Types.BIGINT:
// verify Unsigned BIGINT overflow!
//
if (signed)
{
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
}
else
{
valtype=ValueMetaInterface.TYPE_BIGNUMBER;
precision=0; // Max 18.446.744.073.709.551.615
length=16;
}
break;
case java.sql.Types.INTEGER:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=ValueMetaInterface.TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=ValueMetaInterface.TYPE_NUMBER;
length=rm.getPrecision(index);
precision=rm.getScale(index);
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL)
{
if (precision==0)
{
precision=-1; // precision is obviously incorrect if the type if Double/Float/Real
}
// If we're dealing with PostgreSQL and double precision types
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16)
{
precision=-1;
length=-1;
}
// MySQL: max resolution is double precision floating point (double)
// The (12,31) that is given back is not correct
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL)
{
if (precision >= length) {
precision=-1;
length=-1;
}
}
}
else
{
if (precision==0 && length<18 && length>0) // Among others Oracle is affected here.
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
}
if (length>18 || precision>18) valtype=ValueMetaInterface.TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision == 0 && length == 38 )
{
valtype=ValueMetaInterface.TYPE_INTEGER;
}
if (precision<=0 && length<=0) // undefined size: BIGNUMBER, precision on Oracle can be 38, too big for a Number type
{
valtype=ValueMetaInterface.TYPE_BIGNUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_TERADATA) {
precision = 1;
}
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=ValueMetaInterface.TYPE_DATE;
//
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL) {
String property = databaseMeta.getConnectionProperties().getProperty("yearIsDateType");
if (property != null && property.equalsIgnoreCase("false")
&& rm.getColumnTypeName(index).equalsIgnoreCase("YEAR")) {
valtype = ValueMetaInterface.TYPE_INTEGER;
precision = 0;
length = 4;
break;
}
}
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
valtype=ValueMetaInterface.TYPE_BOOLEAN;
break;
case java.sql.Types.BINARY:
case java.sql.Types.BLOB:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
valtype=ValueMetaInterface.TYPE_BINARY;
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 &&
(2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index))
{
// set the length for "CHAR(X) FOR BIT DATA"
length = rm.getPrecision(index);
}
else
if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_ORACLE &&
( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY )
)
{
// set the length for Oracle "RAW" or "LONGRAW" data types
valtype = ValueMetaInterface.TYPE_STRING;
length = rm.getColumnDisplaySize(index);
}
else
{
length=-1;
}
precision=-1;
break;
default:
valtype=ValueMetaInterface.TYPE_STRING;
precision=rm.getScale(index);
break;
}
// Grab the comment as a description to the field as well.
String comments=rm.getColumnLabel(index);
// get & store more result set meta data for later use
int originalColumnType=rm.getColumnType(index);
String originalColumnTypeName=rm.getColumnTypeName(index);
int originalPrecision=-1;
if (!ignoreLength) rm.getPrecision(index); // Throws exception on MySQL
int originalScale=rm.getScale(index);
// boolean originalAutoIncrement=rm.isAutoIncrement(index); DISABLED FOR PERFORMANCE REASONS : PDI-1788
// int originalNullable=rm.isNullable(index); DISABLED FOR PERFORMANCE REASONS : PDI-1788
boolean originalSigned=rm.isSigned(index);
ValueMetaInterface v=new ValueMeta(name, valtype);
v.setLength(length);
v.setPrecision(precision);
v.setComments(comments);
v.setLargeTextField(isClob);
v.setOriginalColumnType(originalColumnType);
v.setOriginalColumnTypeName(originalColumnTypeName);
v.setOriginalPrecision(originalPrecision);
v.setOriginalScale(originalScale);
// v.setOriginalAutoIncrement(originalAutoIncrement); DISABLED FOR PERFORMANCE REASONS : PDI-1788
// v.setOriginalNullable(originalNullable); DISABLED FOR PERFORMANCE REASONS : PDI-1788
v.setOriginalSigned(originalSigned);
// See if we need to enable lazy conversion...
//
if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) {
v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING);
// TODO set some encoding to go with this.
// Also set the storage metadata. a copy of the parent, set to String too.
//
ValueMetaInterface storageMetaData = v.clone();
storageMetaData.setType(ValueMetaInterface.TYPE_STRING);
storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL);
v.setStorageMetadata(storageMetaData);
}
return v;
}
public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs) throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset. Do not use lazy conversion
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs) throws KettleDatabaseException
{
return getRow(rs, false);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @param lazyConversion set to true if strings need to have lazy conversion enabled
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException
{
if (rowMeta==null)
{
ResultSetMetaData rsmd = null;
try
{
rsmd = rs.getMetaData();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e);
}
rowMeta = getRowInfo(rsmd, false, lazyConversion);
}
return getRow(rs, null, rowMeta);
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException
{
try
{
int nrcols=rowInfo.size();
Object[] data = RowDataUtil.allocateRowData(nrcols);
if (rs.next())
{
for (int i=0;i<nrcols;i++)
{
ValueMetaInterface val = rowInfo.getValueMeta(i);
switch(val.getType())
{
case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break;
case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break;
case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break;
case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break;
case ValueMetaInterface.TYPE_STRING :
{
if (val.isStorageBinaryString()) {
data[i] = rs.getBytes(i+1);
}
else {
data[i] = rs.getString(i+1);
}
}
break;
case ValueMetaInterface.TYPE_BINARY :
{
if (databaseMeta.supportsGetBlob())
{
Blob blob = rs.getBlob(i+1);
if (blob!=null)
{
data[i] = blob.getBytes(1L, (int)blob.length());
}
else
{
data[i] = null;
}
}
else
{
data[i] = rs.getBytes(i+1);
}
}
break;
case ValueMetaInterface.TYPE_DATE :
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW && val.getOriginalColumnType()==java.sql.Types.TIME)
{
// Neoview can not handle getDate / getTimestamp for a Time column
data[i] = rs.getTime(i+1); break; // Time is a subclass of java.util.Date, the default date will be 1970-01-01
}
else if (val.getPrecision()!=1 && databaseMeta.supportsTimeStampToDateConversion())
{
data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date
}
else
{
data[i] = rs.getDate(i+1); break;
}
default: break;
}
if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too.
}
}
else
{
data=null;
}
return data;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String schema, String table, String codes[], String condition[],
String gets[], String rename[], String orderby
) throws KettleDatabaseException
{
setLookup(schema, table, codes, condition, gets, rename, orderby, false);
}
public void setLookup(String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults);
}
// Lookup certain fields in a table
public void setLookup(String schemaName, String tableName, String codes[], String condition[],
String gets[], String rename[], String orderby,
boolean checkForMultipleResults) throws KettleDatabaseException
{
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String sql = "SELECT ";
for (int i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(gets[i]);
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+databaseMeta.quoteField(rename[i]);
}
}
sql += " FROM "+table+" WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += databaseMeta.quoteField(codes[i]);
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
if(log.isDetailed()) log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows())
{
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
return prepareUpdate(null, table, codes, condition, sets);
}
// Lookup certain fields in a table
public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[])
{
StringBuffer sql = new StringBuffer(128);
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET ");
for (int i=0;i<sets.length;i++)
{
if (i!=0) sql.append(", ");
sql.append(databaseMeta.quoteField(sets[i]));
sql.append(" = ?").append(Const.CR);
}
sql.append("WHERE ");
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql.append("AND ");
sql.append(databaseMeta.quoteField(codes[i]));
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql.append(" BETWEEN ? AND ? ");
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql.append(' ').append(condition[i]).append(' ');
}
else
{
sql.append(' ').append(condition[i]).append(" ? ");
}
}
try
{
String s = sql.toString();
if(log.isDetailed()) log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param table The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String table, String codes[], String condition[])
{
return prepareDelete(null, table, codes, condition);
}
/**
* Prepare a delete statement by giving it the tablename, fields and conditions to work with.
* @param schemaName the schema-name to delete in
* @param tableName The table-name to delete in
* @param codes
* @param condition
* @return true when everything went OK, false when something went wrong.
*/
public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[])
{
String sql;
String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
sql = "DELETE FROM "+table+Const.CR;
sql+= "WHERE ";
for (int i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
if(log.isDetailed()) log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (int i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
if(log.isDetailed()) log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (!Const.isEmpty(returnvalue))
{
switch(returntype)
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
public Object[] getLookup() throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException
{
return getLookup(prepStatementLookup, failOnMultipleResults);
}
public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException
{
return getLookup(ps, false);
}
public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException
{
ResultSet res = null;
try
{
res = ps.executeQuery();
rowMeta = getRowInfo(res.getMetaData(), false, false);
Object[] ret = getRow(res);
if (failOnMultipleResults)
{
if (ret != null && res.next())
{
// if the previous row was null, there's no reason to try res.next() again.
// on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver).
throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!");
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database", ex);
}
finally
{
try
{
if (res!=null) res.close(); // close resultset!
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to close resultset after looking up data", e);
}
}
}
public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null;
if (checkTableExists(tableName))
{
retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon);
}
return retval;
}
/**
* Generates SQL
* @param tableName the table name or schema/table combination: this needs to be quoted properly in advance.
* @param fields the fields
* @param tk the name of the technical key field
* @param use_autoinc true if we need to use auto-increment fields for a primary key
* @param pk the name of the primary/technical key field
* @param semicolon append semicolon to the statement
* @return the SQL needed to create the specified table and fields.
*/
public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tableName+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
ValueMetaInterface v=fields.getValueMeta(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (pk==null && tk==null && databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW)
{
retval+="NO PARTITION"; // use this as a default when no pk/tk is there, otherwise you get an error
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
RowMetaInterface tabFields = getTableFields(tableName);
// Don't forget to quote these as well...
databaseMeta.quoteReservedWords(tabFields);
// Find the missing fields
RowMetaInterface missing = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface v = fields.getValueMeta(i);
// Not found?
if (tabFields.searchValueMeta( v.getName() )==null )
{
missing.addValueMeta(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
ValueMetaInterface v=missing.getValueMeta(i);
retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
RowMetaInterface surplus = new RowMeta();
for (int i=0;i<tabFields.size();i++)
{
ValueMetaInterface v = tabFields.getValueMeta(i);
// Found in table, not in input ?
if (fields.searchValueMeta( v.getName() )==null )
{
surplus.addValueMeta(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
ValueMetaInterface v=surplus.getValueMeta(i);
retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
//
// OK, see if there are fields for wich we need to modify the type... (length, precision)
//
RowMetaInterface modify = new RowMeta();
for (int i=0;i<fields.size();i++)
{
ValueMetaInterface desiredField = fields.getValueMeta(i);
ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
// TODO: this is not an optimal way of finding out changes.
// Perhaps we should just generate the data types strings for existing and new data type and see if anything changed.
//
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValueMeta(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
ValueMetaInterface v=modify.getValueMeta(i);
retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(null, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.quoteField(tablename));
}
}
public void truncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
execStatement(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Object[] row = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return new RowMetaAndData(rowMeta, row);
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException {
RowMeta meta = new RowMeta();
for( int i=0; i<md.getColumnCount(); i++ ) {
String name = md.getColumnName(i+1);
ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false );
meta.addValueMeta( valueMeta );
}
return meta;
}
public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param, data);
if (rs!=null)
{
Object[] row = getRow(rs); // One value: a number;
rowMeta=null;
RowMeta tmpMeta = null;
try {
ResultSetMetaData md = rs.getMetaData();
tmpMeta = getMetaFromRow( row, md );
} catch (Exception e) {
e.printStackTrace();
} finally {
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
}
return new RowMetaAndData(tmpMeta, row);
}
else
{
return null;
}
}
public RowMetaInterface getParameterMetaData(PreparedStatement ps)
{
RowMetaInterface par = new RowMeta();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<=pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
ValueMeta val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN);
break;
default:
val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER);
}
par.addValueMeta(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data)
{
// The database couldn't handle it: try manually!
int q=countParameters(sql);
RowMetaInterface par=new RowMeta();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
ValueMetaInterface inf=inform.getValueMeta(i);
ValueMetaInterface v = inf.clone();
par.addValueMeta(v);
}
}
else
{
for (int i=0;i<q;i++)
{
ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER);
par.addValueMeta(v);
}
}
return par;
}
public static final RowMetaInterface getTransLogrecordFields(boolean update, boolean use_batchid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_batchid && !update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING, 255, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING , 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_batchid && update)
{
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public static final RowMetaInterface getJobLogrecordFields(boolean update, boolean use_jobid, boolean use_logfield)
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
if (use_jobid && !update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
if (!update)
{
v=new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING,255, 0); r.addValueMeta(v);
}
v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING, 15, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
if (use_logfield)
{
v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0);
r.addValueMeta(v);
}
if (use_jobid && update)
{
v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
}
return r;
}
public void writeLogRecord(String logtable, boolean use_id, long id, boolean job, String name, String status, long read, long written, long updated, long input, long output, long errors, java.util.Date startdate, java.util.Date enddate, java.util.Date logdate, java.util.Date depdate, java.util.Date replayDate, String log_string) throws KettleDatabaseException {
boolean update = use_id && log_string != null && !status.equalsIgnoreCase(LOG_STATUS_START);
RowMetaInterface rowMeta;
if (job) {
rowMeta = getJobLogrecordFields(update, use_id, !Const.isEmpty(log_string));
} else {
rowMeta = getTransLogrecordFields(update, use_id, !Const.isEmpty(log_string));
}
if (update) {
String sql = "UPDATE " + logtable + " SET ";
for (int i = 0; i < rowMeta.size() - 1; i++) // Without ID_JOB or ID_BATCH
{
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
if (i > 0) {
sql += ", ";
}
sql += databaseMeta.quoteField(valueMeta.getName()) + "=? ";
}
sql += "WHERE ";
if (job) {
sql += databaseMeta.quoteField("ID_JOB") + "=? ";
} else {
sql += databaseMeta.quoteField("ID_BATCH") + "=? ";
}
Object[] data = new Object[] {
status,
Long.valueOf(read), Long.valueOf(written),
Long.valueOf(input), Long.valueOf(output),
Long.valueOf(updated), Long.valueOf(errors),
startdate, enddate, logdate, depdate, replayDate,
log_string,
Long.valueOf(id),
};
execStatement(sql, rowMeta, data);
} else {
String sql = "INSERT INTO " + logtable + " ( ";
for (int i = 0; i < rowMeta.size(); i++) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta(i);
if (i > 0)
sql += ", ";
sql += databaseMeta.quoteField(valueMeta.getName());
}
sql += ") VALUES(";
for (int i = 0; i < rowMeta.size(); i++) {
if (i > 0)
sql += ", ";
sql += "?";
}
sql += ")";
try {
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
List<Object> data = new ArrayList<Object>();
if (job) {
if (use_id) {
data.add(Long.valueOf(id));
}
data.add(name);
} else {
if (use_id) {
data.add(Long.valueOf(id));
}
data.add(name);
}
data.add(status);
data.add(Long.valueOf(read));
data.add(Long.valueOf(written));
data.add(Long.valueOf(updated));
data.add(Long.valueOf(input));
data.add(Long.valueOf(output));
data.add(Long.valueOf(errors));
data.add(startdate);
data.add(enddate);
data.add(logdate);
data.add(depdate);
data.add(replayDate);
if (!Const.isEmpty(log_string)) {
data.add(log_string);
}
setValues(rowMeta, data.toArray(new Object[data.size()]));
pstmt.executeUpdate();
pstmt.close();
pstmt = null;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to write log record to log table " + logtable, ex);
}
}
}
public static final RowMetaInterface getStepPerformanceLogrecordFields()
{
RowMetaInterface r = new RowMeta();
ValueMetaInterface v;
v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
v=new ValueMeta("SEQ_NR", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v);
v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v);
v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING ,255, 0); r.addValueMeta(v);
v=new ValueMeta("STEPNAME", ValueMetaInterface.TYPE_STRING ,255, 0); r.addValueMeta(v);
v=new ValueMeta("STEP_COPY", ValueMetaInterface.TYPE_INTEGER, 3, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("LINES_REJECTED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("INPUT_BUFFER_ROWS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
v=new ValueMeta("OUTPUT_BUFFER_ROWS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v);
return r;
}
public Object[] getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException
{
Object[] row = null;
String jobtrans = job?databaseMeta.quoteField("JOBNAME"):databaseMeta.quoteField("TRANSNAME");
String sql = "";
sql+=" SELECT "+databaseMeta.quoteField("ENDDATE")+", "+databaseMeta.quoteField("DEPDATE")+", "+databaseMeta.quoteField("STARTDATE");
sql+=" FROM "+logtable;
sql+=" WHERE "+databaseMeta.quoteField("ERRORS")+" = 0";
sql+=" AND "+databaseMeta.quoteField("STATUS")+" = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY "+databaseMeta.quoteField("LOGDATE")+" DESC, "+databaseMeta.quoteField("ENDDATE")+" DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
RowMetaInterface r = new RowMeta();
r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING));
setValues(r, new Object[] { name });
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rowMeta = getRowInfo(res.getMetaData(), false, false);
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException
{
return getNextValue(counters, null, tableName, val_key);
}
public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException
{
Long nextValue = null;
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
String lookup = schemaTable+"."+databaseMeta.quoteField(val_key);
// Try to find the previous sequence value...
Counter counter = null;
if (counters!=null) counter=counters.get(lookup);
if (counter==null)
{
RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable);
if (rmad!=null)
{
long previous;
try
{
Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0);
// A "select max(x)" on a table with no matching rows will return null.
if ( tmp != null )
previous = tmp.longValue();
else
previous = 0L;
}
catch (KettleValueException e)
{
throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable);
}
counter = new Counter(previous+1, 1);
nextValue = Long.valueOf( counter.next() );
if (counters!=null) counters.put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable);
}
}
else
{
nextValue = Long.valueOf( counter.next() );
}
return nextValue;
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(String sql, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
return getRows(rset, limit, monitor);
}
/** Reads the result of a ResultSet into an ArrayList
*
* @param rset the ResultSet to read out
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public List<Object[]> getRows(ResultSet rset, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
try
{
List<Object[]> result = new ArrayList<Object[]>();
boolean stop=false;
int i=0;
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Object[] row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e);
}
}
public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
/**
* Get the first rows from a table (for preview)
* @param table_name The table name (or schema/table combination): this needs to be quoted properly
* @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException in case something goes wrong
*/
public List<Object[]> getFirstRows(String table_name, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException
{
String sql = "SELECT";
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW)
{
sql+=" [FIRST " + limit +"]";
}
sql += " * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public RowMetaInterface getReturnRowMeta()
{
return rowMeta;
}
public String[] getTableTypes() throws KettleDatabaseException
{
try
{
ArrayList<String> types = new ArrayList<String>();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames() throws KettleDatabaseException
{
return getTablenames(false);
}
public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
List<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getViews() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getViews(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getSynonyms() throws KettleDatabaseException
{
return getViews(false);
}
public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase();
ArrayList<String> names = new ArrayList<String>();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
String schema = alltables.getString("TABLE_SCHEM");
if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog.
String schemaTable;
if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table);
else schemaTable = table;
if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable);
names.add(schemaTable);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
if(log.isDetailed()) log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
List<Object[]> procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Object[])procs.get(i))[0].toString();
}
return str;
}
else
{
ResultSet rs = null;
try
{
DatabaseMetaData dbmd = getDatabaseMetaData();
rs = dbmd.getProcedures(null, null, null);
List<Object[]> rows = getRows(rs, 0, null);
String result[] = new String[rows.size()];
for (int i=0;i<rows.size();i++)
{
Object[] row = (Object[])rows.get(i);
String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null);
String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null);
String procName = rowMeta.getString(row, "PROCEDURE_NAME", "");
String name = "";
if (procCatalog!=null) name+=procCatalog+".";
else if (procSchema!=null) name+=procSchema+".";
name+=procName;
result[i] = name;
}
return result;
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e);
}
finally
{
if (rs!=null) try { rs.close(); } catch(Exception e) {}
}
}
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
//
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to lock the (quoted) tables
//
String sql = databaseMeta.getSQLLockTables(quotedTableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
if (Const.isEmpty(tableNames)) return;
// Quote table names too...
//
String[] quotedTableNames = new String[tableNames.length];
for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]);
// Get the SQL to unlock the (quoted) tables
//
String sql = databaseMeta.getSQLUnlockTables(quotedTableNames);
if (sql!=null)
{
execStatement(sql);
}
}
/**
* @return the opened
*/
public int getOpened()
{
return opened;
}
/**
* @param opened the opened to set
*/
public void setOpened(int opened)
{
this.opened = opened;
}
/**
* @return the connectionGroup
*/
public String getConnectionGroup()
{
return connectionGroup;
}
/**
* @param connectionGroup the connectionGroup to set
*/
public void setConnectionGroup(String connectionGroup)
{
this.connectionGroup = connectionGroup;
}
/**
* @return the partitionId
*/
public String getPartitionId()
{
return partitionId;
}
/**
* @param partitionId the partitionId to set
*/
public void setPartitionId(String partitionId)
{
this.partitionId = partitionId;
}
/**
* @return the copy
*/
public int getCopy()
{
return copy;
}
/**
* @param copy the copy to set
*/
public void setCopy(int copy)
{
this.copy = copy;
}
public void copyVariablesFrom(VariableSpace space)
{
variables.copyVariablesFrom(space);
}
public String environmentSubstitute(String aString)
{
return variables.environmentSubstitute(aString);
}
public String[] environmentSubstitute(String aString[])
{
return variables.environmentSubstitute(aString);
}
public VariableSpace getParentVariableSpace()
{
return variables.getParentVariableSpace();
}
public void setParentVariableSpace(VariableSpace parent)
{
variables.setParentVariableSpace(parent);
}
public String getVariable(String variableName, String defaultValue)
{
return variables.getVariable(variableName, defaultValue);
}
public String getVariable(String variableName)
{
return variables.getVariable(variableName);
}
public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) {
if (!Const.isEmpty(variableName))
{
String value = environmentSubstitute(variableName);
if (!Const.isEmpty(value))
{
return ValueMeta.convertStringToBoolean(value);
}
}
return defaultValue;
}
public void initializeVariablesFrom(VariableSpace parent)
{
variables.initializeVariablesFrom(parent);
}
public String[] listVariables()
{
return variables.listVariables();
}
public void setVariable(String variableName, String variableValue)
{
variables.setVariable(variableName, variableValue);
}
public void shareVariablesWith(VariableSpace space)
{
variables = space;
// Also share the variables with the meta data object
// Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case.
//
if (space!=databaseMeta) databaseMeta.shareVariablesWith(space);
}
public void injectVariables(Map<String,String> prop)
{
variables.injectVariables(prop);
}
public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype) throws KettleDatabaseException {
RowMetaAndData ret;
try {
cstmt.execute();
ret = new RowMetaAndData();
int pos = 1;
if (resultname != null && resultname.length() != 0) {
ValueMeta vMeta = new ValueMeta(resultname, resulttype);
Object v =null;
switch (resulttype) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getDate(pos);
break;
}
ret.addValue(vMeta, v);
pos++;
}
for (int i = 0; i < arg.length; i++) {
if (argdir[i].equalsIgnoreCase("OUT")
|| argdir[i].equalsIgnoreCase("INOUT")) {
ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]);
Object v=null;
switch (argtype[i]) {
case ValueMetaInterface.TYPE_BOOLEAN:
v=Boolean.valueOf(cstmt.getBoolean(pos + i));
break;
case ValueMetaInterface.TYPE_NUMBER:
v=new Double(cstmt.getDouble(pos + i));
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
v=cstmt.getBigDecimal(pos + i);
break;
case ValueMetaInterface.TYPE_INTEGER:
v=Long.valueOf(cstmt.getLong(pos + i));
break;
case ValueMetaInterface.TYPE_STRING:
v=cstmt.getString(pos + i);
break;
case ValueMetaInterface.TYPE_DATE:
v=cstmt.getTimestamp(pos + i);
break;
}
ret.addValue(vMeta, v);
}
}
return ret;
} catch (SQLException ex) {
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
/**
* Return SQL CREATION statement for a Table
* @param tableName The table to create
* @throws KettleDatabaseException
*/
public String getDDLCreationTable(String tableName, RowMetaInterface fields) throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.quoteReservedWords(fields);
String quotedTk=databaseMeta.quoteField(null);
retval=getCreateTableStatement(tableName, fields, quotedTk, false, null, true);
return retval;
}
/**
* Return SQL TRUNCATE statement for a Table
* @param schema The schema
* @param tableNameWithSchema The table to create
* @throws KettleDatabaseException
*/
public String getDDLTruncateTable(String schema, String tablename) throws KettleDatabaseException
{
if (Const.isEmpty(connectionGroup))
{
return(databaseMeta.getTruncateTableStatement(schema, tablename));
}
else
{
return("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename));
}
}
/**
* Return SQL statement (INSERT INTO TableName ...
* @param schemaName tableName The schema
* @param tableName
* @param fields
* @param dateFormat date format of field
* @throws KettleDatabaseException
*/
public String getSQLOutput(String schemaName, String tableName, RowMetaInterface fields, Object[] r,String dateFormat) throws KettleDatabaseException
{
StringBuffer ins=new StringBuffer(128);
try{
String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName);
ins.append("INSERT INTO ").append(schemaTable).append('(');
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(", ");
String name = fields.getValueMeta(i).getName();
ins.append(databaseMeta.quoteField(name));
}
ins.append(") VALUES (");
// new add values ...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins.append(",");
{
if (fields.getValueMeta(i).getType()==ValueMeta.TYPE_STRING)
ins.append("'" + fields.getString(r,i) + "'") ;
else if (fields.getValueMeta(i).getType()==ValueMeta.TYPE_DATE)
{
if (Const.isEmpty(dateFormat))
ins.append("'" + fields.getString(r,i)+ "'") ;
else
{
try
{
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(dateFormat);
ins.append("'" + formatter.format(fields.getDate(r,i))+ "'") ;
}
catch(Exception e)
{
throw new KettleDatabaseException("Error : ", e);
}
}
}
else
{
ins.append( fields.getString(r,i)) ;
}
}
}
ins.append(')');
}catch (Exception e)
{
throw new KettleDatabaseException(e);
}
return ins.toString();
}
public Savepoint setSavepoint() throws KettleDatabaseException {
try {
return connection.setSavepoint();
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToSetSavepoint"), e);
}
}
public Savepoint setSavepoint(String savePointName) throws KettleDatabaseException {
try {
return connection.setSavepoint(savePointName);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToSetSavepointName", savePointName), e);
}
}
public void releaseSavepoint(Savepoint savepoint) throws KettleDatabaseException {
try {
connection.releaseSavepoint(savepoint);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToReleaseSavepoint"), e);
}
}
public void rollback(Savepoint savepoint) throws KettleDatabaseException {
try {
connection.rollback(savepoint);
} catch (SQLException e) {
throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToRollbackToSavepoint"), e);
}
}
}
| PDI-1891 Dimension lookup does not commit at commitsize
git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@9671 5fb7f6ec-07c1-534a-b4ca-9155e429e800
| src-core/org/pentaho/di/core/database/Database.java | PDI-1891 Dimension lookup does not commit at commitsize | <ide><path>rc-core/org/pentaho/di/core/database/Database.java
<ide> private int written;
<ide>
<ide> private LogWriter log;
<del>
<del> /*
<del> * Counts the number of rows written to a batch for a certain PreparedStatement.
<del> *
<del> private Map<PreparedStatement, Integer> batchCounterMap;
<del> */
<ide>
<ide> /**
<ide> * Number of times a connection was opened using this object.
<ide> {
<ide> insertRow(ps, false);
<ide> }
<del>
<add>
<ide> /**
<ide> * Insert a row into the database using a prepared statement that has all values set.
<ide> * @param ps The prepared statement
<ide> * @throws KettleDatabaseException
<ide> */
<ide> public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException
<add> {
<add> return insertRow(ps, false, true);
<add> }
<add> /**
<add> * Insert a row into the database using a prepared statement that has all values set.
<add> * @param ps The prepared statement
<add> * @param batch True if you want to use batch inserts (size = commit size)
<add> * @param handleCommit True if you want to handle the commit here after the commit size (False e.g. in case the step handles this, see TableOutput)
<add> * @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done.
<add> * @throws KettleDatabaseException
<add> */
<add> public boolean insertRow(PreparedStatement ps, boolean batch, boolean handleCommit) throws KettleDatabaseException
<ide> {
<ide> String debug="insertRow start";
<ide> boolean rowsAreSafe=false;
<ide>
<ide> written++;
<ide>
<del> /*
<del> if (!isAutoCommit() && (written%commitsize)==0)
<del> {
<del> if (useBatchInsert)
<add> if (handleCommit) { // some steps handle the commit themselves (see e.g. TableOutput step)
<add> if (!isAutoCommit() && (written%commitsize)==0)
<ide> {
<del> debug="insertRow executeBatch commit";
<del> ps.executeBatch();
<del> commit();
<del> ps.clearBatch();
<del>
<del> batchCounterMap.put(ps, Integer.valueOf(0));
<add> if (useBatchInsert)
<add> {
<add> debug="insertRow executeBatch commit";
<add> ps.executeBatch();
<add> commit();
<add> ps.clearBatch();
<add> }
<add> else
<add> {
<add> debug="insertRow normal commit";
<add> commit();
<add> }
<add> rowsAreSafe=true;
<ide> }
<del> else
<del> {
<del> debug="insertRow normal commit";
<del> commit();
<del> }
<del> rowsAreSafe=true;
<del> }
<del> */
<add> }
<add>
<ide> return rowsAreSafe;
<ide> }
<ide> catch(BatchUpdateException ex) |
|
Java | apache-2.0 | cd96da2485bc7c41c2f3da7c2b5dee99f73d24da | 0 | apache/jmeter,ham1/jmeter,apache/jmeter,benbenw/jmeter,etnetera/jmeter,ham1/jmeter,ham1/jmeter,apache/jmeter,etnetera/jmeter,etnetera/jmeter,apache/jmeter,ham1/jmeter,benbenw/jmeter,etnetera/jmeter,etnetera/jmeter,apache/jmeter,benbenw/jmeter,benbenw/jmeter,ham1/jmeter | /*
* 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.
*
*/
package org.apache.jmeter.report.processor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* The class ListResultData provides a list of results from sample processing.
*
* @since 3.0
*/
public class ListResultData implements ResultData, Iterable<ResultData> {
private List<ResultData> items = new ArrayList<>();
/*
* (non-Javadoc)
*
* @see
* org.apache.jmeter.report.processor.ResultData#accept(org.apache.jmeter
* .report.processor.ResultDataVisitor)
*/
@Override
public <T> T accept(ResultDataVisitor<T> visitor) {
return visitor.visitListResult(this);
}
/**
* Adds the result at the end of the list.
*
* @param result the result
* @return true, if the result is added
*/
public boolean addResult(ResultData result) {
return items.add(result);
}
/**
* Removes the result at the specified index.
*
* @param index the index of the result in the list
* @return the removed result data
*/
public ResultData removeResult(int index) {
return items.remove(index);
}
/**
* Gets the stored item at the specified index.
*
* @param index the index
* @return the result data
*/
public ResultData get(int index) {
return items.get(index);
}
/**
* Gets the size of the list.
*
* @return the size of the list
*/
public int getSize() {
return items.size();
}
/*
* (non-Javadoc)
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<ResultData> iterator() {
return items.iterator();
}
}
| src/core/org/apache/jmeter/report/processor/ListResultData.java | /*
* 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.
*
*/
package org.apache.jmeter.report.processor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* The class ListResultData provides a list of results from sample processing.
*
* @since 3.0
*/
public class ListResultData implements ResultData, Iterable<ResultData> {
/** The items. */
private List<ResultData> items = new ArrayList<>();
/*
* (non-Javadoc)
*
* @see
* org.apache.jmeter.report.processor.ResultData#accept(org.apache.jmeter
* .report.processor.ResultDataVisitor)
*/
@Override
public <T> T accept(ResultDataVisitor<T> visitor) {
return visitor.visitListResult(this);
}
/**
* Adds the result at the end of the list.
*
* @param result
* the result
* @return true, if the result is added
*/
public boolean addResult(ResultData result) {
return items.add(result);
}
/**
* Removes the result at the specified index.
*
* @param index
* the index of the result in the list
* @return the removed result data
*/
public ResultData removeResult(int index) {
return items.remove(index);
}
/**
* Gets the stored item at the specified index.
*
* @param index
* the index
* @return the result data
*/
public ResultData get(int index) {
return items.get(index);
}
/**
* Gets the size of the list.
*
* @return the size of the list
*/
public int getSize() {
return items.size();
}
/*
* (non-Javadoc)
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<ResultData> iterator() {
return items.iterator();
}
}
| Javadoc clean up. Part of #332 Contributed by Graham Russell
git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1816329 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: 35c2c725812e1eef00ade321702651bd1800dda9 | src/core/org/apache/jmeter/report/processor/ListResultData.java | Javadoc clean up. Part of #332 Contributed by Graham Russell | <ide><path>rc/core/org/apache/jmeter/report/processor/ListResultData.java
<ide>
<ide> /**
<ide> * The class ListResultData provides a list of results from sample processing.
<del> *
<add> *
<ide> * @since 3.0
<ide> */
<ide> public class ListResultData implements ResultData, Iterable<ResultData> {
<ide>
<del> /** The items. */
<ide> private List<ResultData> items = new ArrayList<>();
<ide>
<ide> /*
<ide> * (non-Javadoc)
<del> *
<add> *
<ide> * @see
<ide> * org.apache.jmeter.report.processor.ResultData#accept(org.apache.jmeter
<ide> * .report.processor.ResultDataVisitor)
<ide> /**
<ide> * Adds the result at the end of the list.
<ide> *
<del> * @param result
<del> * the result
<add> * @param result the result
<ide> * @return true, if the result is added
<ide> */
<ide> public boolean addResult(ResultData result) {
<ide> /**
<ide> * Removes the result at the specified index.
<ide> *
<del> * @param index
<del> * the index of the result in the list
<add> * @param index the index of the result in the list
<ide> * @return the removed result data
<ide> */
<ide> public ResultData removeResult(int index) {
<ide> /**
<ide> * Gets the stored item at the specified index.
<ide> *
<del> * @param index
<del> * the index
<add> * @param index the index
<ide> * @return the result data
<ide> */
<ide> public ResultData get(int index) {
<ide>
<ide> /*
<ide> * (non-Javadoc)
<del> *
<add> *
<ide> * @see java.lang.Iterable#iterator()
<ide> */
<ide> @Override |
|
JavaScript | mit | 0e24442818130a16d0278fddededff9102f531aa | 0 | linnovate/icu,linnovate/icu,linnovate/icu | 'use strict';
angular.module('mean.icu.ui.tabs')
.directive('icuTabsOfficedocuments', function ($state, $filter, OfficeDocumentsService, PermissionsService) {
function controller($scope) {
$scope.sorting = {
field: 'created',
isReverse: false
};
$scope.officeDocuments = $scope.$parent.$parent.officeDocuments;
$scope.loadNext = $scope.officeDocuments.next;
$scope.loadPrev = $scope.officeDocuments.prev;
$scope.officeDocuments = $scope.officeDocuments.data || $scope.officeDocuments;
OfficeDocumentsService.tabData = $scope.officeDocuments;
$scope.officeDocumentOrder = function(officeDocument) {
if (officeDocument._id && $scope.sorting) {
var parts = $scope.sorting.field.split('.');
var result = officeDocument;
for (var i = 0; i < parts.length; i+=1) {
if (result) {
result = result[parts[i]];
} else {
result = undefined;
}
}
//HACK: instead of using array of 2 values, this code concatenates
//2 values
//Reason: inconsistency in sorting results between sorting by one param
//and array of params
return result + officeDocument.title;
}
};
function sort() {
var result = $filter('orderBy')($scope.officeDocuments, $scope.officeDocumentOrder);
Array.prototype.splice.apply($scope.officeDocuments, [0, $scope.officeDocuments.length].concat(result));
}
sort();
$scope.havePermissions = function(type, enableRecycled) {
enableRecycled = enableRecycled || !$scope.isRecycled;
return (PermissionsService.havePermissions($scope.entity, type) && enableRecycled);
}
$scope.manageOfficeDocuments = function () {
$state.go('main.officeDocuments.byentity.activities', {
entity: $scope.entityName,
id: $scope.entity._id,
entityId: $scope.entity._id
},
{
reload: true
});
};
}
return {
restrict: 'A',
scope: {
officeDocuments: '=',
entityName: '@',
entity: '='
},
controller: controller,
replace: true,
templateUrl: '/icu/components/tabs/officeDocuments/officeDocuments.html'
};
});
| packages/custom/icu/public/components/tabs/officeDocuments/officeDocuments.directive.js | 'use strict';
angular.module('mean.icu.ui.tabs')
.directive('icuTabsOfficedocuments', function ($state, $filter, OfficeDocumentsService) {
function controller($scope) {
$scope.sorting = {
field: 'created',
isReverse: false
};
$scope.officeDocuments = $scope.$parent.$parent.officeDocuments;
$scope.loadNext = $scope.officeDocuments.next;
$scope.loadPrev = $scope.officeDocuments.prev;
$scope.officeDocuments = $scope.officeDocuments.data || $scope.officeDocuments;
OfficeDocumentsService.tabData = $scope.officeDocuments;
$scope.officeDocumentOrder = function(officeDocument) {
if (officeDocument._id && $scope.sorting) {
var parts = $scope.sorting.field.split('.');
var result = officeDocument;
for (var i = 0; i < parts.length; i+=1) {
if (result) {
result = result[parts[i]];
} else {
result = undefined;
}
}
//HACK: instead of using array of 2 values, this code concatenates
//2 values
//Reason: inconsistency in sorting results between sorting by one param
//and array of params
return result + officeDocument.title;
}
};
function sort() {
var result = $filter('orderBy')($scope.officeDocuments, $scope.officeDocumentOrder);
Array.prototype.splice.apply($scope.officeDocuments, [0, $scope.officeDocuments.length].concat(result));
}
sort();
$scope.manageOfficeDocuments = function () {
$state.go('main.officeDocuments.byentity.activities', {
entity: $scope.entityName,
id: $scope.entity._id,
entityId: $scope.entity._id
},
{
reload: true
});
};
}
return {
restrict: 'A',
scope: {
officeDocuments: '=',
entityName: '@',
entity: '='
},
controller: controller,
replace: true,
templateUrl: '/icu/components/tabs/officeDocuments/officeDocuments.html'
};
});
| Fixed #1262
| packages/custom/icu/public/components/tabs/officeDocuments/officeDocuments.directive.js | Fixed #1262 | <ide><path>ackages/custom/icu/public/components/tabs/officeDocuments/officeDocuments.directive.js
<ide> 'use strict';
<ide>
<ide> angular.module('mean.icu.ui.tabs')
<del> .directive('icuTabsOfficedocuments', function ($state, $filter, OfficeDocumentsService) {
<add> .directive('icuTabsOfficedocuments', function ($state, $filter, OfficeDocumentsService, PermissionsService) {
<ide> function controller($scope) {
<ide> $scope.sorting = {
<ide> field: 'created',
<ide>
<ide> sort();
<ide>
<add> $scope.havePermissions = function(type, enableRecycled) {
<add> enableRecycled = enableRecycled || !$scope.isRecycled;
<add> return (PermissionsService.havePermissions($scope.entity, type) && enableRecycled);
<add> }
<add>
<ide> $scope.manageOfficeDocuments = function () {
<ide> $state.go('main.officeDocuments.byentity.activities', {
<ide> entity: $scope.entityName, |
|
Java | apache-2.0 | 6cd9e35ee6ff80f9eb6b08d112f4b6e474747fe2 | 0 | atsolakid/jena,adrapereira/jena,CesarPantoja/jena,CesarPantoja/jena,adrapereira/jena,jianglili007/jena,jianglili007/jena,kidaa/jena,kamir/jena,kamir/jena,CesarPantoja/jena,adrapereira/jena,atsolakid/jena,jianglili007/jena,apache/jena,adrapereira/jena,apache/jena,samaitra/jena,tr3vr/jena,tr3vr/jena,kamir/jena,adrapereira/jena,kidaa/jena,samaitra/jena,atsolakid/jena,tr3vr/jena,atsolakid/jena,CesarPantoja/jena,apache/jena,jianglili007/jena,kidaa/jena,tr3vr/jena,jianglili007/jena,apache/jena,apache/jena,jianglili007/jena,CesarPantoja/jena,samaitra/jena,CesarPantoja/jena,adrapereira/jena,kidaa/jena,atsolakid/jena,samaitra/jena,apache/jena,kamir/jena,kamir/jena,adrapereira/jena,jianglili007/jena,atsolakid/jena,kidaa/jena,samaitra/jena,atsolakid/jena,kidaa/jena,kamir/jena,apache/jena,tr3vr/jena,tr3vr/jena,apache/jena,CesarPantoja/jena,tr3vr/jena,kidaa/jena,kamir/jena,samaitra/jena,samaitra/jena | /*
* 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.
*/
package com.hp.hpl.jena.sparql.expr;
import org.junit.Assert ;
import org.junit.Test ;
import com.hp.hpl.jena.sparql.expr.nodevalue.XSDFuncOp ;
import com.hp.hpl.jena.sparql.function.FunctionEnvBase ;
import com.hp.hpl.jena.sparql.util.ExprUtils ;
/** Break expression testing suite into parts
* @see TestExpressions
* @see TestExprLib
* @see TestNodeValue
*/
public class TestExpressions2 extends Assert
{
@Test public void gregorian_eq_01() { eval("'1999'^^xsd:gYear = '1999'^^xsd:gYear", true) ; }
@Test public void gregorian_eq_02() { eval("'1999'^^xsd:gYear != '1999'^^xsd:gYear", false) ; }
@Test (expected=ExprEvalException.class)
public void gregorian_eq_03() { eval("'1999'^^xsd:gYear = '1999Z'^^xsd:gYear") ; }
@Test public void gregorian_eq_04() { eval("'1999'^^xsd:gYear = '2001Z'^^xsd:gYear", false) ; }
// Different value spaces => different.
@Test public void gregorian_eq_05() { eval("'1999-01'^^xsd:gYearMonth != '2001Z'^^xsd:gYear", true) ; }
@Test public void gregorian_eq_06() { eval("'--01'^^xsd:gMonth != '--01-25'^^xsd:gMonthDay", true) ; }
@Test public void gregorian_eq_07() { eval("'---25'^^xsd:gDay = '---25'^^xsd:gDay", true) ; }
@Test public void gregorian_eq_08() { eval("'1999-01'^^xsd:gYearMonth != '2001Z'^^xsd:gYear", true) ; }
@Test public void gregorian_eq_09() { eval("'1999-01'^^xsd:gYearMonth != '2001Z'^^xsd:gYear", true) ; }
@Test public void gregorian_cmp_01() { eval("'1999'^^xsd:gYear < '2001'^^xsd:gYear", true) ; }
@Test public void gregorian_cmp_02() { eval("'1999'^^xsd:gYear > '2001'^^xsd:gYear", false) ; }
@Test public void gregorian_cmp_03() { eval("'1999'^^xsd:gYear < '2001+01:00'^^xsd:gYear", true) ; }
@Test (expected=ExprEvalException.class)
public void gregorian_cmp_04() { eval("'1999'^^xsd:gYear < '1999+05:00'^^xsd:gYear") ; }
public void gregorian_cast_01() { eval("xsd:gYear('2010-03-22'^^xsd:date) = '2010'^^xsd:gYear", true ) ; }
@Test (expected=ExprEvalException.class)
public void coalesce_01() { eval("COALESCE()") ; }
@Test public void coalesce_02() { eval("COALESCE(1) = 1", true) ; }
@Test public void coalesce_03() { eval("COALESCE(?x,1) = 1", true) ; }
@Test public void coalesce_04() { eval("COALESCE(9,1) = 9", true) ; }
// IF
@Test public void if_01() { eval("IF(1+2=3, 'yes', 'no') = 'yes'", true) ; }
@Test public void if_02() { eval("IF(1+2=4, 'yes', 'no') = 'no'", true) ; }
@Test public void if_03() { eval("IF(true, 'yes', 1/0) = 'yes'", true) ; }
@Test (expected=ExprEvalException.class)
public void if_04() { eval("IF(true, 1/0, 'no') = 'no'") ; }
// NOT IN, IN
@Test public void in_01() { eval("1 IN(1,2,3)", true) ; }
@Test public void in_02() { eval("1 IN(<x>,2,1)", true) ; }
@Test public void in_03() { eval("1 IN()", false) ; }
@Test public void in_04() { eval("1 IN(7)", false) ; }
@Test public void not_in_01() { eval("1 NOT IN(1,2,3)", false) ; }
@Test public void not_in_02() { eval("1 NOT IN(<x>,2,1)", false) ; }
@Test public void not_in_03() { eval("1 NOT IN()", true) ; }
@Test public void not_in_04() { eval("1 NOT IN(7)", true) ; }
// Term constructors
@Test public void term_constructor_iri_01() { eval("IRI('http://example/') = <http://example/>", true) ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_iri_02() { eval("IRI(123)") ; }
@Test public void term_constructor_iri_03() { eval("IRI(<http://example/>) = <http://example/>", true) ; }
@Test public void term_constructor_iri_04() { eval("isIRI(IRI(BNODE()))", true) ; } // SPARQL extension
@Test public void term_constructor_iri_05() { eval("regex(str(IRI(BNODE())), '^_:' )", true) ; } // SPARQL extension
@Test public void term_constructor_bnode_01() { eval("isBlank(BNODE())", true) ; }
@Test public void term_constructor_bnode_02() { eval("isBlank(BNODE('abc'))", true) ; }
@Test public void term_constructor_bnode_03() { eval("isBlank(BNODE('abc'))", true) ; }
@Test public void term_constructor_bnode_04() { eval("BNODE('abc') = BNODE('abc')", true) ; }
@Test public void term_constructor_bnode_05() { eval("BNODE('abc') = BNODE('def')", false) ; }
@Test public void term_constructor_strdt_01() { eval("STRDT('123',xsd:integer) = 123", true) ; }
@Test public void term_constructor_strdt_02() { eval("STRDT('123',<http://example/DT>) = '123'^^<http://example/DT>", true) ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_strdt_03() { eval("STRDT('123','abc') = '123'") ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_strdt_04() { eval("STRDT('123'^^xsd:integer,<http://example/DT>) = '123'^^<http://example/DT>") ; }
@Test public void term_constructor_strlang_01() { eval("STRLANG('abc', 'en') = 'abc'@en", true) ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_strlang_02() { eval("STRLANG(<http://example/>, 'en') = 'abc'@en") ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_strlang_03() { eval("STRLANG('abc'@en, 'en') = 'abc'@en") ; }
// XSD casts
@Test public void xsd_cast_01() { eval("xsd:integer('1') = 1", true) ; }
@Test public void xsd_cast_02() { eval("xsd:boolean('1') = true", true) ; }
@Test public void xsd_cast_03() { eval("sameTerm(xsd:double('1.0e0'),1.0e0)", true) ; }
@Test public void xsd_cast_04() { eval("xsd:double('1') = 1", true) ; }
@Test (expected=ExprEvalException.class)
public void xsd_cast_10() { eval("xsd:integer(' 1')") ; }
@Test (expected=ExprEvalException.class)
public void xsd_cast_11() { eval("xsd:boolean(' 1')") ; }
@Test (expected=ExprEvalException.class)
public void xsd_cast_12() { eval("xsd:double(' 1.0e0')") ; }
@Test (expected=ExprEvalException.class)
public void xsd_cast_13() { eval("xsd:double(' 1.0e0')") ; }
// Dynamic Function Calls
@Test public void dynamic_call_01() { eval("CALL()", false); }
@Test public void dynamic_call_02() { eval("CALL(xsd:double, '1') = 1") ; }
@Test public void dynamic_call_03() { eval("CALL(fn:concat, 'A', 2+3 ) = 'A5'") ; }
@Test (expected=ExprEvalException.class)
public void dynamic_call_10() { eval("CALL(xsd:double)") ; }
@Test (expected=ExprEvalException.class)
public void dynamic_call_11() { eval("CALL(xsd:noSuchFunc)") ; }
// ---- Workers
private static void eval(String string)
{
eval(string, true) ;
}
// It's easier to write tests that simple are expected to return true/false
private static void eval(String string, boolean result)
{
Expr expr = ExprUtils.parse(string) ;
NodeValue nv = expr.eval(null, FunctionEnvBase.createTest()) ;
boolean b = XSDFuncOp.booleanEffectiveValue(nv) ;
assertEquals(string, result, b) ;
}
}
| jena-arq/src/test/java/com/hp/hpl/jena/sparql/expr/TestExpressions2.java | /*
* 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.
*/
package com.hp.hpl.jena.sparql.expr;
import org.junit.Assert ;
import org.junit.Test ;
import com.hp.hpl.jena.sparql.expr.nodevalue.XSDFuncOp ;
import com.hp.hpl.jena.sparql.function.FunctionEnvBase ;
import com.hp.hpl.jena.sparql.util.ExprUtils ;
/** Break expression testing suite into parts
* @see TestExpressions
* @see TestExprLib
* @see TestNodeValue
*/
public class TestExpressions2 extends Assert
{
@Test public void gregorian_eq_01() { eval("'1999'^^xsd:gYear = '1999'^^xsd:gYear", true) ; }
@Test public void gregorian_eq_02() { eval("'1999'^^xsd:gYear != '1999'^^xsd:gYear", false) ; }
@Test (expected=ExprEvalException.class)
public void gregorian_eq_03() { eval("'1999'^^xsd:gYear = '1999Z'^^xsd:gYear") ; }
@Test public void gregorian_eq_04() { eval("'1999'^^xsd:gYear = '2001Z'^^xsd:gYear", false) ; }
// Different value spaces => different.
@Test public void gregorian_eq_05() { eval("'1999-01'^^xsd:gYearMonth != '2001Z'^^xsd:gYear", true) ; }
@Test public void gregorian_eq_06() { eval("'--01'^^xsd:gMonth != '--01-25'^^xsd:gMonthDay", true) ; }
@Test public void gregorian_eq_07() { eval("'---25'^^xsd:gDay = '---25'^^xsd:gDay", true) ; }
@Test public void gregorian_eq_08() { eval("'1999-01'^^xsd:gYearMonth != '2001Z'^^xsd:gYear", true) ; }
@Test public void gregorian_eq_09() { eval("'1999-01'^^xsd:gYearMonth != '2001Z'^^xsd:gYear", true) ; }
@Test public void gregorian_cmp_01() { eval("'1999'^^xsd:gYear < '2001'^^xsd:gYear", true) ; }
@Test public void gregorian_cmp_02() { eval("'1999'^^xsd:gYear > '2001'^^xsd:gYear", false) ; }
@Test public void gregorian_cmp_03() { eval("'1999'^^xsd:gYear < '2001+01:00'^^xsd:gYear", true) ; }
@Test (expected=ExprEvalException.class)
public void gregorian_cmp_04() { eval("'1999'^^xsd:gYear < '1999+05:00'^^xsd:gYear") ; }
public void gregorian_cast_01() { eval("xsd:gYear('2010-03-22'^^xsd:date) = '2010'^^xsd:gYear", true ) ; }
@Test (expected=ExprEvalException.class)
public void coalesce_01() { eval("COALESCE()") ; }
@Test public void coalesce_02() { eval("COALESCE(1) = 1", true) ; }
@Test public void coalesce_03() { eval("COALESCE(?x,1) = 1", true) ; }
@Test public void coalesce_04() { eval("COALESCE(9,1) = 9", true) ; }
// IF
@Test public void if_01() { eval("IF(1+2=3, 'yes', 'no') = 'yes'", true) ; }
@Test public void if_02() { eval("IF(1+2=4, 'yes', 'no') = 'no'", true) ; }
@Test public void if_03() { eval("IF(true, 'yes', 1/0) = 'yes'", true) ; }
@Test (expected=ExprEvalException.class)
public void if_04() { eval("IF(true, 1/0, 'no') = 'no'") ; }
// NOT IN, IN
@Test public void in_01() { eval("1 IN(1,2,3)", true) ; }
@Test public void in_02() { eval("1 IN(<x>,2,1)", true) ; }
@Test public void in_03() { eval("1 IN()", false) ; }
@Test public void in_04() { eval("1 IN(7)", false) ; }
@Test public void not_in_01() { eval("1 NOT IN(1,2,3)", false) ; }
@Test public void not_in_02() { eval("1 NOT IN(<x>,2,1)", false) ; }
@Test public void not_in_03() { eval("1 NOT IN()", true) ; }
@Test public void not_in_04() { eval("1 NOT IN(7)", true) ; }
// Term constructors
@Test public void term_constructor_iri_01() { eval("IRI('http://example/') = <http://example/>", true) ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_iri_02() { eval("IRI(123)") ; }
@Test public void term_constructor_iri_03() { eval("IRI(<http://example/>) = <http://example/>", true) ; }
@Test public void term_constructor_iri_04() { eval("isIRI(IRI(BNODE()))", true) ; } // SPARQL extension
@Test public void term_constructor_iri_05() { eval("regex(str(IRI(BNODE())), '^_:' )", true) ; } // SPARQL extension
@Test public void term_constructor_bnode_01() { eval("isBlank(BNODE())", true) ; }
@Test public void term_constructor_bnode_02() { eval("isBlank(BNODE('abc'))", true) ; }
@Test public void term_constructor_bnode_03() { eval("isBlank(BNODE('abc'))", true) ; }
@Test public void term_constructor_bnode_04() { eval("BNODE('abc') = BNODE('abc')", true) ; }
@Test public void term_constructor_bnode_05() { eval("BNODE('abc') = BNODE('def')", false) ; }
@Test public void term_constructor_strdt_01() { eval("STRDT('123',xsd:integer) = 123", true) ; }
@Test public void term_constructor_strdt_02() { eval("STRDT('123',<http://example/DT>) = '123'^^<http://example/DT>", true) ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_strdt_03() { eval("STRDT('123','abc') = '123'") ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_strdt_04() { eval("STRDT('123'^^xsd:integer,<http://example/DT>) = '123'^^<http://example/DT>") ; }
@Test public void term_constructor_strlang_01() { eval("STRLANG('abc', 'en') = 'abc'@en", true) ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_strlang_02() { eval("STRLANG(<http://example/>, 'en') = 'abc'@en") ; }
@Test (expected=ExprEvalException.class)
public void term_constructor_strlang_03() { eval("STRLANG('abc'@en, 'en') = 'abc'@en") ; }
// XSD casts
@Test public void xsd_cast_01() { eval("xsd:integer('1') = 1", true) ; }
@Test public void xsd_cast_02() { eval("xsd:boolean('1') = true", true) ; }
@Test public void xsd_cast_03() { eval("sameTerm(xsd:double('1.0e0'),1.0e0)", true) ; }
@Test public void xsd_cast_04() { eval("xsd:double('1') = 1", true) ; }
@Test (expected=ExprEvalException.class)
public void xsd_cast_10() { eval("xsd:integer(' 1')") ; }
@Test (expected=ExprEvalException.class)
public void xsd_cast_11() { eval("xsd:boolean(' 1')") ; }
@Test (expected=ExprEvalException.class)
public void xsd_cast_12() { eval("xsd:double(' 1.0e0')") ; }
@Test (expected=ExprEvalException.class)
public void xsd_cast_13() { eval("xsd:double(' 1.0e0')") ; }
// Dynamic Function Calls
@Test (expected=ExprEvalException.class)
public void dynamic_call_01() { eval("CALL()", false); }
@Test public void dynamic_call_02() { eval("CALL(xsd:double, '1') = 1") ; }
@Test (expected=ExprEvalException.class)
public void dynamic_call_03() { eval("CALL(xsd:double)") ; }
@Test (expected=ExprEvalException.class)
public void dynamic_call_04() { eval("CALL(xsd:noSuchFunc)") ; }
// ---- Workers
private static void eval(String string)
{
eval(string, true) ;
}
// It's easier to write tests that simple are expected to return true/false
private static void eval(String string, boolean result)
{
Expr expr = ExprUtils.parse(string) ;
NodeValue nv = expr.eval(null, FunctionEnvBase.createTest()) ;
boolean b = XSDFuncOp.booleanEffectiveValue(nv) ;
assertEquals(string, result, b) ;
}
}
| CALL tests: multi arguments, expressions as arguments.
git-svn-id: bc509ec38c1227b3e85ea1246fda136342965d36@1353721 13f79535-47bb-0310-9956-ffa450edef68
| jena-arq/src/test/java/com/hp/hpl/jena/sparql/expr/TestExpressions2.java | CALL tests: multi arguments, expressions as arguments. | <ide><path>ena-arq/src/test/java/com/hp/hpl/jena/sparql/expr/TestExpressions2.java
<ide> public void xsd_cast_13() { eval("xsd:double(' 1.0e0')") ; }
<ide>
<ide> // Dynamic Function Calls
<add> @Test public void dynamic_call_01() { eval("CALL()", false); }
<add> @Test public void dynamic_call_02() { eval("CALL(xsd:double, '1') = 1") ; }
<add> @Test public void dynamic_call_03() { eval("CALL(fn:concat, 'A', 2+3 ) = 'A5'") ; }
<add>
<ide> @Test (expected=ExprEvalException.class)
<del> public void dynamic_call_01() { eval("CALL()", false); }
<del> @Test public void dynamic_call_02() { eval("CALL(xsd:double, '1') = 1") ; }
<add> public void dynamic_call_10() { eval("CALL(xsd:double)") ; }
<ide> @Test (expected=ExprEvalException.class)
<del> public void dynamic_call_03() { eval("CALL(xsd:double)") ; }
<del> @Test (expected=ExprEvalException.class)
<del> public void dynamic_call_04() { eval("CALL(xsd:noSuchFunc)") ; }
<add> public void dynamic_call_11() { eval("CALL(xsd:noSuchFunc)") ; }
<ide>
<ide> // ---- Workers
<ide> |
|
Java | apache-2.0 | a50a70f68e6779966dd4e4293d7667d9c3423b43 | 0 | lime-company/lime-security-powerauth-webauth,lime-company/lime-security-powerauth-webauth,lime-company/lime-security-powerauth-webauth,lime-company/powerauth-webflow,lime-company/powerauth-webflow,lime-company/powerauth-webflow | /*
* Copyright 2019 Wultra s.r.o.
*
* 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.
*/
package io.getlime.security.powerauth.lib.dataadapter.model.request;
import io.getlime.security.powerauth.lib.dataadapter.model.entity.OperationContext;
import io.getlime.security.powerauth.lib.dataadapter.model.enumeration.AuthInstrument;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Request for an anti-fraud system call.
*
* @author Roman Strobl, [email protected]
*/
public class AfsRequest {
/**
* User ID for this request, use null value before user is authenticated.
*/
private String userId;
/**
* Organization ID for this request.
*/
private String organizationId;
/**
* Operation context.
*/
private OperationContext operationContext;
/**
* Request parameters for anti-fraud system.
*/
private AfsRequestParameters afsRequestParameters;
/**
* Authentication instruments used during this authentication step.
*/
private final List<AuthInstrument> authInstruments = new ArrayList<>();
/**
* Extra parameters sent with the request depending on AFS type, e.g. cookies for Threat Mark.
*/
private final Map<String, Object> extras = new LinkedHashMap<>();
/**
* Default constructor.
*/
public AfsRequest() {
}
/**
* Constructor with all details.
* @param userId User ID.
* @param organizationId Organization ID.
* @param operationContext Operation context.
* @param afsRequestParameters Request parameters for AFS.
* @param authInstruments Authentication instruments used during this authentication step.
* @param extras Extra parameters for AFS.
*/
public AfsRequest(String userId, String organizationId, OperationContext operationContext, AfsRequestParameters afsRequestParameters, List<AuthInstrument> authInstruments, Map<String, Object> extras) {
this.userId = userId;
this.organizationId = organizationId;
this.operationContext = operationContext;
this.afsRequestParameters = afsRequestParameters;
this.authInstruments.addAll(authInstruments);
this.extras.putAll(extras);
}
/**
* Get user ID.
* @return User ID.
*/
public String getUserId() {
return userId;
}
/**
* Set user ID.
* @param userId user ID.
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Get organization ID.
* @return Organization ID.
*/
public String getOrganizationId() {
return organizationId;
}
/**
* Set organization ID.
* @param organizationId Organization ID.
*/
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId;
}
/**
* Get operation context.
* @return Operation context.
*/
public OperationContext getOperationContext() {
return operationContext;
}
/**
* Set operation context.
* @param operationContext Operation context.
*/
public void setOperationContext(OperationContext operationContext) {
this.operationContext = operationContext;
}
/**
* Get request parameters for anti-fraud system.
* @return Request parameters for anti-fraud system.
*/
public AfsRequestParameters getAfsRequestParameters() {
return afsRequestParameters;
}
/**
* Set request parameters for anti-fraud system.
* @param afsRequestParameters Request parameters for anti-fraud system.
*/
public void setAfsRequestParameters(AfsRequestParameters afsRequestParameters) {
this.afsRequestParameters = afsRequestParameters;
}
/**
* Get authentication authentication instruments used during this step.
* @return Authentication authentication instruments used during this step.
*/
public List<AuthInstrument> getAuthInstruments() {
return authInstruments;
}
/**
* Extra parameters sent with the request depending on AFS type, e.g. cookies for Threat Mark.
* @return Get extra parameters for AFS.
*/
public Map<String, Object> getExtras() {
return extras;
}
}
| powerauth-data-adapter-model/src/main/java/io/getlime/security/powerauth/lib/dataadapter/model/request/AfsRequest.java | /*
* Copyright 2019 Wultra s.r.o.
*
* 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.
*/
package io.getlime.security.powerauth.lib.dataadapter.model.request;
import io.getlime.security.powerauth.lib.dataadapter.model.entity.OperationContext;
import io.getlime.security.powerauth.lib.dataadapter.model.enumeration.AuthInstrument;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Request for an anti-fraud system call.
*
* @author Roman Strobl, [email protected]
*/
public class AfsRequest {
/**
* User ID for this request, use null value before user is authenticated.
*/
private String userId;
/**
* Organization ID for this request.
*/
private String organizationId;
/**
* Operation context which provides context for creating the consent form.
*/
private OperationContext operationContext;
/**
* Request parameters for anti-fraud system.
*/
private AfsRequestParameters afsRequestParameters;
/**
* Authentication instruments used during this authentication step.
*/
private final List<AuthInstrument> authInstruments = new ArrayList<>();
/**
* Extra parameters sent with the request depending on AFS type, e.g. cookies for Threat Mark.
*/
private final Map<String, Object> extras = new LinkedHashMap<>();
/**
* Default constructor.
*/
public AfsRequest() {
}
/**
* Constructor with all details.
* @param userId User ID.
* @param organizationId Organization ID.
* @param operationContext Operation context which provides context for creating the consent form.
* @param afsRequestParameters Request parameters for AFS.
* @param authInstruments Authentication instruments used during this authentication step.
* @param extras Extra parameters for AFS.
*/
public AfsRequest(String userId, String organizationId, OperationContext operationContext, AfsRequestParameters afsRequestParameters, List<AuthInstrument> authInstruments, Map<String, Object> extras) {
this.userId = userId;
this.organizationId = organizationId;
this.operationContext = operationContext;
this.afsRequestParameters = afsRequestParameters;
this.authInstruments.addAll(authInstruments);
this.extras.putAll(extras);
}
/**
* Get user ID.
* @return User ID.
*/
public String getUserId() {
return userId;
}
/**
* Set user ID.
* @param userId user ID.
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Get organization ID.
* @return Organization ID.
*/
public String getOrganizationId() {
return organizationId;
}
/**
* Set organization ID.
* @param organizationId Organization ID.
*/
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId;
}
/**
* Get operation context which provides context for creating the consent form.
* @return Operation context which provides context for creating the consent form.
*/
public OperationContext getOperationContext() {
return operationContext;
}
/**
* Set operation context which provides context for creating the consent form.
* @param operationContext Operation context which provides context for creating the consent form.
*/
public void setOperationContext(OperationContext operationContext) {
this.operationContext = operationContext;
}
/**
* Get request parameters for anti-fraud system.
* @return Request parameters for anti-fraud system.
*/
public AfsRequestParameters getAfsRequestParameters() {
return afsRequestParameters;
}
/**
* Set request parameters for anti-fraud system.
* @param afsRequestParameters Request parameters for anti-fraud system.
*/
public void setAfsRequestParameters(AfsRequestParameters afsRequestParameters) {
this.afsRequestParameters = afsRequestParameters;
}
/**
* Get authentication authentication instruments used during this step.
* @return Authentication authentication instruments used during this step.
*/
public List<AuthInstrument> getAuthInstruments() {
return authInstruments;
}
/**
* Extra parameters sent with the request depending on AFS type, e.g. cookies for Threat Mark.
* @return Get extra parameters for AFS.
*/
public Map<String, Object> getExtras() {
return extras;
}
}
| Fix copy-and-paste errors.
| powerauth-data-adapter-model/src/main/java/io/getlime/security/powerauth/lib/dataadapter/model/request/AfsRequest.java | Fix copy-and-paste errors. | <ide><path>owerauth-data-adapter-model/src/main/java/io/getlime/security/powerauth/lib/dataadapter/model/request/AfsRequest.java
<ide> private String organizationId;
<ide>
<ide> /**
<del> * Operation context which provides context for creating the consent form.
<add> * Operation context.
<ide> */
<ide> private OperationContext operationContext;
<ide>
<ide> * Constructor with all details.
<ide> * @param userId User ID.
<ide> * @param organizationId Organization ID.
<del> * @param operationContext Operation context which provides context for creating the consent form.
<add> * @param operationContext Operation context.
<ide> * @param afsRequestParameters Request parameters for AFS.
<ide> * @param authInstruments Authentication instruments used during this authentication step.
<ide> * @param extras Extra parameters for AFS.
<ide> }
<ide>
<ide> /**
<del> * Get operation context which provides context for creating the consent form.
<del> * @return Operation context which provides context for creating the consent form.
<add> * Get operation context.
<add> * @return Operation context.
<ide> */
<ide> public OperationContext getOperationContext() {
<ide> return operationContext;
<ide> }
<ide>
<ide> /**
<del> * Set operation context which provides context for creating the consent form.
<del> * @param operationContext Operation context which provides context for creating the consent form.
<add> * Set operation context.
<add> * @param operationContext Operation context.
<ide> */
<ide> public void setOperationContext(OperationContext operationContext) {
<ide> this.operationContext = operationContext; |
|
Java | epl-1.0 | 60381453a11d1f84a2209285dc7807fd3693daeb | 0 | girba/jdt2famix,girba/jdt2famix | package org.moosetechnology.jdt2famix;
import jniport.SmalltalkRequest;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration;
import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.EnumDeclaration;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.TypeDeclaration;
public class AstVisitor extends ASTVisitor {
public AstVisitor() {
}
////////PACKAGES
public static String visitCompilationUnitCallback = AstVisitor.class.getName() + "visit(CompilationUnit)";
@Override
public boolean visit(CompilationUnit node) {
try {
new SmalltalkRequest(visitCompilationUnitCallback, this, node.getPackage()).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
/**
* Needed for keeping track of the current container
*/
public static String endVisitCompilationUnitCallback = AstVisitor.class.getName() + "endVisit(CompilationUnit)";
@Override
public void endVisit(CompilationUnit node) {
try {
new SmalltalkRequest(endVisitCompilationUnitCallback, this, node.getPackage()).value();
} catch (Throwable e) {
e.printStackTrace();
}
}
////////TYPES
public static String visitTypeDeclarationCallback = AstVisitor.class.getName() + "visit(TypeDeclaration)";
@Override
public boolean visit(TypeDeclaration node) {
try {
new SmalltalkRequest(visitTypeDeclarationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
/**
* Needed for keeping track of the current container
*/
public static String endVisitTypeDeclarationCallback = AstVisitor.class.getName() + "endVisit(TypeDeclaration)";
@Override
public void endVisit(TypeDeclaration node) {
try {
new SmalltalkRequest(endVisitTypeDeclarationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override
public boolean visit(AnonymousClassDeclaration node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(AnonymousClassDeclaration node) {
// TODO Auto-generated method stub
super.endVisit(node);
}
@Override
public boolean visit(EnumDeclaration node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(EnumDeclaration node) {
// TODO Auto-generated method stub
super.endVisit(node);
}
////////ANNOTATIONS
@Override
public boolean visit(AnnotationTypeDeclaration node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(AnnotationTypeDeclaration node) {
// TODO Auto-generated method stub
super.endVisit(node);
}
@Override
public boolean visit(AnnotationTypeMemberDeclaration node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(AnnotationTypeMemberDeclaration node) {
// TODO Auto-generated method stub
super.endVisit(node);
}
////////METHODS
public static String visitMethodDeclarationCallback = AstVisitor.class.getName() + "visit(MethodDeclaration)";
@Override
public boolean visit(MethodDeclaration node) {
try {
new SmalltalkRequest(visitMethodDeclarationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
/**
* Needed for keeping track of the current container
*/
public static String endVisitMethodDeclarationCallback = AstVisitor.class.getName() + "endVisit(MethodDeclaration)";
@Override
public void endVisit(MethodDeclaration node) {
try {
new SmalltalkRequest(endVisitMethodDeclarationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
}
////////INVOCATIONS
public static String visitMethodInvocationCallback = AstVisitor.class.getName() + "visit(MethodInvocation)";
@Override
public boolean visit(MethodInvocation node) {
try {
new SmalltalkRequest(visitMethodInvocationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
@Override
public void endVisit(MethodInvocation node) {
//Not needed
}
public static String visitSuperMethodInvocationCallback = AstVisitor.class.getName() + "visit(SuperMethodInvocation)";
@Override
public boolean visit(SuperMethodInvocation node) {
try {
new SmalltalkRequest(visitSuperMethodInvocationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
@Override
public void endVisit(SuperMethodInvocation node) {
}
@Override
public boolean visit(ConstructorInvocation node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(ConstructorInvocation node) {
}
}
| src/main/java/org/moosetechnology/jdt2famix/AstVisitor.java | package org.moosetechnology.jdt2famix;
import jniport.SmalltalkRequest;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration;
import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.EnumDeclaration;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.TypeDeclaration;
public class AstVisitor extends ASTVisitor {
public AstVisitor() {
}
////////PACKAGES
public static String visitCompilationUnitCallback = AstVisitor.class.getName() + "visit(CompilationUnit)";
@Override
public boolean visit(CompilationUnit node) {
try {
new SmalltalkRequest(visitCompilationUnitCallback, this, node.getPackage()).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
/**
* Needed for keeping track of the current container
*/
public static String endVisitCompilationUnitCallback = AstVisitor.class.getName() + "endVisit(CompilationUnit)";
@Override
public void endVisit(CompilationUnit node) {
try {
new SmalltalkRequest(endVisitCompilationUnitCallback, this, node.getPackage()).value();
} catch (Throwable e) {
e.printStackTrace();
}
}
////////TYPES
public static String visitTypeDeclarationCallback = AstVisitor.class.getName() + "visit(TypeDeclaration)";
@Override
public boolean visit(TypeDeclaration node) {
try {
new SmalltalkRequest(visitTypeDeclarationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
/**
* Needed for keeping track of the current container
*/
public static String endVisitTypeDeclarationCallback = AstVisitor.class.getName() + "endVisit(TypeDeclaration)";
@Override
public void endVisit(TypeDeclaration node) {
try {
new SmalltalkRequest(endVisitTypeDeclarationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Override
public boolean visit(AnonymousClassDeclaration node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(AnonymousClassDeclaration node) {
// TODO Auto-generated method stub
super.endVisit(node);
}
@Override
public boolean visit(EnumDeclaration node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(EnumDeclaration node) {
// TODO Auto-generated method stub
super.endVisit(node);
}
////////ANNOTATIONS
@Override
public boolean visit(AnnotationTypeDeclaration node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(AnnotationTypeDeclaration node) {
// TODO Auto-generated method stub
super.endVisit(node);
}
@Override
public boolean visit(AnnotationTypeMemberDeclaration node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(AnnotationTypeMemberDeclaration node) {
// TODO Auto-generated method stub
super.endVisit(node);
}
////////METHODS
public static String visitMethodDeclarationCallback = AstVisitor.class.getName() + "visit(MethodDeclaration)";
@Override
public boolean visit(MethodDeclaration node) {
try {
new SmalltalkRequest(visitMethodDeclarationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
/**
* Needed for keeping track of the current container
*/
public static String endVisitMethodDeclarationCallback = AstVisitor.class.getName() + "endVisit(MethodDeclaration)";
@Override
public void endVisit(MethodDeclaration node) {
try {
new SmalltalkRequest(endVisitMethodDeclarationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
}
////////INVOCATIONS
public static String visitMethodInvocationCallback = AstVisitor.class.getName() + "visit(MethodInvocation)";
@Override
public boolean visit(MethodInvocation node) {
try {
new SmalltalkRequest(visitMethodInvocationCallback, this, node).value();
} catch (Throwable e) {
e.printStackTrace();
}
return super.visit(node);
}
@Override
public void endVisit(MethodInvocation node) {
//Not needed
}
@Override
public boolean visit(SuperMethodInvocation node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(SuperMethodInvocation node) {
}
@Override
public boolean visit(ConstructorInvocation node) {
// TODO Auto-generated method stub
return super.visit(node);
}
@Override
public void endVisit(ConstructorInvocation node) {
}
}
| super method invocation
| src/main/java/org/moosetechnology/jdt2famix/AstVisitor.java | super method invocation | <ide><path>rc/main/java/org/moosetechnology/jdt2famix/AstVisitor.java
<ide> //Not needed
<ide> }
<ide>
<add> public static String visitSuperMethodInvocationCallback = AstVisitor.class.getName() + "visit(SuperMethodInvocation)";
<ide> @Override
<ide> public boolean visit(SuperMethodInvocation node) {
<del> // TODO Auto-generated method stub
<add> try {
<add> new SmalltalkRequest(visitSuperMethodInvocationCallback, this, node).value();
<add> } catch (Throwable e) {
<add> e.printStackTrace();
<add> }
<ide> return super.visit(node);
<ide> }
<ide> |
|
JavaScript | lgpl-2.1 | e1162490ee7843d1efbbe1d8be4e3035b1cca93f | 0 | Cyperghost/WCF,WoltLab/WCF,WoltLab/WCF,Cyperghost/WCF,SoftCreatR/WCF,MenesesEvandro/WCF,0xLeon/WCF,Morik/WCF,WoltLab/WCF,Cyperghost/WCF,SoftCreatR/WCF,joshuaruesweg/WCF,Morik/WCF,joshuaruesweg/WCF,SoftCreatR/WCF,Morik/WCF,SoftCreatR/WCF,0xLeon/WCF,Cyperghost/WCF,joshuaruesweg/WCF,0xLeon/WCF,Morik/WCF,WoltLab/WCF,MenesesEvandro/WCF,Cyperghost/WCF | "use strict";
/**
* Class and function collection for WCF.
*
* Major Contributors: Markus Bartz, Tim Duesterhus, Matthias Schmidt and Marcel Werk
*
* @author Alexander Ebert
* @copyright 2001-2015 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
*/
(function() {
// store original implementation
var $jQueryData = jQuery.fn.data;
/**
* Override jQuery.fn.data() to support custom 'ID' suffix which will
* be translated to '-id' at runtime.
*
* @see jQuery.fn.data()
*/
jQuery.fn.data = function(key, value) {
if (key) {
switch (typeof key) {
case 'object':
for (var $key in key) {
if ($key.match(/ID$/)) {
var $value = key[$key];
delete key[$key];
$key = $key.replace(/ID$/, '-id');
key[$key] = $value;
}
}
arguments[0] = key;
break;
case 'string':
if (key.match(/ID$/)) {
arguments[0] = key.replace(/ID$/, '-id');
}
break;
}
}
// call jQuery's own data method
var $data = $jQueryData.apply(this, arguments);
// handle .data() call without arguments
if (key === undefined) {
for (var $key in $data) {
if ($key.match(/Id$/)) {
$data[$key.replace(/Id$/, 'ID')] = $data[$key];
delete $data[$key];
}
}
}
return $data;
};
// provide a sane window.console implementation
if (!window.console) window.console = { };
var consoleProperties = [ "log",/* "debug",*/ "info", "warn", "exception", "assert", "dir", "dirxml", "trace", "group", "groupEnd", "groupCollapsed", "profile", "profileEnd", "count", "clear", "time", "timeEnd", "timeStamp", "table", "error" ];
for (var i = 0; i < consoleProperties.length; i++) {
if (typeof (console[consoleProperties[i]]) === 'undefined') {
console[consoleProperties[i]] = function () { };
}
}
if (typeof(console.debug) === 'undefined') {
// forward console.debug to console.log (IE9)
console.debug = function(string) { console.log(string); };
}
})();
/**
* Provides a hashCode() method for strings, similar to Java's String.hashCode().
*
* @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
*/
String.prototype.hashCode = function() {
var $char;
var $hash = 0;
if (this.length) {
for (var $i = 0, $length = this.length; $i < $length; $i++) {
$char = this.charCodeAt($i);
$hash = (($hash << 5) - $hash) + $char;
$hash = $hash & $hash; // convert to 32bit integer
}
}
return $hash;
};
/**
* Adds a Fisher-Yates shuffle algorithm for arrays.
*
* @see http://stackoverflow.com/a/2450976
*/
window.shuffle = function(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return this;
};
/**
* User-Agent based browser detection and touch detection.
*/
(function(jQuery) {
var ua = navigator.userAgent.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
var matched = {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
var browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = jQuery.browser || { };
jQuery.browser = $.extend(jQuery.browser, browser);
jQuery.browser.touch = (!!('ontouchstart' in window) || (!!('msMaxTouchPoints' in window.navigator) && window.navigator.msMaxTouchPoints > 0));
// detect smartphones
jQuery.browser.smartphone = ($('html').css('caption-side') == 'bottom');
// properly detect IE11
if (jQuery.browser.mozilla && ua.match(/trident/)) {
jQuery.browser.mozilla = false;
jQuery.browser.msie = true;
}
// detect iOS devices
jQuery.browser.iOS = /\((ipad|iphone|ipod);/.test(ua);
if (jQuery.browser.iOS) {
$('html').addClass('iOS');
}
// dectect Android
jQuery.browser.android = (ua.indexOf('android') !== -1);
// allow plugins to detect the used editor, value should be the same as the $.browser.<editorName> key
jQuery.browser.editor = 'redactor';
// CKEditor support (removed in WCF 2.1), do NOT remove this variable for the sake for compatibility
jQuery.browser.ckeditor = false;
// Redactor support
jQuery.browser.redactor = true;
// work-around for zoom bug on iOS when using .focus()
if (jQuery.browser.iOS) {
jQuery.fn.focus = function(data, fn) {
return arguments.length > 0 ? this.on('focus', null, data, fn) : this.trigger('focus');
};
}
})(jQuery);
/**
* Initialize WCF namespace
*/
// non strict equals by intent
if (window.WCF == null) window.WCF = { };
/**
* Extends jQuery with additional methods.
*/
$.extend(true, {
/**
* Removes the given value from the given array and returns the array.
*
* @param array array
* @param mixed element
* @return array
*/
removeArrayValue: function(array, value) {
return $.grep(array, function(element, index) {
return value !== element;
});
},
/**
* Escapes an ID to work with jQuery selectors.
*
* @see http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_element_by_an_ID_that_has_characters_used_in_CSS_notation.3F
* @param string id
* @return string
*/
wcfEscapeID: function(id) {
return id.replace(/(:|\.)/g, '\\$1');
},
/**
* Returns true if given ID exists within DOM.
*
* @param string id
* @return boolean
*/
wcfIsset: function(id) {
return !!$('#' + $.wcfEscapeID(id)).length;
},
/**
* Returns the length of an object.
*
* @param object targetObject
* @return integer
*/
getLength: function(targetObject) {
var $length = 0;
for (var $key in targetObject) {
if (targetObject.hasOwnProperty($key)) {
$length++;
}
}
return $length;
}
});
/**
* Extends jQuery's chainable methods.
*/
$.fn.extend({
/**
* Returns tag name of first jQuery element.
*
* @returns string
*/
getTagName: function() {
return (this.length) ? this.get(0).tagName.toLowerCase() : '';
},
/**
* Returns the dimensions for current element.
*
* @see http://api.jquery.com/hidden-selector/
* @param string type
* @return object
*/
getDimensions: function(type) {
var css = { };
var dimensions = { };
var wasHidden = false;
// show element to retrieve dimensions and restore them later
if (this.is(':hidden')) {
css = WCF.getInlineCSS(this);
wasHidden = true;
this.css({
display: 'block',
visibility: 'hidden'
});
}
switch (type) {
case 'inner':
dimensions = {
height: this.innerHeight(),
width: this.innerWidth()
};
break;
case 'outer':
dimensions = {
height: this.outerHeight(),
width: this.outerWidth()
};
break;
default:
dimensions = {
height: this.height(),
width: this.width()
};
break;
}
// restore previous settings
if (wasHidden) {
WCF.revertInlineCSS(this, css, [ 'display', 'visibility' ]);
}
return dimensions;
},
/**
* Returns the offsets for current element, defaults to position
* relative to document.
*
* @see http://api.jquery.com/hidden-selector/
* @param string type
* @return object
*/
getOffsets: function(type) {
var css = { };
var offsets = { };
var wasHidden = false;
// show element to retrieve dimensions and restore them later
if (this.is(':hidden')) {
css = WCF.getInlineCSS(this);
wasHidden = true;
this.css({
display: 'block',
visibility: 'hidden'
});
}
switch (type) {
case 'offset':
offsets = this.offset();
break;
case 'position':
default:
offsets = this.position();
break;
}
// restore previous settings
if (wasHidden) {
WCF.revertInlineCSS(this, css, [ 'display', 'visibility' ]);
}
return offsets;
},
/**
* Changes element's position to 'absolute' or 'fixed' while maintaining it's
* current position relative to viewport. Optionally removes element from
* current DOM-node and moving it into body-element (useful for drag & drop)
*
* @param boolean rebase
* @return object
*/
makePositioned: function(position, rebase) {
if (position != 'absolute' && position != 'fixed') {
position = 'absolute';
}
var $currentPosition = this.getOffsets('position');
this.css({
position: position,
left: $currentPosition.left,
margin: 0,
top: $currentPosition.top
});
if (rebase) {
this.remove().appentTo('body');
}
return this;
},
/**
* Disables a form element.
*
* @return jQuery
*/
disable: function() {
return this.attr('disabled', 'disabled');
},
/**
* Enables a form element.
*
* @return jQuery
*/
enable: function() {
return this.removeAttr('disabled');
},
/**
* Returns the element's id. If none is set, a random unique
* ID will be assigned.
*
* @return string
*/
wcfIdentify: function() {
return window.bc_wcfDomUtil.identify(this[0]);
},
/**
* Returns the caret position of current element. If the element
* does not equal input[type=text], input[type=password] or
* textarea, -1 is returned.
*
* @return integer
*/
getCaret: function() {
if (this.is('input')) {
if (this.attr('type') != 'text' && this.attr('type') != 'password') {
return -1;
}
}
else if (!this.is('textarea')) {
return -1;
}
var $position = 0;
var $element = this.get(0);
if (document.selection) { // IE 8
// set focus to enable caret on this element
this.focus();
var $selection = document.selection.createRange();
$selection.moveStart('character', -this.val().length);
$position = $selection.text.length;
}
else if ($element.selectionStart || $element.selectionStart == '0') { // Opera, Chrome, Firefox, Safari, IE 9+
$position = parseInt($element.selectionStart);
}
return $position;
},
/**
* Sets the caret position of current element. If the element
* does not equal input[type=text], input[type=password] or
* textarea, false is returned.
*
* @param integer position
* @return boolean
*/
setCaret: function (position) {
if (this.is('input')) {
if (this.attr('type') != 'text' && this.attr('type') != 'password') {
return false;
}
}
else if (!this.is('textarea')) {
return false;
}
var $element = this.get(0);
// set focus to enable caret on this element
this.focus();
if (document.selection) { // IE 8
var $selection = document.selection.createRange();
$selection.moveStart('character', position);
$selection.moveEnd('character', 0);
$selection.select();
}
else if ($element.selectionStart || $element.selectionStart == '0') { // Opera, Chrome, Firefox, Safari, IE 9+
$element.selectionStart = position;
$element.selectionEnd = position;
}
return true;
},
/**
* Shows an element by sliding and fading it into viewport.
*
* @param string direction
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfDropIn: function(direction, callback, duration) {
if (!direction) direction = 'up';
if (!duration || !parseInt(duration)) duration = 200;
return this.show(WCF.getEffect(this, 'drop'), { direction: direction }, duration, callback);
},
/**
* Hides an element by sliding and fading it out the viewport.
*
* @param string direction
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfDropOut: function(direction, callback, duration) {
if (!direction) direction = 'down';
if (!duration || !parseInt(duration)) duration = 200;
return this.hide(WCF.getEffect(this, 'drop'), { direction: direction }, duration, callback);
},
/**
* Shows an element by blinding it up.
*
* @param string direction
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfBlindIn: function(direction, callback, duration) {
if (!direction) direction = 'vertical';
if (!duration || !parseInt(duration)) duration = 200;
return this.show(WCF.getEffect(this, 'blind'), { direction: direction }, duration, callback);
},
/**
* Hides an element by blinding it down.
*
* @param string direction
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfBlindOut: function(direction, callback, duration) {
if (!direction) direction = 'vertical';
if (!duration || !parseInt(duration)) duration = 200;
return this.hide(WCF.getEffect(this, 'blind'), { direction: direction }, duration, callback);
},
/**
* Highlights an element.
*
* @param object options
* @param object callback
* @returns jQuery
*/
wcfHighlight: function(options, callback) {
return this.effect('highlight', options, 600, callback);
},
/**
* Shows an element by fading it in.
*
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfFadeIn: function(callback, duration) {
if (!duration || !parseInt(duration)) duration = 200;
return this.show(WCF.getEffect(this, 'fade'), { }, duration, callback);
},
/**
* Hides an element by fading it out.
*
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfFadeOut: function(callback, duration) {
if (!duration || !parseInt(duration)) duration = 200;
return this.hide(WCF.getEffect(this, 'fade'), { }, duration, callback);
},
/**
* Returns a CSS property as raw number.
*
* @param string property
*/
cssAsNumber: function(property) {
if (this.length) {
var $property = this.css(property);
if ($property !== undefined) {
return parseInt($property.replace(/px$/, ''));
}
}
return 0;
},
/**
* @deprecated Use perfectScrollbar directly.
*
* This is taken from the jQuery adaptor of perfect scrollbar.
* Copyright (c) 2015 Hyunje Alex Jun and other contributors
* Licensed under the MIT License
*/
perfectScrollbar: function (settingOrCommand) {
var ps = require('perfect-scrollbar');
return this.each(function () {
if (typeof settingOrCommand === 'object' ||
typeof settingOrCommand === 'undefined') {
// If it's an object or none, initialize.
var settings = settingOrCommand;
if (!$(this).data('psID'))
ps.initialize(this, settings);
} else {
// Unless, it may be a command.
var command = settingOrCommand;
if (command === 'update') {
ps.update(this);
} else if (command === 'destroy') {
ps.destroy(this);
}
}
return jQuery(this);
});
}
});
/**
* WoltLab Suite Core methods
*/
$.extend(WCF, {
/**
* count of active dialogs
* @var integer
*/
activeDialogs: 0,
/**
* Counter for dynamic element ids
*
* @var integer
*/
_idCounter: 0,
/**
* Returns a dynamically created id.
*
* @see https://github.com/sstephenson/prototype/blob/5e5cfff7c2c253eaf415c279f9083b4650cd4506/src/prototype/dom/dom.js#L1789
* @return string
*/
getRandomID: function() {
return window.bc_wcfDomUtil.getUniqueId();
},
/**
* Wrapper for $.inArray which returns boolean value instead of
* index value, similar to PHP's in_array().
*
* @param mixed needle
* @param array haystack
* @return boolean
*/
inArray: function(needle, haystack) {
return ($.inArray(needle, haystack) != -1);
},
/**
* Adjusts effect for partially supported elements.
*
* @param jQuery object
* @param string effect
* @return string
*/
getEffect: function(object, effect) {
// most effects are not properly supported on table rows, use highlight instead
if (object.is('tr')) {
return 'highlight';
}
return effect;
},
/**
* Returns inline CSS for given element.
*
* @param jQuery element
* @return object
*/
getInlineCSS: function(element) {
var $inlineStyles = { };
var $style = element.attr('style');
// no style tag given or empty
if (!$style) {
return { };
}
$style = $style.split(';');
for (var $i = 0, $length = $style.length; $i < $length; $i++) {
var $fragment = $.trim($style[$i]);
if ($fragment == '') {
continue;
}
$fragment = $fragment.split(':');
$inlineStyles[$.trim($fragment[0])] = $.trim($fragment[1]);
}
return $inlineStyles;
},
/**
* Reverts inline CSS or negates a previously set property.
*
* @param jQuery element
* @param object inlineCSS
* @param array<string> targetProperties
*/
revertInlineCSS: function(element, inlineCSS, targetProperties) {
for (var $i = 0, $length = targetProperties.length; $i < $length; $i++) {
var $property = targetProperties[$i];
// revert inline CSS
if (inlineCSS[$property]) {
element.css($property, inlineCSS[$property]);
}
else {
// negate inline CSS
element.css($property, '');
}
}
},
/**
* @deprecated Use WoltLabSuite/Core/Core.getUuid().
*/
getUUID: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
},
/**
* Converts a base64 encoded file into a native Blob.
*
* @param string base64data
* @param string contentType
* @param integer sliceSize
* @return Blob
*/
base64toBlob: function(base64data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var $byteCharacters = atob(base64data);
var $byteArrays = [ ];
for (var $offset = 0; $offset < $byteCharacters.length; $offset += sliceSize) {
var $slice = $byteCharacters.slice($offset, $offset + sliceSize);
var $byteNumbers = new Array($slice.length);
for (var $i = 0; $i < $slice.length; $i++) {
$byteNumbers[$i] = $slice.charCodeAt($i);
}
var $byteArray = new Uint8Array($byteNumbers);
$byteArrays.push($byteArray);
}
return new Blob($byteArrays, { type: contentType });
},
/**
* Converts legacy URLs to the URL schema used by WCF 2.1.
*
* @param string url
* @return string
*/
convertLegacyURL: function(url) {
if (URL_LEGACY_MODE) {
return url;
}
return url.replace(/^index\.php\/(.*?)\/\?/, function(match, controller) {
var $parts = controller.split(/([A-Z][a-z0-9]+)/);
var $controller = '';
for (var $i = 0, $length = $parts.length; $i < $length; $i++) {
var $part = $parts[$i].trim();
if ($part.length) {
if ($controller.length) $controller += '-';
$controller += $part.toLowerCase();
}
}
return 'index.php?' + $controller + '/&';
});
}
});
/**
* Browser related functions.
*/
WCF.Browser = {
/**
* determines if browser is chrome
* @var boolean
*/
_isChrome: null,
/**
* Returns true, if browser is Chrome, Chromium or using GoogleFrame for Internet Explorer.
*
* @return boolean
*/
isChrome: function() {
if (this._isChrome === null) {
this._isChrome = false;
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
this._isChrome = true;
}
}
return this._isChrome;
}
};
/**
* Dropdown API
*
* @deprecated 3.0 - please use `Ui/SimpleDropdown` instead
*/
WCF.Dropdown = {
/**
* Initializes dropdowns.
*/
init: function(api) {
window.bc_wcfSimpleDropdown.initAll();
},
/**
* Initializes a dropdown.
*
* @param jQuery button
* @param boolean isLazyInitialization
*/
initDropdown: function(button, isLazyInitialization) {
window.bc_wcfSimpleDropdown.init(button[0], isLazyInitialization);
},
/**
* Removes the dropdown with the given container id.
*
* @param string containerID
*/
removeDropdown: function(containerID) {
window.bc_wcfSimpleDropdown.remove(containerID);
},
/**
* Initializes a dropdown fragment which behaves like a usual dropdown
* but is not controlled by a trigger element.
*
* @param jQuery dropdown
* @param jQuery dropdownMenu
*/
initDropdownFragment: function(dropdown, dropdownMenu) {
window.bc_wcfSimpleDropdown.initFragment(dropdown[0], dropdownMenu[0]);
},
/**
* Registers a callback notified upon dropdown state change.
*
* @param string identifier
* @var object callback
*/
registerCallback: function(identifier, callback) {
window.bc_wcfSimpleDropdown.registerCallback(identifier, callback);
},
/**
* Toggles a dropdown.
*
* @param object event
* @param string targetID
*/
_toggle: function(event, targetID) {
window.bc_wcfSimpleDropdown._toggle(event, targetID);
},
/**
* Toggles a dropdown.
*
* @param string containerID
*/
toggleDropdown: function(containerID) {
window.bc_wcfSimpleDropdown._toggle(null, containerID);
},
/**
* Returns dropdown by container id.
*
* @param string containerID
* @return jQuery
*/
getDropdown: function(containerID) {
var dropdown = window.bc_wcfSimpleDropdown.getDropdown(containerID);
return (dropdown) ? $(dropdown) : null;
},
/**
* Returns dropdown menu by container id.
*
* @param string containerID
* @return jQuery
*/
getDropdownMenu: function(containerID) {
var menu = window.bc_wcfSimpleDropdown.getDropdownMenu(containerID);
return (menu) ? $(menu) : null;
},
/**
* Sets alignment for given container id.
*
* @param string containerID
*/
setAlignmentByID: function(containerID) {
window.bc_wcfSimpleDropdown.setAlignmentById(containerID);
},
/**
* Sets alignment for dropdown.
*
* @param jQuery dropdown
* @param jQuery dropdownMenu
*/
setAlignment: function(dropdown, dropdownMenu) {
window.bc_wcfSimpleDropdown.setAlignment(dropdown[0], dropdownMenu[0]);
},
/**
* Closes all dropdowns.
*/
_closeAll: function() {
window.bc_wcfSimpleDropdown.closeAll();
},
/**
* Closes a dropdown without notifying callbacks.
*
* @param string containerID
*/
close: function(containerID) {
window.bc_wcfSimpleDropdown.close(containerID);
},
/**
* Destroies an existing dropdown menu.
*
* @param string containerID
* @return boolean
*/
destroy: function(containerID) {
window.bc_wcfSimpleDropdown.destroy(containerID);
}
};
/**
* Namespace for interactive dropdowns.
*/
WCF.Dropdown.Interactive = { };
/**
* General interface to create and manage interactive dropdowns.
*/
WCF.Dropdown.Interactive.Handler = {
/**
* global container for interactive dropdowns
* @var jQuery
*/
_dropdownContainer: null,
/**
* list of dropdown instances by identifier
* @var object<WCF.Dropdown.Interactive.Instance>
*/
_dropdownMenus: { },
/**
* Creates a new interactive dropdown instance.
*
* @param jQuery triggerElement
* @param string identifier
* @param object options
* @return WCF.Dropdown.Interactive.Instance
*/
create: function(triggerElement, identifier, options) {
if (this._dropdownContainer === null) {
this._dropdownContainer = $('<div class="dropdownMenuContainer" />').appendTo(document.body);
WCF.CloseOverlayHandler.addCallback('WCF.Dropdown.Interactive.Handler', $.proxy(this.closeAll, this));
window.addEventListener('scroll', (function (event) {
if (!document.documentElement.classList.contains('pageOverlayActive')) {
this.closeAll.bind(this)
}
}).bind(this));
}
var $instance = new WCF.Dropdown.Interactive.Instance(this._dropdownContainer, triggerElement, identifier, options);
this._dropdownMenus[identifier] = $instance;
return $instance;
},
/**
* Opens an interactive dropdown, returns false if identifier is unknown.
*
* @param string identifier
* @return boolean
*/
open: function(identifier) {
if (this._dropdownMenus[identifier]) {
this._dropdownMenus[identifier].open();
return true;
}
return false;
},
/**
* Closes an interactive dropdown, returns false if identifier is unknown.
*
* @param string identifier
* @return boolean
*/
close: function(identifier) {
if (this._dropdownMenus[identifier]) {
this._dropdownMenus[identifier].close();
return true;
}
return false;
},
/**
* Closes all interactive dropdowns.
*/
closeAll: function() {
$.each(this._dropdownMenus, function(identifier, instance) {
instance.close();
});
}
};
/**
* Represents and manages a single interactive dropdown instance.
*
* @param jQuery dropdownContainer
* @param jQuery triggerElement
* @param string identifier
* @param object options
*/
WCF.Dropdown.Interactive.Instance = Class.extend({
/**
* dropdown container
* @var jQuery
*/
_container: null,
/**
* inner item list
* @var jQuery
*/
_itemList: null,
/**
* header link list
* @var jQuery
*/
_linkList: null,
/**
* option list
* @var object
*/
_options: { },
/**
* arrow pointer
* @var jQuery
*/
_pointer: null,
/**
* trigger element
* @var jQuery
*/
_triggerElement: null,
/**
* Represents and manages a single interactive dropdown instance.
*
* @param jQuery dropdownContainer
* @param jQuery triggerElement
* @param string identifier
* @param object options
*/
init: function(dropdownContainer, triggerElement, identifier, options) {
this._options = options || { };
this._triggerElement = triggerElement;
var $itemContainer = null;
if (options.staticDropdown === true) {
this._container = this._triggerElement.find('.interactiveDropdownStatic:eq(0)').data('source', identifier).click(function(event) { event.stopPropagation(); });
}
else {
this._container = $('<div class="interactiveDropdown" data-source="' + identifier + '" />').click(function(event) { event.stopPropagation(); });
var $header = $('<div class="interactiveDropdownHeader" />').appendTo(this._container);
$('<span class="interactiveDropdownTitle">' + options.title + '</span>').appendTo($header);
this._linkList = $('<ul class="interactiveDropdownLinks inlineList"></ul>').appendTo($header);
$itemContainer = $('<div class="interactiveDropdownItemsContainer" />').appendTo(this._container);
this._itemList = $('<ul class="interactiveDropdownItems" />').appendTo($itemContainer);
$('<a href="' + options.showAllLink + '" class="interactiveDropdownShowAll">' + WCF.Language.get('wcf.user.panel.showAll') + '</a>').appendTo(this._container);
}
this._pointer = $('<span class="elementPointer"><span /></span>').appendTo(this._container);
require(['Environment'], function(Environment) {
if (Environment.platform() === 'desktop' && $itemContainer !== null) {
// use jQuery scrollbar on desktop, mobile browsers have a similar display built-in
$itemContainer.perfectScrollbar({
suppressScrollX: true
});
}
});
this._container.appendTo(dropdownContainer);
},
/**
* Returns the dropdown container.
*
* @return jQuery
*/
getContainer: function() {
return this._container;
},
/**
* Returns the inner item list.
*
* @return jQuery
*/
getItemList: function() {
return this._itemList;
},
/**
* Returns the header link list.
*
* @return jQuery
*/
getLinkList: function() {
return this._linkList;
},
/**
* Opens the dropdown.
*/
open: function() {
WCF.Dropdown._closeAll();
this._triggerElement.addClass('open');
this._container.addClass('open');
this.render();
},
/**
* Closes the dropdown
*/
close: function() {
this._triggerElement.removeClass('open');
this._container.removeClass('open');
},
/**
* Returns true if dropdown instance is visible.
*
* @returns {boolean}
*/
isOpen: function() {
return this._triggerElement.hasClass('open');
},
/**
* Toggles the dropdown state, returns true if dropdown is open afterwards, else false.
*
* @return boolean
*/
toggle: function() {
if (this._container.hasClass('open')) {
this.close();
return false;
}
else {
WCF.Dropdown.Interactive.Handler.closeAll();
this.open();
return true;
}
},
/**
* Resets the inner item list and closes the dropdown.
*/
resetItems: function() {
this._itemList.empty();
this.close();
},
/**
* Renders the dropdown.
*/
render: function() {
if (window.matchMedia('(max-width: 767px)').matches) {
this._container.css({
bottom: '',
left: '',
right: '',
top: elById('pageHeader').clientHeight + 'px'
});
}
else {
require(['Ui/Alignment'], (function(UiAlignment) {
UiAlignment.set(this._container[0], this._triggerElement[0], {
horizontal: 'right',
pointer: true
});
}).bind(this));
}
},
/**
* Rebuilds the desktop scrollbar.
*/
rebuildScrollbar: function() {
require(['Environment'], function(Environment) {
if (Environment.platform() === 'desktop') {
var $itemContainer = this._itemList.parent();
// do NOT use 'update', seems to be broken
$itemContainer.perfectScrollbar('destroy');
$itemContainer.perfectScrollbar({
suppressScrollX: true
});
}
}.bind(this));
}
});
/**
* Clipboard API
*
* @deprecated 3.0 - please use `WoltLabSuite/Core/Controller/Clipboard` instead
*/
WCF.Clipboard = {
/**
* Initializes the clipboard API.
*
* @param string page
* @param integer hasMarkedItems
* @param object actionObjects
* @param integer pageObjectID
*/
init: function(page, hasMarkedItems, actionObjects, pageObjectID) {
require(['WoltLabSuite/Core/Controller/Clipboard'], function(ControllerClipboard) {
ControllerClipboard.setup({
hasMarkedItems: (hasMarkedItems > 0),
pageClassName: page,
pageObjectId: pageObjectID
});
});
},
/**
* Reloads the list of marked items.
*/
reload: function() {
require(['WoltLabSuite/Core/Controller/Clipboard'], function(ControllerClipboard) {
ControllerClipboard.reload();
});
}
};
/**
* @deprecated Use WoltLabSuite/Core/Timer/Repeating
*/
WCF.PeriodicalExecuter = Class.extend({
/**
* callback for each execution cycle
* @var object
*/
_callback: null,
/**
* interval
* @var integer
*/
_delay: 0,
/**
* interval id
* @var integer
*/
_intervalID: null,
/**
* execution state
* @var boolean
*/
_isExecuting: false,
/**
* Initializes a periodical executer.
*
* @param function callback
* @param integer delay
*/
init: function(callback, delay) {
if (!$.isFunction(callback)) {
console.debug('[WCF.PeriodicalExecuter] Given callback is invalid, aborting.');
return;
}
this._callback = callback;
this._interval = delay;
this.resume();
},
/**
* Executes callback.
*/
_execute: function() {
if (!this._isExecuting) {
try {
this._isExecuting = true;
this._callback(this);
this._isExecuting = false;
}
catch (e) {
this._isExecuting = false;
throw e;
}
}
},
/**
* Terminates loop.
*/
stop: function() {
if (!this._intervalID) {
return;
}
clearInterval(this._intervalID);
},
/**
* Resumes the interval-based callback execution.
*
* @deprecated 2.1 - use restart() instead
*/
resume: function() {
this.restart();
},
/**
* Restarts the interval-based callback execution.
*/
restart: function() {
if (this._intervalID) {
this.stop();
}
this._intervalID = setInterval($.proxy(this._execute, this), this._interval);
},
/**
* Sets the interval and restarts the interval.
*
* @param integer interval
*/
setInterval: function(interval) {
this._interval = interval;
this.restart();
}
});
/**
* Handler for loading overlays
*
* @deprecated 3.0 - Please use WoltLabSuite/Core/Ajax/Status
*/
WCF.LoadingOverlayHandler = {
/**
* Adds one loading-request and shows the loading overlay if nessercery
*/
show: function() {
require(['WoltLabSuite/Core/Ajax/Status'], function(AjaxStatus) {
AjaxStatus.show();
});
},
/**
* Removes one loading-request and hides loading overlay if there're no more pending requests
*/
hide: function() {
require(['WoltLabSuite/Core/Ajax/Status'], function(AjaxStatus) {
AjaxStatus.hide();
});
},
/**
* Updates a icon to/from spinner
*
* @param jQuery target
* @pram boolean loading
*/
updateIcon: function(target, loading) {
var $method = (loading === undefined || loading ? 'addClass' : 'removeClass');
target.find('.icon')[$method]('fa-spinner');
if (target.hasClass('icon')) {
target[$method]('fa-spinner');
}
}
};
/**
* Namespace for AJAXProxies
*/
WCF.Action = {};
/**
* Basic implementation for AJAX-based proxyies
*
* @deprecated 3.0 - please use `WoltLabSuite/Core/Ajax.api()` instead
*
* @param object options
*/
WCF.Action.Proxy = Class.extend({
_ajaxRequest: null,
/**
* Initializes AJAXProxy.
*
* @param object options
*/
init: function(options) {
this._ajaxRequest = null;
options = $.extend(true, {
autoSend: false,
data: { },
dataType: 'json',
after: null,
init: null,
jsonp: 'callback',
async: true,
failure: null,
showLoadingOverlay: true,
success: null,
suppressErrors: false,
type: 'POST',
url: 'index.php?ajax-proxy/&t=' + SECURITY_TOKEN,
aborted: null,
autoAbortPrevious: false
}, options);
if (options.dataType === 'jsonp') {
require(['AjaxJsonp'], function(AjaxJsonp) {
AjaxJsonp.send(options.url, options.success, options.failure, {
parameterName: options.jsonp
});
});
}
else {
require(['AjaxRequest'], (function(AjaxRequest) {
this._ajaxRequest = new AjaxRequest({
data: options.data,
type: options.type,
url: options.url,
responseType: (options.dataType === 'json' ? 'application/json' : ''),
autoAbort: options.autoAbortPrevious,
ignoreError: options.suppressErrors,
silent: !options.showLoadingOverlay,
failure: options.failure,
finalize: options.after,
success: options.success
});
if (options.autoSend) {
this._ajaxRequest.sendRequest();
}
}).bind(this));
}
},
/**
* Sends an AJAX request.
*
* @param abortPrevious boolean
*/
sendRequest: function(abortPrevious) {
require(['AjaxRequest'], (function(AjaxRequest) {
if (this._ajaxRequest !== null) {
this._ajaxRequest.sendRequest(abortPrevious);
}
}).bind(this));
},
/**
* Aborts the previous request
*/
abortPrevious: function() {
require(['AjaxRequest'], (function(AjaxRequest) {
if (this._ajaxRequest !== null) {
this._ajaxRequest.abortPrevious();
}
}).bind(this));
},
/**
* Sets options, MUST be used to set parameters before sending request
* if calling from child classes.
*
* @param string optionName
* @param mixed optionData
*/
setOption: function(optionName, optionData) {
require(['AjaxRequest'], (function(AjaxRequest) {
if (this._ajaxRequest !== null) {
this._ajaxRequest.setOption(optionName, optionData);
}
}).bind(this));
},
// legacy methods, no longer supported
showLoadingOverlayOnce: function() {},
suppressErrors: function() {},
_failure: function(jqXHR, textStatus, errorThrown) {},
_success: function(data, textStatus, jqXHR) {},
_after: function() {}
});
/**
* Basic implementation for simple proxy access using bound elements.
*
* @param object options
* @param object callbacks
*/
WCF.Action.SimpleProxy = Class.extend({
/**
* Initializes SimpleProxy.
*
* @param object options
* @param object callbacks
*/
init: function(options, callbacks) {
/**
* action-specific options
*/
this.options = $.extend(true, {
action: '',
className: '',
elements: null,
eventName: 'click'
}, options);
/**
* proxy-specific options
*/
this.callbacks = $.extend(true, {
after: null,
failure: null,
init: null,
success: null
}, callbacks);
if (!this.options.elements) return;
// initialize proxy
this.proxy = new WCF.Action.Proxy(this.callbacks);
// bind event listener
this.options.elements.each($.proxy(function(index, element) {
$(element).bind(this.options.eventName, $.proxy(this._handleEvent, this));
}, this));
},
/**
* Handles event actions.
*
* @param object event
*/
_handleEvent: function(event) {
this.proxy.setOption('data', {
actionName: this.options.action,
className: this.options.className,
objectIDs: [ $(event.target).data('objectID') ]
});
this.proxy.sendRequest();
}
});
/**
* Basic implementation for AJAXProxy-based deletion.
*
* @param string className
* @param string containerSelector
* @param string buttonSelector
*/
WCF.Action.Delete = Class.extend({
/**
* delete button selector
* @var string
*/
_buttonSelector: '',
/**
* action class name
* @var string
*/
_className: '',
/**
* container selector
* @var string
*/
_containerSelector: '',
/**
* list of known container ids
* @var array<string>
*/
_containers: [ ],
/**
* Initializes 'delete'-Proxy.
*
* @param string className
* @param string containerSelector
* @param string buttonSelector
*/
init: function(className, containerSelector, buttonSelector) {
this._containerSelector = containerSelector;
this._className = className;
this._buttonSelector = (buttonSelector) ? buttonSelector : '.jsDeleteButton';
this.proxy = new WCF.Action.Proxy({
success: $.proxy(this._success, this)
});
this._initElements();
WCF.DOMNodeInsertedHandler.addCallback('WCF.Action.Delete' + this._className.hashCode(), $.proxy(this._initElements, this));
},
/**
* Initializes available element containers.
*/
_initElements: function() {
$(this._containerSelector).each((function(index, container) {
var $container = $(container);
var $containerID = $container.wcfIdentify();
if (!WCF.inArray($containerID, this._containers)) {
var $deleteButton = $container.find(this._buttonSelector);
if ($deleteButton.length) {
this._containers.push($containerID);
$deleteButton.click($.proxy(this._click, this));
}
}
}).bind(this));
},
/**
* Sends AJAX request.
*
* @param object event
*/
_click: function(event) {
var $target = $(event.currentTarget);
event.preventDefault();
if ($target.data('confirmMessageHtml') || $target.data('confirmMessage')) {
WCF.System.Confirmation.show($target.data('confirmMessageHtml') ? $target.data('confirmMessageHtml') : $target.data('confirmMessage'), $.proxy(this._execute, this), { target: $target }, undefined, $target.data('confirmMessageHtml') ? true : false);
}
else {
WCF.LoadingOverlayHandler.updateIcon($target);
this._sendRequest($target);
}
},
/**
* Is called if the delete effect has been triggered on the given element.
*
* @param jQuery element
*/
_didTriggerEffect: function(element) {
// does nothing
},
/**
* Executes deletion.
*
* @param string action
* @param object parameters
*/
_execute: function(action, parameters) {
if (action === 'cancel') {
return;
}
WCF.LoadingOverlayHandler.updateIcon(parameters.target);
this._sendRequest(parameters.target);
},
/**
* Sends the request
*
* @param jQuery object
*/
_sendRequest: function(object) {
this.proxy.setOption('data', {
actionName: 'delete',
className: this._className,
interfaceName: 'wcf\\data\\IDeleteAction',
objectIDs: [ $(object).data('objectID') ]
});
this.proxy.sendRequest();
},
/**
* Deletes items from containers.
*
* @param object data
* @param string textStatus
* @param object jqXHR
*/
_success: function(data, textStatus, jqXHR) {
this.triggerEffect(data.objectIDs);
},
/**
* Triggers the delete effect for the objects with the given ids.
*
* @param array objectIDs
*/
triggerEffect: function(objectIDs) {
for (var $index in this._containers) {
var $container = $('#' + this._containers[$index]);
var $button = $container.find(this._buttonSelector);
if (WCF.inArray($button.data('objectID'), objectIDs)) {
var self = this;
$container.wcfBlindOut('up',function() {
var $container = $(this).remove();
self._containers.splice(self._containers.indexOf($container.wcfIdentify()), 1);
self._didTriggerEffect($container);
if ($button.data('eventName')) {
WCF.System.Event.fireEvent('com.woltlab.wcf.action.delete', $button.data('eventName'), {
button: $button,
container: $container
});
}
});
}
}
}
});
/**
* Basic implementation for deletion of nested elements.
*
* The implementation requires the nested elements to be grouped as numbered lists
* (ol lists). The child elements of the deleted elements are moved to the parent
* element of the deleted element.
*
* @see WCF.Action.Delete
*/
WCF.Action.NestedDelete = WCF.Action.Delete.extend({
/**
* @see WCF.Action.Delete.triggerEffect()
*/
triggerEffect: function(objectIDs) {
for (var $index in this._containers) {
var $container = $('#' + this._containers[$index]);
if (WCF.inArray($container.find(this._buttonSelector).data('objectID'), objectIDs)) {
// move children up
if ($container.has('ol').has('li').length) {
if ($container.is(':only-child')) {
$container.parent().replaceWith($container.find('> ol'));
}
else {
$container.replaceWith($container.find('> ol > li'));
}
this._containers.splice(this._containers.indexOf($container.wcfIdentify()), 1);
this._didTriggerEffect($container);
}
else {
var self = this;
$container.wcfBlindOut('up', function() {
$(this).remove();
self._containers.splice(self._containers.indexOf($(this).wcfIdentify()), 1);
self._didTriggerEffect($(this));
});
}
}
}
}
});
/**
* Basic implementation for AJAXProxy-based toggle actions.
*
* @param string className
* @param jQuery containerList
* @param string buttonSelector
*/
WCF.Action.Toggle = Class.extend({
/**
* toogle button selector
* @var string
*/
_buttonSelector: '.jsToggleButton',
/**
* action class name
* @var string
*/
_className: '',
/**
* container selector
* @var string
*/
_containerSelector: '',
/**
* list of known container ids
* @var array<string>
*/
_containers: [ ],
/**
* Initializes 'toggle'-Proxy
*
* @param string className
* @param string containerSelector
* @param string buttonSelector
*/
init: function(className, containerSelector, buttonSelector) {
this._containerSelector = containerSelector;
this._className = className;
this._buttonSelector = (buttonSelector) ? buttonSelector : '.jsToggleButton';
this._containers = [ ];
// initialize proxy
var options = {
success: $.proxy(this._success, this)
};
this.proxy = new WCF.Action.Proxy(options);
// bind event listener
this._initElements();
WCF.DOMNodeInsertedHandler.addCallback('WCF.Action.Toggle' + this._className.hashCode(), $.proxy(this._initElements, this));
},
/**
* Initializes available element containers.
*/
_initElements: function() {
$(this._containerSelector).each($.proxy(function(index, container) {
var $container = $(container);
var $containerID = $container.wcfIdentify();
if (!WCF.inArray($containerID, this._containers)) {
this._containers.push($containerID);
$container.find(this._buttonSelector).click($.proxy(this._click, this));
}
}, this));
},
/**
* Sends AJAX request.
*
* @param object event
*/
_click: function(event) {
var $target = $(event.currentTarget);
event.preventDefault();
if ($target.data('confirmMessageHtml') || $target.data('confirmMessage')) {
WCF.System.Confirmation.show($target.data('confirmMessageHtml') ? $target.data('confirmMessageHtml') : $target.data('confirmMessage'), $.proxy(this._execute, this), { target: $target }, undefined, $target.data('confirmMessageHtml') ? true : false);
}
else {
WCF.LoadingOverlayHandler.updateIcon($target);
this._sendRequest($target);
}
},
/**
* Executes toggeling.
*
* @param string action
* @param object parameters
*/
_execute: function(action, parameters) {
if (action === 'cancel') {
return;
}
WCF.LoadingOverlayHandler.updateIcon(parameters.target);
this._sendRequest(parameters.target);
},
_sendRequest: function(object) {
this.proxy.setOption('data', {
actionName: 'toggle',
className: this._className,
interfaceName: 'wcf\\data\\IToggleAction',
objectIDs: [ $(object).data('objectID') ]
});
this.proxy.sendRequest();
},
/**
* Toggles status icons.
*
* @param object data
* @param string textStatus
* @param object jqXHR
*/
_success: function(data, textStatus, jqXHR) {
this.triggerEffect(data.objectIDs);
},
/**
* Triggers the toggle effect for the objects with the given ids.
*
* @param array objectIDs
*/
triggerEffect: function(objectIDs) {
for (var $index in this._containers) {
var $container = $('#' + this._containers[$index]);
var $toggleButton = $container.find(this._buttonSelector);
if (WCF.inArray($toggleButton.data('objectID'), objectIDs)) {
$container.wcfHighlight();
this._toggleButton($container, $toggleButton);
}
}
},
/**
* Tiggers the toggle effect on a button
*
* @param jQuery $container
* @param jQuery $toggleButton
*/
_toggleButton: function($container, $toggleButton) {
var $newTitle = '';
// toggle icon source
WCF.LoadingOverlayHandler.updateIcon($toggleButton, false);
if ($toggleButton.hasClass('fa-square-o')) {
$toggleButton.removeClass('fa-square-o').addClass('fa-check-square-o');
$newTitle = ($toggleButton.data('disableTitle') ? $toggleButton.data('disableTitle') : WCF.Language.get('wcf.global.button.disable'));
$toggleButton.attr('title', $newTitle);
}
else {
$toggleButton.removeClass('fa-check-square-o').addClass('fa-square-o');
$newTitle = ($toggleButton.data('enableTitle') ? $toggleButton.data('enableTitle') : WCF.Language.get('wcf.global.button.enable'));
$toggleButton.attr('title', $newTitle);
}
// toggle css class
$container.toggleClass('disabled');
}
});
/**
* Executes provided callback if scroll threshold is reached. Usuable to determine
* if user reached the bottom of an element to load new elements on the fly.
*
* If you do not provide a value for 'reference' and 'target' it will assume you're
* monitoring page scrolls, otherwise a valid jQuery selector must be provided for both.
*
* @param integer threshold
* @param object callback
* @param string reference
* @param string target
*/
WCF.Action.Scroll = Class.extend({
/**
* callback used once threshold is reached
* @var object
*/
_callback: null,
/**
* reference object
* @var jQuery
*/
_reference: null,
/**
* target object
* @var jQuery
*/
_target: null,
/**
* threshold value
* @var integer
*/
_threshold: 0,
/**
* Initializes a new WCF.Action.Scroll object.
*
* @param integer threshold
* @param object callback
* @param string reference
* @param string target
*/
init: function(threshold, callback, reference, target) {
this._threshold = parseInt(threshold);
if (this._threshold === 0) {
console.debug("[WCF.Action.Scroll] Given threshold is invalid, aborting.");
return;
}
if ($.isFunction(callback)) this._callback = callback;
if (this._callback === null) {
console.debug("[WCF.Action.Scroll] Given callback is invalid, aborting.");
return;
}
// bind element references
this._reference = $((reference) ? reference : window);
this._target = $((target) ? target : document);
// watch for scroll event
this.start();
// check if browser navigated back and jumped to offset before JavaScript was loaded
this._scroll();
},
/**
* Calculates if threshold is reached and notifies callback.
*/
_scroll: function() {
var $targetHeight = this._target.height();
var $topOffset = this._reference.scrollTop();
var $referenceHeight = this._reference.height();
// calculate if defined threshold is visible
if (($targetHeight - ($referenceHeight + $topOffset)) < this._threshold) {
this._callback(this);
}
},
/**
* Enables scroll monitoring, may be used to resume.
*/
start: function() {
this._reference.on('scroll', $.proxy(this._scroll, this));
},
/**
* Disables scroll monitoring, e.g. no more elements loadable.
*/
stop: function() {
this._reference.off('scroll');
}
});
/**
* Namespace for date-related functions.
*/
WCF.Date = {};
/**
* Provides a date picker for date input fields.
*
* @deprecated 3.0 - no longer required
*/
WCF.Date.Picker = { init: function() {} };
/**
* Provides utility functions for date operations.
*
* @deprecated 3.0 - use `DateUtil` instead
*/
WCF.Date.Util = {
/**
* Returns UTC timestamp, if date is not given, current time will be used.
*
* @param Date date
* @return integer
*
* @deprecated 3.0 - use `DateUtil::gmdate()` instead
*/
gmdate: function(date) {
var $date = (date) ? date : new Date();
return Math.round(Date.UTC(
$date.getUTCFullYear(),
$date.getUTCMonth(),
$date.getUTCDay(),
$date.getUTCHours(),
$date.getUTCMinutes(),
$date.getUTCSeconds()
) / 1000);
},
/**
* Returns a Date object with precise offset (including timezone and local timezone).
* Parameters timestamp and offset must be in miliseconds!
*
* @param integer timestamp
* @param integer offset
* @return Date
*
* @deprecated 3.0 - use `DateUtil::getTimezoneDate()` instead
*/
getTimezoneDate: function(timestamp, offset) {
var $date = new Date(timestamp);
var $localOffset = $date.getTimezoneOffset() * 60000;
return new Date((timestamp + $localOffset + offset));
}
};
/**
* Hash-like dictionary. Based upon idead from Prototype's hash
*
* @see https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/hash.js
*/
WCF.Dictionary = Class.extend({
/**
* list of variables
* @var object
*/
_variables: { },
/**
* Initializes a new dictionary.
*/
init: function() {
this._variables = { };
},
/**
* Adds an entry.
*
* @param string key
* @param mixed value
*/
add: function(key, value) {
this._variables[key] = value;
},
/**
* Adds a traditional object to current dataset.
*
* @param object object
*/
addObject: function(object) {
for (var $key in object) {
this.add($key, object[$key]);
}
},
/**
* Adds a dictionary to current dataset.
*
* @param object dictionary
*/
addDictionary: function(dictionary) {
dictionary.each($.proxy(function(pair) {
this.add(pair.key, pair.value);
}, this));
},
/**
* Retrieves the value of an entry or returns null if key is not found.
*
* @param string key
* @returns mixed
*/
get: function(key) {
if (this.isset(key)) {
return this._variables[key];
}
return null;
},
/**
* Returns true if given key is a valid entry.
*
* @param string key
*/
isset: function(key) {
return this._variables.hasOwnProperty(key);
},
/**
* Removes an entry.
*
* @param string key
*/
remove: function(key) {
delete this._variables[key];
},
/**
* Iterates through dictionary.
*
* Usage:
* var $hash = new WCF.Dictionary();
* $hash.add('foo', 'bar');
* $hash.each(function(pair) {
* // alerts: foo = bar
* alert(pair.key + ' = ' + pair.value);
* });
*
* @param function callback
*/
each: function(callback) {
if (!$.isFunction(callback)) {
return;
}
for (var $key in this._variables) {
var $value = this._variables[$key];
var $pair = {
key: $key,
value: $value
};
callback($pair);
}
},
/**
* Returns the amount of items.
*
* @return integer
*/
count: function() {
return $.getLength(this._variables);
},
/**
* Returns true if dictionary is empty.
*
* @return integer
*/
isEmpty: function() {
return !this.count();
}
});
// non strict equals by intent
if (window.WCF.Language == null) {
/**
* @deprecated Use WoltLabSuite/Core/Language
*/
WCF.Language = {
add: function(key, value) {
require(['Language'], function(Language) {
Language.add(key, value);
});
},
addObject: function(object) {
require(['Language'], function(Language) {
Language.addObject(object);
});
},
get: function(key, parameters) {
// This cannot be sanely provided as a compatibility wrapper.
throw new Error('Call to deprecated WCF.Language.get("' + key + '")');
}
};
}
/**
* Handles multiple language input fields.
*
* @param string elementID
* @param boolean forceSelection
* @param object values
* @param object availableLanguages
*/
WCF.MultipleLanguageInput = Class.extend({
/**
* list of available languages
* @var object
*/
_availableLanguages: {},
/**
* button element
* @var jQuery
*/
_button: null,
/**
* initialization state
* @var boolean
*/
_didInit: false,
/**
* target input element
* @var jQuery
*/
_element: null,
/**
* true, if data was entered after initialization
* @var boolean
*/
_insertedDataAfterInit: false,
/**
* enables multiple language ability
* @var boolean
*/
_isEnabled: false,
/**
* enforce multiple language ability
* @var boolean
*/
_forceSelection: false,
/**
* currently active language id
* @var integer
*/
_languageID: 0,
/**
* language selection list
* @var jQuery
*/
_list: null,
/**
* list of language values on init
* @var object
*/
_values: null,
/**
* Initializes multiple language ability for given element id.
*
* @param integer elementID
* @param boolean forceSelection
* @param boolean isEnabled
* @param object values
* @param object availableLanguages
*/
init: function(elementID, forceSelection, values, availableLanguages) {
this._button = null;
this._element = $('#' + $.wcfEscapeID(elementID));
this._forceSelection = forceSelection;
this._values = values;
this._availableLanguages = availableLanguages;
// unescape values
if ($.getLength(this._values)) {
for (var $key in this._values) {
this._values[$key] = WCF.String.unescapeHTML(this._values[$key]);
}
}
// default to current user language
this._languageID = LANGUAGE_ID;
if (this._element.length == 0) {
console.debug("[WCF.MultipleLanguageInput] element id '" + elementID + "' is unknown");
return;
}
// build selection handler
var $enableOnInit = ($.getLength(this._values) > 0) ? true : false;
this._insertedDataAfterInit = $enableOnInit;
this._prepareElement($enableOnInit);
// listen for submit event
this._element.parents('form').submit($.proxy(this._submit, this));
this._didInit = true;
},
/**
* Builds language handler.
*
* @param boolean enableOnInit
*/
_prepareElement: function(enableOnInit) {
this._element.wrap('<div class="dropdown preInput" />');
var $wrapper = this._element.parent();
this._button = $('<p class="button dropdownToggle"><span>' + WCF.Language.get('wcf.global.button.disabledI18n') + '</span></p>').prependTo($wrapper);
// insert list
this._list = $('<ul class="dropdownMenu"></ul>').insertAfter(this._button);
// add a special class if next item is a textarea
if (this._button.nextAll('textarea').length) {
this._button.addClass('dropdownCaptionTextarea');
}
else {
this._button.addClass('dropdownCaption');
}
// insert available languages
for (var $languageID in this._availableLanguages) {
$('<li><span>' + this._availableLanguages[$languageID] + '</span></li>').data('languageID', $languageID).click($.proxy(this._changeLanguage, this)).appendTo(this._list);
}
// disable language input
if (!this._forceSelection) {
$('<li class="dropdownDivider" />').appendTo(this._list);
$('<li><span>' + WCF.Language.get('wcf.global.button.disabledI18n') + '</span></li>').click($.proxy(this._disable, this)).appendTo(this._list);
}
WCF.Dropdown.initDropdown(this._button, enableOnInit);
if (enableOnInit || this._forceSelection) {
this._isEnabled = true;
// pre-select current language
this._list.children('li').each($.proxy(function(index, listItem) {
var $listItem = $(listItem);
if ($listItem.data('languageID') == this._languageID) {
$listItem.trigger('click');
}
}, this));
}
WCF.Dropdown.registerCallback($wrapper.wcfIdentify(), $.proxy(this._handleAction, this));
},
/**
* Handles dropdown actions.
*
* @param string containerID
* @param string action
*/
_handleAction: function(containerID, action) {
if (action === 'open') {
this._enable();
}
else {
this._closeSelection();
}
},
/**
* Enables the language selection or shows the selection if already enabled.
*
* @param object event
*/
_enable: function(event) {
if (!this._isEnabled) {
var $button = (this._button.is('p')) ? this._button.children('span:eq(0)') : this._button;
$button.addClass('active');
this._isEnabled = true;
}
// toggle list
if (this._list.is(':visible')) {
this._showSelection();
}
},
/**
* Shows the language selection.
*/
_showSelection: function() {
if (this._isEnabled) {
// display status for each language
this._list.children('li').each($.proxy(function(index, listItem) {
var $listItem = $(listItem);
var $languageID = $listItem.data('languageID');
if ($languageID) {
if (this._values[$languageID] && this._values[$languageID] != '') {
$listItem.removeClass('missingValue');
}
else {
$listItem.addClass('missingValue');
}
}
}, this));
}
},
/**
* Closes the language selection.
*/
_closeSelection: function() {
this._disable();
},
/**
* Changes the currently active language.
*
* @param object event
*/
_changeLanguage: function(event) {
var $button = $(event.currentTarget);
this._insertedDataAfterInit = true;
// save current value
if (this._didInit) {
this._values[this._languageID] = this._element.val();
}
// set new language
this._languageID = $button.data('languageID');
if (this._values[this._languageID]) {
this._element.val(this._values[this._languageID]);
}
else {
this._element.val('');
}
// update marking
this._list.children('li').removeClass('active');
$button.addClass('active');
// update label
this._button.children('span').addClass('active').text(this._availableLanguages[this._languageID]);
// close selection and set focus on input element
if (this._didInit) {
this._element.blur().focus();
}
},
/**
* Disables language selection for current element.
*
* @param object event
*/
_disable: function(event) {
if (event === undefined && this._insertedDataAfterInit) {
event = null;
}
if (this._forceSelection || !this._list || event === null) {
return;
}
// remove active marking
this._button.children('span').removeClass('active').text(WCF.Language.get('wcf.global.button.disabledI18n'));
// update element value
if (this._values[LANGUAGE_ID]) {
this._element.val(this._values[LANGUAGE_ID]);
}
else {
// no value for current language found, proceed with empty input
this._element.val();
}
if (event) {
this._list.children('li').removeClass('active');
$(event.currentTarget).addClass('active');
}
this._element.blur().focus();
this._insertedDataAfterInit = false;
this._isEnabled = false;
this._values = { };
},
/**
* Prepares language variables on before submit.
*/
_submit: function() {
// insert hidden form elements on before submit
if (!this._isEnabled) {
return 0xDEADBEEF;
}
// fetch active value
if (this._languageID) {
this._values[this._languageID] = this._element.val();
}
var $form = $(this._element.parents('form')[0]);
var $elementID = this._element.wcfIdentify();
for (var $languageID in this._availableLanguages) {
if (this._values[$languageID] === undefined) {
this._values[$languageID] = '';
}
$('<input type="hidden" name="' + $elementID + '_i18n[' + $languageID + ']" value="' + WCF.String.escapeHTML(this._values[$languageID]) + '" />').appendTo($form);
}
// remove name attribute to prevent conflict with i18n values
this._element.removeAttr('name');
}
});
/**
* Number utilities.
* @deprecated Use WoltLabSuite/Core/NumberUtil
*/
WCF.Number = {
/**
* Rounds a number to a given number of decimal places. Defaults to 0.
*
* @param number number
* @param decimalPlaces number of decimal places
* @return number
*/
round: function (number, decimalPlaces) {
decimalPlaces = Math.pow(10, (decimalPlaces || 0));
return Math.round(number * decimalPlaces) / decimalPlaces;
}
};
/**
* String utilities.
* @deprecated Use WoltLabSuite/Core/StringUtil
*/
WCF.String = {
/**
* Adds thousands separators to a given number.
*
* @see http://stackoverflow.com/a/6502556/782822
* @param mixed number
* @return string
*/
addThousandsSeparator: function(number) {
return String(number).replace(/(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1' + WCF.Language.get('wcf.global.thousandsSeparator'));
},
/**
* Escapes special HTML-characters within a string
*
* @param string string
* @return string
*/
escapeHTML: function (string) {
return String(string).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
},
/**
* Escapes a String to work with RegExp.
*
* @see https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/regexp.js#L25
* @param string string
* @return string
*/
escapeRegExp: function(string) {
return String(string).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
},
/**
* Rounds number to given count of floating point digits, localizes decimal-point and inserts thousands-separators
*
* @param mixed number
* @return string
*/
formatNumeric: function(number, decimalPlaces) {
number = String(WCF.Number.round(number, decimalPlaces || 2));
var numberParts = number.split('.');
number = this.addThousandsSeparator(numberParts[0]);
if (numberParts.length > 1) number += WCF.Language.get('wcf.global.decimalPoint') + numberParts[1];
number = number.replace('-', '\u2212');
return number;
},
/**
* Makes a string's first character lowercase
*
* @param string string
* @return string
*/
lcfirst: function(string) {
return String(string).substring(0, 1).toLowerCase() + string.substring(1);
},
/**
* Makes a string's first character uppercase
*
* @param string string
* @return string
*/
ucfirst: function(string) {
return String(string).substring(0, 1).toUpperCase() + string.substring(1);
},
/**
* Unescapes special HTML-characters within a string
*
* @param string string
* @return string
*/
unescapeHTML: function (string) {
return String(string).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
};
/**
* Basic implementation for WCF TabMenus. Use the data attributes 'active' to specify the
* tab which should be shown on init. Furthermore you may specify a 'store' data-attribute
* which will be filled with the currently selected tab.
*/
WCF.TabMenu = {
/**
* Initializes all TabMenus
*/
init: function() {
require(['WoltLabSuite/Core/Ui/TabMenu'], function(UiTabMenu) {
UiTabMenu.setup();
});
},
/**
* Reloads the tab menus.
*/
reload: function() {
this.init();
}
};
/**
* Templates that may be fetched more than once with different variables.
* Based upon ideas from Prototype's template.
*
* Usage:
* var myTemplate = new WCF.Template('{$hello} World');
* myTemplate.fetch({ hello: 'Hi' }); // Hi World
* myTemplate.fetch({ hello: 'Hello' }); // Hello World
*
* my2ndTemplate = new WCF.Template('{@$html}{$html}');
* my2ndTemplate.fetch({ html: '<b>Test</b>' }); // <b>Test</b><b>Test</b>
*
* var my3rdTemplate = new WCF.Template('You can use {literal}{$variable}{/literal}-Tags here');
* my3rdTemplate.fetch({ variable: 'Not shown' }); // You can use {$variable}-Tags here
*
* @param template template-content
* @see https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/template.js
*/
WCF.Template = Class.extend({
/**
* Prepares template
*
* @param $template template-content
*/
init: function(template) {
var $literals = new WCF.Dictionary();
var $tagID = 0;
// escape \ and ' and newlines
template = template.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/(\r\n|\n|\r)/g, '\\n');
// save literal-tags
template = template.replace(/\{literal\}(.*?)\{\/literal\}/g, $.proxy(function(match) {
// hopefully no one uses this string in one of his templates
var id = '@@@@@@@@@@@'+Math.random()+'@@@@@@@@@@@';
$literals.add(id, match.replace(/\{\/?literal\}/g, ''));
return id;
}, this));
// remove comments
template = template.replace(/\{\*.*?\*\}/g, '');
var parseParameterList = function(parameterString) {
var $chars = parameterString.split('');
var $parameters = { };
var $inName = true;
var $name = '';
var $value = '';
var $doubleQuoted = false;
var $singleQuoted = false;
var $escaped = false;
for (var $i = 0, $max = $chars.length; $i < $max; $i++) {
var $char = $chars[$i];
if ($inName && $char != '=' && $char != ' ') $name += $char;
else if ($inName && $char == '=') {
$inName = false;
$singleQuoted = false;
$doubleQuoted = false;
$escaped = false;
}
else if (!$inName && !$singleQuoted && !$doubleQuoted && $char == ' ') {
$inName = true;
$parameters[$name] = $value;
$value = $name = '';
}
else if (!$inName && $singleQuoted && !$escaped && $char == "'") {
$singleQuoted = false;
$value += $char;
}
else if (!$inName && !$singleQuoted && !$doubleQuoted && $char == "'") {
$singleQuoted = true;
$value += $char;
}
else if (!$inName && $doubleQuoted && !$escaped && $char == '"') {
$doubleQuoted = false;
$value += $char;
}
else if (!$inName && !$singleQuoted && !$doubleQuoted && $char == '"') {
$doubleQuoted = true;
$value += $char;
}
else if (!$inName && ($doubleQuoted || $singleQuoted) && !$escaped && $char == '\\') {
$escaped = true;
$value += $char;
}
else if (!$inName) {
$escaped = false;
$value += $char;
}
}
$parameters[$name] = $value;
if ($doubleQuoted || $singleQuoted || $escaped) throw new Error('Syntax error in parameterList: "' + parameterString + '"');
return $parameters;
};
var unescape = function(string) {
return string.replace(/\\n/g, "\n").replace(/\\\\/g, '\\').replace(/\\'/g, "'");
};
template = template.replace(/\{(\$[^\}]+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "' + WCF.String.escapeHTML(" + content + ") + '";
})
// Numeric Variable
.replace(/\{#(\$[^\}]+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "' + WCF.String.formatNumeric(" + content + ") + '";
})
// Variable without escaping
.replace(/\{@(\$[^\}]+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "' + " + content + " + '";
})
// {lang}foo{/lang}
.replace(/\{lang\}(.+?)\{\/lang\}/g, function(_, content) {
return "' + WCF.Language.get('" + content + "', v) + '";
})
// {include}
.replace(/\{include (.+?)\}/g, function(_, content) {
content = content.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
var $parameters = parseParameterList(content);
if (typeof $parameters['file'] === 'undefined') throw new Error('Missing file attribute in include-tag');
$parameters['file'] = $parameters['file'].replace(/\$([^.\[\(\)\]\s]+)/g, "(v.$1)");
return "' + " + $parameters['file'] + ".fetch(v) + '";
})
// {if}
.replace(/\{if (.+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "';\n" +
"if (" + content + ") {\n" +
" $output += '";
})
// {elseif}
.replace(/\{else ?if (.+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "';\n" +
"}\n" +
"else if (" + content + ") {\n" +
" $output += '";
})
// {implode}
.replace(/\{implode (.+?)\}/g, function(_, content) {
$tagID++;
content = content.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
var $parameters = parseParameterList(content);
if (typeof $parameters['from'] === 'undefined') throw new Error('Missing from attribute in implode-tag');
if (typeof $parameters['item'] === 'undefined') throw new Error('Missing item attribute in implode-tag');
if (typeof $parameters['glue'] === 'undefined') $parameters['glue'] = "', '";
$parameters['from'] = $parameters['from'].replace(/\$([^.\[\(\)\]\s]+)/g, "(v.$1)");
return "';\n"+
"var $implode_" + $tagID + " = false;\n" +
"for ($implodeKey_" + $tagID + " in " + $parameters['from'] + ") {\n" +
" v[" + $parameters['item'] + "] = " + $parameters['from'] + "[$implodeKey_" + $tagID + "];\n" +
(typeof $parameters['key'] !== 'undefined' ? " v[" + $parameters['key'] + "] = $implodeKey_" + $tagID + ";\n" : "") +
" if ($implode_" + $tagID + ") $output += " + $parameters['glue'] + ";\n" +
" $implode_" + $tagID + " = true;\n" +
" $output += '";
})
// {foreach}
.replace(/\{foreach (.+?)\}/g, function(_, content) {
$tagID++;
content = content.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
var $parameters = parseParameterList(content);
if (typeof $parameters['from'] === 'undefined') throw new Error('Missing from attribute in foreach-tag');
if (typeof $parameters['item'] === 'undefined') throw new Error('Missing item attribute in foreach-tag');
$parameters['from'] = $parameters['from'].replace(/\$([^.\[\(\)\]\s]+)/g, "(v.$1)");
return "';\n" +
"$foreach_"+$tagID+" = false;\n" +
"for ($foreachKey_" + $tagID + " in " + $parameters['from'] + ") {\n" +
" $foreach_"+$tagID+" = true;\n" +
" break;\n" +
"}\n" +
"if ($foreach_"+$tagID+") {\n" +
" for ($foreachKey_" + $tagID + " in " + $parameters['from'] + ") {\n" +
" v[" + $parameters['item'] + "] = " + $parameters['from'] + "[$foreachKey_" + $tagID + "];\n" +
(typeof $parameters['key'] !== 'undefined' ? " v[" + $parameters['key'] + "] = $foreachKey_" + $tagID + ";\n" : "") +
" $output += '";
})
// {foreachelse}
.replace(/\{foreachelse\}/g,
"';\n" +
" }\n" +
"}\n" +
"else {\n" +
" {\n" +
" $output += '"
)
// {/foreach}
.replace(/\{\/foreach\}/g,
"';\n" +
" }\n" +
"}\n" +
"$output += '"
)
// {else}
.replace(/\{else\}/g,
"';\n" +
"}\n" +
"else {\n" +
" $output += '"
)
// {/if} and {/implode}
.replace(/\{\/(if|implode)\}/g,
"';\n" +
"}\n" +
"$output += '"
);
// call callback
for (var key in WCF.Template.callbacks) {
template = WCF.Template.callbacks[key](template);
}
// insert delimiter tags
template = template.replace('{ldelim}', '{').replace('{rdelim}', '}');
$literals.each(function(pair) {
template = template.replace(pair.key, pair.value);
});
template = "$output += '" + template + "';";
try {
this.fetch = new Function("v", "v = window.$.extend({}, v, { __wcf: window.WCF, __window: window }); var $output = ''; " + template + ' return $output;');
}
catch (e) {
console.debug("var $output = ''; " + template + ' return $output;');
throw e;
}
},
/**
* Fetches the template with the given variables.
*
* @param v variables to insert
* @return parsed template
*/
fetch: function(v) {
// this will be replaced in the init function
}
});
/**
* Array of callbacks that will be called after parsing the included tags. Only applies to Templates compiled after the callback was added.
*
* @var array<Function>
*/
WCF.Template.callbacks = [ ];
/**
* Toggles options.
*
* @param string element
* @param array showItems
* @param array hideItems
* @param function callback
*/
WCF.ToggleOptions = Class.extend({
/**
* target item
*
* @var jQuery
*/
_element: null,
/**
* list of items to be shown
*
* @var array
*/
_showItems: [],
/**
* list of items to be hidden
*
* @var array
*/
_hideItems: [],
/**
* callback after options were toggled
*
* @var function
*/
_callback: null,
/**
* Initializes option toggle.
*
* @param string element
* @param array showItems
* @param array hideItems
* @param function callback
*/
init: function(element, showItems, hideItems, callback) {
this._element = $('#' + element);
this._showItems = showItems;
this._hideItems = hideItems;
if (callback !== undefined) {
this._callback = callback;
}
// bind event
this._element.click($.proxy(this._toggle, this));
// execute toggle on init
this._toggle();
},
/**
* Toggles items.
*/
_toggle: function() {
if (!this._element.prop('checked')) return;
for (var $i = 0, $length = this._showItems.length; $i < $length; $i++) {
var $item = this._showItems[$i];
$('#' + $item).show();
}
for (var $i = 0, $length = this._hideItems.length; $i < $length; $i++) {
var $item = this._hideItems[$i];
$('#' + $item).hide();
}
if (this._callback !== null) {
this._callback();
}
}
});
/**
* Namespace for all kind of collapsible containers.
*/
WCF.Collapsible = {};
/**
* Simple implementation for collapsible content, neither does it
* store its state nor does it allow AJAX callbacks to fetch content.
*/
WCF.Collapsible.Simple = {
/**
* Initializes collapsibles.
*/
init: function() {
$('.jsCollapsible').each($.proxy(function(index, button) {
this._initButton(button);
}, this));
},
/**
* Binds an event listener on all buttons triggering the collapsible.
*
* @param object button
*/
_initButton: function(button) {
var $button = $(button);
var $isOpen = $button.data('isOpen');
if (!$isOpen) {
// hide container on init
$('#' + $button.data('collapsibleContainer')).hide();
}
$button.click($.proxy(this._toggle, this));
},
/**
* Toggles collapsible containers on click.
*
* @param object event
*/
_toggle: function(event) {
var $button = $(event.currentTarget);
var $isOpen = $button.data('isOpen');
var $target = $('#' + $.wcfEscapeID($button.data('collapsibleContainer')));
if ($isOpen) {
$target.stop().wcfBlindOut('vertical', $.proxy(function() {
this._toggleImage($button);
}, this));
$isOpen = false;
}
else {
$target.stop().wcfBlindIn('vertical', $.proxy(function() {
this._toggleImage($button);
}, this));
$isOpen = true;
}
$button.data('isOpen', $isOpen);
// suppress event
event.stopPropagation();
return false;
},
/**
* Toggles image of target button.
*
* @param jQuery button
*/
_toggleImage: function(button) {
var $icon = button.find('span.icon');
if (button.data('isOpen')) {
$icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
}
else {
$icon.removeClass('fa-chevron-down').addClass('fa-chevron-right');
}
}
};
/**
* Basic implementation for collapsible containers with AJAX support. Results for open
* and closed state will be cached.
*
* @param string className
*/
WCF.Collapsible.Remote = Class.extend({
/**
* class name
* @var string
*/
_className: '',
/**
* list of active containers
* @var object
*/
_containers: {},
/**
* container meta data
* @var object
*/
_containerData: {},
/**
* action proxy
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* Initializes the controller for collapsible containers with AJAX support.
*
* @param string className
*/
init: function(className) {
this._className = className;
this._proxy = new WCF.Action.Proxy({
success: $.proxy(this._success, this)
});
// initialize each container
this._init();
WCF.DOMNodeInsertedHandler.addCallback('WCF.Collapsible.Remote', $.proxy(this._init, this));
},
/**
* Initializes a collapsible container.
*
* @param string containerID
*/
_init: function(containerID) {
this._getContainers().each($.proxy(function(index, container) {
var $container = $(container);
var $containerID = $container.wcfIdentify();
if (this._containers[$containerID] === undefined) {
this._containers[$containerID] = $container;
this._initContainer($containerID);
}
}, this));
},
/**
* Initializes a collapsible container.
*
* @param string containerID
*/
_initContainer: function(containerID) {
var $target = this._getTarget(containerID);
var $buttonContainer = this._getButtonContainer(containerID);
var $button = this._createButton(containerID, $buttonContainer);
// store container meta data
this._containerData[containerID] = {
button: $button,
buttonContainer: $buttonContainer,
isOpen: this._containers[containerID].data('isOpen'),
target: $target
};
// add 'jsCollapsed' CSS class
if (!this._containers[containerID].data('isOpen')) {
$('#' + containerID).addClass('jsCollapsed');
}
},
/**
* Returns a collection of collapsible containers.
*
* @return jQuery
*/
_getContainers: function() { },
/**
* Returns the target element for current collapsible container.
*
* @param integer containerID
* @return jQuery
*/
_getTarget: function(containerID) { },
/**
* Returns the button container for current collapsible container.
*
* @param integer containerID
* @return jQuery
*/
_getButtonContainer: function(containerID) { },
/**
* Creates the toggle button.
*
* @param integer containerID
* @param jQuery buttonContainer
*/
_createButton: function(containerID, buttonContainer) {
var $isOpen = this._containers[containerID].data('isOpen');
var $button = $('<span class="collapsibleButton jsTooltip pointer icon icon16 fa-chevron-down" title="'+WCF.Language.get('wcf.global.button.collapsible')+'">').prependTo(buttonContainer);
$button.data('containerID', containerID).click($.proxy(this._toggleContainer, this));
return $button;
},
/**
* Toggles a container.
*
* @param object event
*/
_toggleContainer: function(event) {
var $button = $(event.currentTarget);
var $containerID = $button.data('containerID');
var $isOpen = this._containerData[$containerID].isOpen;
var $state = ($isOpen) ? 'open' : 'close';
var $newState = ($isOpen) ? 'close' : 'open';
// fetch content state via AJAX
this._proxy.setOption('data', {
actionName: 'loadContainer',
className: this._className,
interfaceName: 'wcf\\data\\ILoadableContainerAction',
objectIDs: [ this._getObjectID($containerID) ],
parameters: $.extend(true, {
containerID: $containerID,
currentState: $state,
newState: $newState
}, this._getAdditionalParameters($containerID))
});
this._proxy.sendRequest();
// toogle 'jsCollapsed' CSS class
$('#' + $containerID).toggleClass('jsCollapsed');
// set spinner for current button
// this._exchangeIcon($button);
},
/**
* Exchanges button icon.
*
* @param jQuery button
* @param string newIcon
*/
_exchangeIcon: function(button, newIcon) {
newIcon = newIcon || 'spinner';
button.removeClass('fa-chevron-down fa-chevron-right fa-spinner').addClass('fa-' + newIcon);
},
/**
* Returns the object id for current container.
*
* @param integer containerID
* @return integer
*/
_getObjectID: function(containerID) {
return $('#' + containerID).data('objectID');
},
/**
* Returns additional parameters.
*
* @param integer containerID
* @return object
*/
_getAdditionalParameters: function(containerID) {
return {};
},
/**
* Updates container content.
*
* @param integer containerID
* @param string newContent
* @param string newState
*/
_updateContent: function(containerID, newContent, newState) {
this._containerData[containerID].target.html(newContent);
},
/**
* Sets content upon successfull AJAX request.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
// validate container id
if (!data.returnValues.containerID) return;
var $containerID = data.returnValues.containerID;
// check if container id is known
if (!this._containers[$containerID]) return;
// update content storage
this._containerData[$containerID].isOpen = (data.returnValues.isOpen) ? true : false;
var $newState = (data.returnValues.isOpen) ? 'open' : 'close';
// update container content
this._updateContent($containerID, $.trim(data.returnValues.content), $newState);
// update icon
this._exchangeIcon(this._containerData[$containerID].button, (data.returnValues.isOpen ? 'chevron-down' : 'chevron-right'));
}
});
/**
* Basic implementation for collapsible containers with AJAX support. Requires collapsible
* content to be available in DOM already, if you want to load content on the fly use
* WCF.Collapsible.Remote instead.
*/
WCF.Collapsible.SimpleRemote = WCF.Collapsible.Remote.extend({
/**
* Initializes an AJAX-based collapsible handler.
*
* @param string className
*/
init: function(className) {
this._super(className);
// override settings for action proxy
this._proxy = new WCF.Action.Proxy({
showLoadingOverlay: false
});
},
/**
* @see WCF.Collapsible.Remote._initContainer()
*/
_initContainer: function(containerID) {
this._super(containerID);
// hide container on init if applicable
if (!this._containerData[containerID].isOpen) {
this._containerData[containerID].target.hide();
this._exchangeIcon(this._containerData[containerID].button, 'chevron-right');
}
},
/**
* Toggles container visibility.
*
* @param object event
*/
_toggleContainer: function(event) {
var $button = $(event.currentTarget);
var $containerID = $button.data('containerID');
var $isOpen = this._containerData[$containerID].isOpen;
var $currentState = ($isOpen) ? 'open' : 'close';
var $newState = ($isOpen) ? 'close' : 'open';
this._proxy.setOption('data', {
actionName: 'toggleContainer',
className: this._className,
interfaceName: 'wcf\\data\\IToggleContainerAction',
objectIDs: [ this._getObjectID($containerID) ],
parameters: $.extend(true, {
containerID: $containerID,
currentState: $currentState,
newState: $newState
}, this._getAdditionalParameters($containerID))
});
this._proxy.sendRequest();
// exchange icon
this._exchangeIcon(this._containerData[$containerID].button, ($newState === 'open' ? 'chevron-down' : 'chevron-right'));
// toggle container
if ($newState === 'open') {
this._containerData[$containerID].target.show();
}
else {
this._containerData[$containerID].target.hide();
}
// toogle 'jsCollapsed' CSS class
$('#' + $containerID).toggleClass('jsCollapsed');
// update container data
this._containerData[$containerID].isOpen = ($newState === 'open' ? true : false);
}
});
/**
* Holds userdata of the current user
*
* @deprecated use WCF/WoltLab/User
*/
WCF.User = {
/**
* id of the active user
* @var integer
*/
userID: 0,
/**
* name of the active user
* @var string
*/
username: '',
/**
* Initializes userdata
*
* @param integer userID
* @param string username
*/
init: function(userID, username) {
this.userID = userID;
this.username = username;
}
};
/**
* Namespace for effect-related functions.
*/
WCF.Effect = {};
/**
* Scrolls to a specific element offset, optionally handling menu height.
*/
WCF.Effect.Scroll = Class.extend({
/**
* Scrolls to a specific element offset.
*
* @param jQuery element
* @param boolean excludeMenuHeight
* @param boolean disableAnimation
* @return boolean
*/
scrollTo: function(element, excludeMenuHeight, disableAnimation) {
if (!element.length) {
return true;
}
var $elementOffset = element.getOffsets('offset').top;
var $documentHeight = $(document).height();
var $windowHeight = $(window).height();
if ($elementOffset > $documentHeight - $windowHeight) {
$elementOffset = $documentHeight - $windowHeight;
if ($elementOffset < 0) {
$elementOffset = 0;
}
}
if (disableAnimation === true) {
$('html,body').scrollTop($elementOffset);
}
else {
$('html,body').animate({ scrollTop: $elementOffset }, 400, function (x, t, b, c, d) {
return -c * ( ( t = t / d - 1 ) * t * t * t - 1) + b;
});
}
return false;
}
});
/**
* Handles clicks outside an overlay, hitting body-tag through bubbling.
*
* You should always remove callbacks before disposing the attached element,
* preventing errors from blocking the iteration. Furthermore you should
* always handle clicks on your overlay's container and return 'false' to
* prevent bubbling.
*
* @deprecated 3.0 - please use `Ui/CloseOverlay` instead
*/
WCF.CloseOverlayHandler = {
/**
* Adds a new callback.
*
* @param string identifier
* @param object callback
*/
addCallback: function(identifier, callback) {
require(['Ui/CloseOverlay'], function(UiCloseOverlay) {
UiCloseOverlay.add(identifier, callback);
});
},
/**
* Removes a callback from list.
*
* @param string identifier
*/
removeCallback: function(identifier) {
require(['Ui/CloseOverlay'], function(UiCloseOverlay) {
UiCloseOverlay.remove(identifier);
});
},
/**
* Triggers the callbacks programmatically.
*/
forceExecution: function() {
require(['Ui/CloseOverlay'], function(UiCloseOverlay) {
UiCloseOverlay.execute();
});
}
};
/**
* @deprecated Use WoltLabSuite/Core/Dom/Change/Listener
*/
WCF.DOMNodeInsertedHandler = {
addCallback: function(identifier, callback) {
require(['WoltLabSuite/Core/Dom/Change/Listener'], function (ChangeListener) {
ChangeListener.add('__legacy__', callback);
});
},
_executeCallbacks: function() {
require(['WoltLabSuite/Core/Dom/Change/Listener'], function (ChangeListener) {
ChangeListener.trigger();
});
},
execute: function() {
this._executeCallbacks();
}
};
/**
* Notifies objects once a DOM node was removed.
*/
WCF.DOMNodeRemovedHandler = {
/**
* list of callbacks
* @var WCF.Dictionary
*/
_callbacks: new WCF.Dictionary(),
/**
* prevent infinite loop if a callback manipulates DOM
* @var boolean
*/
_isExecuting: false,
/**
* indicates that overlay handler is listening to DOMNodeRemoved events on body-tag
* @var boolean
*/
_isListening: false,
/**
* Adds a new callback.
*
* @param string identifier
* @param object callback
*/
addCallback: function(identifier, callback) {
this._bindListener();
if (this._callbacks.isset(identifier)) {
console.debug("[WCF.DOMNodeRemovedHandler] identifier '" + identifier + "' is already bound to a callback");
return false;
}
this._callbacks.add(identifier, callback);
},
/**
* Removes a callback from list.
*
* @param string identifier
*/
removeCallback: function(identifier) {
if (this._callbacks.isset(identifier)) {
this._callbacks.remove(identifier);
}
},
/**
* Binds click event handler.
*/
_bindListener: function() {
if (this._isListening) return;
if (window.MutationObserver) {
var $mutationObserver = new MutationObserver((function(mutations) {
var $triggerEvent = false;
mutations.forEach((function(mutation) {
if (mutation.removedNodes.length) {
$triggerEvent = true;
}
}).bind(this));
if ($triggerEvent) {
this._executeCallbacks({ });
}
}).bind(this));
$mutationObserver.observe(document.body, {
childList: true,
subtree: true
});
}
else {
$(document).bind('DOMNodeRemoved', $.proxy(this._executeCallbacks, this));
}
this._isListening = true;
},
/**
* Executes callbacks if a DOM node is removed.
*/
_executeCallbacks: function(event) {
if (this._isExecuting) return;
// do not track events while executing callbacks
this._isExecuting = true;
this._callbacks.each(function(pair) {
// execute callback
pair.value(event);
});
// enable listener again
this._isExecuting = false;
}
};
/**
* Namespace for option handlers.
*/
WCF.Option = { };
/**
* Handles option selection.
*/
WCF.Option.Handler = Class.extend({
/**
* Initializes the WCF.Option.Handler class.
*/
init: function() {
this._initOptions();
WCF.DOMNodeInsertedHandler.addCallback('WCF.Option.Handler', $.proxy(this._initOptions, this));
},
/**
* Initializes all options.
*/
_initOptions: function() {
$('.jsEnablesOptions').each($.proxy(this._initOption, this));
},
/**
* Initializes an option.
*
* @param integer index
* @param object option
*/
_initOption: function(index, option) {
// execute action on init
this._change(option);
// bind event listener
$(option).change($.proxy(this._handleChange, this));
},
/**
* Applies whenever an option is changed.
*
* @param object event
*/
_handleChange: function(event) {
this._change($(event.target));
},
/**
* Enables or disables options on option value change.
*
* @param object option
*/
_change: function(option) {
option = $(option);
var $disableOptions = eval(option.data('disableOptions'));
var $enableOptions = eval(option.data('enableOptions'));
// determine action by type
switch(option.getTagName()) {
case 'input':
switch(option.attr('type')) {
case 'checkbox':
this._execute(option.prop('checked'), $disableOptions, $enableOptions);
break;
case 'radio':
if (option.prop('checked')) {
var isActive = true;
if (option.data('isBoolean') && option.val() != 1) {
isActive = false;
}
this._execute(isActive, $disableOptions, $enableOptions);
}
break;
}
break;
case 'select':
var $value = option.val();
var $disableOptions = $enableOptions = [];
if (option.data('disableOptions').length > 0) {
for (var $index in option.data('disableOptions')) {
var $item = option.data('disableOptions')[$index];
if ($item.value == $value) {
$disableOptions.push($item.option);
}
}
}
if (option.data('enableOptions').length > 0) {
for (var $index in option.data('enableOptions')) {
var $item = option.data('enableOptions')[$index];
if ($item.value == $value) {
$enableOptions.push($item.option);
}
}
}
this._execute(true, $disableOptions, $enableOptions);
break;
}
},
/**
* Enables or disables options.
*
* @param boolean isActive
* @param array disableOptions
* @param array enableOptions
*/
_execute: function(isActive, disableOptions, enableOptions) {
if (disableOptions.length > 0) {
for (var $i = 0, $size = disableOptions.length; $i < $size; $i++) {
var $target = disableOptions[$i];
if ($.wcfIsset($target)) {
this._enableOption($target, !isActive);
}
else {
var $dl = $('.' + $target + 'Input');
if ($dl.length) {
this._enableOptions($dl.children('dd').find('input, select, textarea'), !isActive);
}
}
}
}
if (enableOptions.length > 0) {
for (var $i = 0, $size = enableOptions.length; $i < $size; $i++) {
var $target = enableOptions[$i];
if ($.wcfIsset($target)) {
this._enableOption($target, isActive);
}
else {
var $dl = $('.' + $target + 'Input');
if ($dl.length) {
this._enableOptions($dl.children('dd').find('input, select, textarea'), isActive);
}
}
}
}
},
/**
* Enables/Disables an option.
*
* @param string target
* @param boolean enable
*/
_enableOption: function(target, enable) {
this._enableOptionElement($('#' + $.wcfEscapeID(target)), enable);
},
/**
* Enables/Disables an option element.
*
* @param string target
* @param boolean enable
*/
_enableOptionElement: function(element, enable) {
element = $(element);
var $tagName = element.getTagName();
if ($tagName == 'select' || ($tagName == 'input' && (element.attr('type') == 'checkbox' || element.attr('type') == 'file' || element.attr('type') == 'radio'))) {
if (enable) element.enable();
else element.disable();
}
else {
if (enable) element.removeAttr('readonly');
else element.attr('readonly', true);
}
if (enable) {
element.closest('dl').removeClass('disabled');
}
else {
element.closest('dl').addClass('disabled');
}
},
/**
* Enables/Disables an option consisting of multiple form elements.
*
* @param string target
* @param boolean enable
*/
_enableOptions: function(targets, enable) {
for (var $i = 0, $length = targets.length; $i < $length; $i++) {
this._enableOptionElement(targets[$i], enable);
}
}
});
WCF.PageVisibilityHandler = {
/**
* list of callbacks
* @var WCF.Dictionary
*/
_callbacks: new WCF.Dictionary(),
/**
* indicates that event listeners are bound
* @var boolean
*/
_isListening: false,
/**
* name of window's hidden property
* @var string
*/
_hiddenFieldName: '',
/**
* Adds a new callback.
*
* @param string identifier
* @param object callback
*/
addCallback: function(identifier, callback) {
this._bindListener();
if (this._callbacks.isset(identifier)) {
console.debug("[WCF.PageVisibilityHandler] identifier '" + identifier + "' is already bound to a callback");
return false;
}
this._callbacks.add(identifier, callback);
},
/**
* Removes a callback from list.
*
* @param string identifier
*/
removeCallback: function(identifier) {
if (this._callbacks.isset(identifier)) {
this._callbacks.remove(identifier);
}
},
/**
* Binds click event handler.
*/
_bindListener: function() {
if (this._isListening) return;
var $eventName = null;
if (typeof document.hidden !== "undefined") {
this._hiddenFieldName = "hidden";
$eventName = "visibilitychange";
}
else if (typeof document.mozHidden !== "undefined") {
this._hiddenFieldName = "mozHidden";
$eventName = "mozvisibilitychange";
}
else if (typeof document.msHidden !== "undefined") {
this._hiddenFieldName = "msHidden";
$eventName = "msvisibilitychange";
}
else if (typeof document.webkitHidden !== "undefined") {
this._hiddenFieldName = "webkitHidden";
$eventName = "webkitvisibilitychange";
}
if ($eventName === null) {
console.debug("[WCF.PageVisibilityHandler] This browser does not support the page visibility API.");
}
else {
$(document).on($eventName, $.proxy(this._executeCallbacks, this));
}
this._isListening = true;
},
/**
* Executes callbacks if page is hidden/visible again.
*/
_executeCallbacks: function(event) {
if (this._isExecuting) return;
// do not track events while executing callbacks
this._isExecuting = true;
var $state = document[this._hiddenFieldName];
this._callbacks.each(function(pair) {
// execute callback
pair.value($state);
});
// enable listener again
this._isExecuting = false;
}
};
/**
* Namespace for table related classes.
*/
WCF.Table = { };
/**
* Handles empty tables which can be used in combination with WCF.Action.Proxy.
*/
WCF.Table.EmptyTableHandler = Class.extend({
/**
* handler options
* @var object
*/
_options: {},
/**
* class name of the relevant rows
* @var string
*/
_rowClassName: '',
/**
* Initalizes a new WCF.Table.EmptyTableHandler object.
*
* @param jQuery tableContainer
* @param string rowClassName
* @param object options
*/
init: function(tableContainer, rowClassName, options) {
this._rowClassName = rowClassName;
this._tableContainer = tableContainer;
this._options = $.extend(true, {
emptyMessage: null,
messageType: 'info',
refreshPage: false,
updatePageNumber: false
}, options || { });
WCF.DOMNodeRemovedHandler.addCallback('WCF.Table.EmptyTableHandler.' + rowClassName, $.proxy(this._remove, this));
},
/**
* Returns the current number of table rows.
*
* @return integer
*/
_getRowCount: function() {
return this._tableContainer.find('table tr.' + this._rowClassName).length;
},
/**
* Handles an empty table.
*/
_handleEmptyTable: function() {
if (this._options.emptyMessage) {
// insert message
this._tableContainer.replaceWith($('<p />').addClass(this._options.messageType).text(this._options.emptyMessage));
}
else if (this._options.refreshPage) {
// refresh page
if (this._options.updatePageNumber) {
// calculate the new page number
var pageNumberURLComponents = window.location.href.match(/(\?|&)pageNo=(\d+)/g);
if (pageNumberURLComponents) {
var currentPageNumber = pageNumberURLComponents[pageNumberURLComponents.length - 1].match(/\d+/g);
if (this._options.updatePageNumber > 0) {
currentPageNumber++;
}
else {
currentPageNumber--;
}
window.location = window.location.href.replace(pageNumberURLComponents[pageNumberURLComponents.length - 1], pageNumberURLComponents[pageNumberURLComponents.length - 1][0] + 'pageNo=' + currentPageNumber);
}
}
else {
window.location.reload();
}
}
else {
// simply remove the table container
this._tableContainer.remove();
}
},
/**
* Handles the removal of a DOM node.
*/
_remove: function(event) {
if ($.getLength(event)) {
var element = $(event.target);
// check if DOM element is relevant
if (element.hasClass(this._rowClassName)) {
var tbody = element.parents('tbody:eq(0)');
// check if table will be empty if DOM node is removed
if (tbody.children('tr').length == 1) {
this._handleEmptyTable();
}
}
}
else if (!this._getRowCount()) {
this._handleEmptyTable();
}
}
});
/**
* Namespace for search related classes.
*/
WCF.Search = {};
/**
* Performs a quick search.
*
* @deprecated 3.0 - please use `WoltLabSuite/Core/Ui/Search/Input` instead
*/
WCF.Search.Base = Class.extend({
/**
* notification callback
* @var object
*/
_callback: null,
/**
* represents index of search string (relative to original caret position)
* @var integer
*/
_caretAt: -1,
/**
* class name
* @var string
*/
_className: '',
/**
* comma seperated list
* @var boolean
*/
_commaSeperated: false,
/**
* delay in miliseconds before a request is send to the server
* @var integer
*/
_delay: 0,
/**
* list with values that are excluded from seaching
* @var array
*/
_excludedSearchValues: [],
/**
* count of available results
* @var integer
*/
_itemCount: 0,
/**
* item index, -1 if none is selected
* @var integer
*/
_itemIndex: -1,
/**
* result list
* @var jQuery
*/
_list: null,
/**
* old search string, used for comparison
* @var array<string>
*/
_oldSearchString: [ ],
/**
* action proxy
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* search input field
* @var jQuery
*/
_searchInput: null,
/**
* minimum search input length, MUST be 1 or higher
* @var integer
*/
_triggerLength: 3,
/**
* delay timer
* @var WCF.PeriodicalExecuter
*/
_timer: null,
/**
* Initializes a new search.
*
* @param jQuery searchInput
* @param object callback
* @param array excludedSearchValues
* @param boolean commaSeperated
* @param boolean showLoadingOverlay
*/
init: function(searchInput, callback, excludedSearchValues, commaSeperated, showLoadingOverlay) {
if (callback !== null && callback !== undefined && !$.isFunction(callback)) {
console.debug("[WCF.Search.Base] The given callback is invalid, aborting.");
return;
}
this._callback = (callback) ? callback : null;
this._caretAt = -1;
this._delay = 0;
this._excludedSearchValues = [];
if (excludedSearchValues) {
this._excludedSearchValues = excludedSearchValues;
}
this._searchInput = $(searchInput);
if (!this._searchInput.length) {
console.debug("[WCF.Search.Base] Selector '" + searchInput + "' for search input is invalid, aborting.");
return;
}
this._searchInput.keydown($.proxy(this._keyDown, this)).keyup($.proxy(this._keyUp, this)).wrap('<span class="dropdown" />');
if ($.browser.mozilla && $.browser.touch) {
this._searchInput.on('input', $.proxy(this._keyUp, this));
}
this._list = $('<ul class="dropdownMenu" />').insertAfter(this._searchInput);
this._commaSeperated = (commaSeperated) ? true : false;
this._oldSearchString = [ ];
this._itemCount = 0;
this._itemIndex = -1;
this._proxy = new WCF.Action.Proxy({
showLoadingOverlay: (showLoadingOverlay !== true ? false : true),
success: $.proxy(this._success, this),
autoAbortPrevious: true
});
if (this._searchInput.is('input')) {
this._searchInput.attr('autocomplete', 'off');
}
this._searchInput.blur($.proxy(this._blur, this));
WCF.Dropdown.initDropdownFragment(this._searchInput.parent(), this._list);
},
/**
* Closes the dropdown after a short delay.
*/
_blur: function() {
var self = this;
new WCF.PeriodicalExecuter(function(pe) {
if (self._list.is(':visible')) {
self._clearList(false);
}
pe.stop();
}, 250);
},
/**
* Blocks execution of 'Enter' event.
*
* @param object event
*/
_keyDown: function(event) {
if (event.which === $.ui.keyCode.ENTER) {
var $dropdown = this._searchInput.parents('.dropdown');
if ($dropdown.data('disableAutoFocus')) {
if (this._itemIndex !== -1) {
event.preventDefault();
}
}
else if ($dropdown.data('preventSubmit') || this._itemIndex !== -1) {
event.preventDefault();
}
}
},
/**
* Performs a search upon key up.
*
* @param object event
*/
_keyUp: function(event) {
// handle arrow keys and return key
switch (event.which) {
case 37: // arrow-left
case 39: // arrow-right
return;
break;
case 38: // arrow up
this._selectPreviousItem();
return;
break;
case 40: // arrow down
this._selectNextItem();
return;
break;
case 13: // return key
return this._selectElement(event);
break;
}
var $content = this._getSearchString(event);
if ($content === '') {
this._clearList(false);
}
else if ($content.length >= this._triggerLength) {
var $parameters = {
data: {
excludedSearchValues: this._excludedSearchValues,
searchString: $content
}
};
if (this._delay) {
if (this._timer !== null) {
this._timer.stop();
}
var self = this;
this._timer = new WCF.PeriodicalExecuter(function() {
self._queryServer($parameters);
self._timer.stop();
self._timer = null;
}, this._delay);
}
else {
this._queryServer($parameters);
}
}
else {
// input below trigger length
this._clearList(false);
}
},
/**
* Queries the server.
*
* @param object parameters
*/
_queryServer: function(parameters) {
this._searchInput.parents('.searchBar').addClass('loading');
this._proxy.setOption('data', {
actionName: 'getSearchResultList',
className: this._className,
interfaceName: 'wcf\\data\\ISearchAction',
parameters: this._getParameters(parameters)
});
this._proxy.sendRequest();
},
/**
* Sets query delay in miliseconds.
*
* @param integer delay
*/
setDelay: function(delay) {
this._delay = delay;
},
/**
* Selects the next item in list.
*/
_selectNextItem: function() {
if (this._itemCount === 0) {
return;
}
// remove previous marking
this._itemIndex++;
if (this._itemIndex === this._itemCount) {
this._itemIndex = 0;
}
this._highlightSelectedElement();
},
/**
* Selects the previous item in list.
*/
_selectPreviousItem: function() {
if (this._itemCount === 0) {
return;
}
this._itemIndex--;
if (this._itemIndex === -1) {
this._itemIndex = this._itemCount - 1;
}
this._highlightSelectedElement();
},
/**
* Highlights the active item.
*/
_highlightSelectedElement: function() {
this._list.find('li').removeClass('dropdownNavigationItem');
this._list.find('li:eq(' + this._itemIndex + ')').addClass('dropdownNavigationItem');
},
/**
* Selects the active item by pressing the return key.
*
* @param object event
* @return boolean
*/
_selectElement: function(event) {
if (this._itemCount === 0) {
return true;
}
this._list.find('li.dropdownNavigationItem').trigger('click');
return false;
},
/**
* Returns search string.
*
* @return string
*/
_getSearchString: function(event) {
var $searchString = $.trim(this._searchInput.val());
if (this._commaSeperated) {
var $keyCode = event.keyCode || event.which;
if ($keyCode == $.ui.keyCode.COMMA) {
// ignore event if char is ','
return '';
}
var $current = $searchString.split(',');
var $length = $current.length;
for (var $i = 0; $i < $length; $i++) {
// remove whitespaces at the beginning or end
$current[$i] = $.trim($current[$i]);
}
for (var $i = 0; $i < $length; $i++) {
var $part = $current[$i];
if (this._oldSearchString[$i]) {
// compare part
if ($part != this._oldSearchString[$i]) {
// current part was changed
$searchString = $part;
this._caretAt = $i;
break;
}
}
else {
// new part was added
$searchString = $part;
break;
}
}
this._oldSearchString = $current;
}
return $searchString;
},
/**
* Returns parameters for quick search.
*
* @param object parameters
* @return object
*/
_getParameters: function(parameters) {
return parameters;
},
/**
* Evalutes search results.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
this._clearList(false);
this._searchInput.parents('.searchBar').removeClass('loading');
if ($.getLength(data.returnValues)) {
for (var $i in data.returnValues) {
var $item = data.returnValues[$i];
this._createListItem($item);
}
}
else if (!this._handleEmptyResult()) {
return;
}
WCF.CloseOverlayHandler.addCallback('WCF.Search.Base', $.proxy(function() { this._clearList(); }, this));
var $containerID = this._searchInput.parents('.dropdown').wcfIdentify();
if (!WCF.Dropdown.getDropdownMenu($containerID).hasClass('dropdownOpen')) {
WCF.Dropdown.toggleDropdown($containerID);
}
// pre-select first item
this._itemIndex = -1;
if (!WCF.Dropdown.getDropdown($containerID).data('disableAutoFocus')) {
this._selectNextItem();
}
},
/**
* Handles empty result lists, should return false if dropdown should be hidden.
*
* @return boolean
*/
_handleEmptyResult: function() {
return false;
},
/**
* Creates a new list item.
*
* @param object item
* @return jQuery
*/
_createListItem: function(item) {
var $listItem = $('<li><span>' + WCF.String.escapeHTML(item.label) + '</span></li>').appendTo(this._list);
$listItem.data('objectID', item.objectID).data('label', item.label).click($.proxy(this._executeCallback, this));
this._itemCount++;
return $listItem;
},
/**
* Executes callback upon result click.
*
* @param object event
*/
_executeCallback: function(event) {
var $clearSearchInput = false;
var $listItem = $(event.currentTarget);
// notify callback
if (this._commaSeperated) {
// auto-complete current part
var $result = $listItem.data('label');
this._oldSearchString[this._caretAt] = $result;
this._searchInput.val(this._oldSearchString.join(', '));
if ($.browser.webkit) {
// chrome won't display the new value until the textarea is rendered again
// this quick fix forces chrome to render it again, even though it changes nothing
this._searchInput.css({ display: 'block' });
}
// set focus on input field again
var $position = this._searchInput.val().toLowerCase().indexOf($result.toLowerCase()) + $result.length;
this._searchInput.focus().setCaret($position);
}
else {
if (this._callback === null) {
this._searchInput.val($listItem.data('label'));
}
else {
$clearSearchInput = (this._callback($listItem.data()) === true) ? true : false;
}
}
// close list and revert input
this._clearList($clearSearchInput);
},
/**
* Closes the suggestion list and clears search input on demand.
*
* @param boolean clearSearchInput
*/
_clearList: function(clearSearchInput) {
if (clearSearchInput && !this._commaSeperated) {
this._searchInput.val('');
}
// close dropdown
WCF.Dropdown.getDropdown(this._searchInput.parents('.dropdown').wcfIdentify()).removeClass('dropdownOpen');
WCF.Dropdown.getDropdownMenu(this._searchInput.parents('.dropdown').wcfIdentify()).removeClass('dropdownOpen');
this._list.end().empty();
WCF.CloseOverlayHandler.removeCallback('WCF.Search.Base');
// reset item navigation
this._itemCount = 0;
this._itemIndex = -1;
},
/**
* Adds an excluded search value.
*
* @param string value
*/
addExcludedSearchValue: function(value) {
if (!WCF.inArray(value, this._excludedSearchValues)) {
this._excludedSearchValues.push(value);
}
},
/**
* Removes an excluded search value.
*
* @param string value
*/
removeExcludedSearchValue: function(value) {
var index = $.inArray(value, this._excludedSearchValues);
if (index != -1) {
this._excludedSearchValues.splice(index, 1);
}
}
});
/**
* Provides quick search for users and user groups.
*
* @see WCF.Search.Base
* @deprecated 3.0 - please use `WoltLabSuite/Core/Ui/User/Search/Input` instead
*/
WCF.Search.User = WCF.Search.Base.extend({
/**
* @see WCF.Search.Base._className
*/
_className: 'wcf\\data\\user\\UserAction',
/**
* include user groups in search
* @var boolean
*/
_includeUserGroups: false,
/**
* @see WCF.Search.Base.init()
*/
init: function(searchInput, callback, includeUserGroups, excludedSearchValues, commaSeperated) {
this._includeUserGroups = includeUserGroups;
this._super(searchInput, callback, excludedSearchValues, commaSeperated);
},
/**
* @see WCF.Search.Base._getParameters()
*/
_getParameters: function(parameters) {
parameters.data.includeUserGroups = this._includeUserGroups ? 1 : 0;
return parameters;
},
/**
* @see WCF.Search.Base._createListItem()
*/
_createListItem: function(item) {
var $listItem = this._super(item);
var $icon = null;
if (item.icon) {
$icon = $(item.icon);
}
else if (this._includeUserGroups && item.type === 'group') {
$icon = $('<span class="icon icon16 fa-users" />');
}
if ($icon) {
var $label = $listItem.find('span').detach();
var $box16 = $('<div />').addClass('box16').appendTo($listItem);
$box16.append($icon);
$box16.append($('<div />').append($label));
}
// insert item type
$listItem.data('type', item.type);
return $listItem;
}
});
/**
* Namespace for system-related classes.
*/
WCF.System = { };
/**
* Namespace for dependency-related classes.
*/
WCF.System.Dependency = { };
/**
* JavaScript Dependency Manager.
*/
WCF.System.Dependency.Manager = {
/**
* list of callbacks grouped by identifier
* @var object
*/
_callbacks: { },
/**
* list of loaded identifiers
* @var array<string>
*/
_loaded: [ ],
/**
* list of setup callbacks grouped by identifier
* @var object
*/
_setupCallbacks: { },
/**
* Registers a callback for given identifier, will be executed after all setup
* callbacks have been invoked.
*
* @param string identifier
* @param object callback
*/
register: function(identifier, callback) {
if (!$.isFunction(callback)) {
console.debug("[WCF.System.Dependency.Manager] Callback for identifier '" + identifier + "' is invalid, aborting.");
return;
}
// already loaded, invoke now
if (WCF.inArray(identifier, this._loaded)) {
setTimeout(function() {
callback();
}, 1);
}
else {
if (!this._callbacks[identifier]) {
this._callbacks[identifier] = [ ];
}
this._callbacks[identifier].push(callback);
}
},
/**
* Registers a setup callback for given identifier, will be invoked
* prior to all other callbacks.
*
* @param string identifier
* @param object callback
*/
setup: function(identifier, callback) {
if (!$.isFunction(callback)) {
console.debug("[WCF.System.Dependency.Manager] Setup callback for identifier '" + identifier + "' is invalid, aborting.");
return;
}
if (!this._setupCallbacks[identifier]) {
this._setupCallbacks[identifier] = [ ];
}
this._setupCallbacks[identifier].push(callback);
},
/**
* Invokes all callbacks for given identifier and marks it as loaded.
*
* @param string identifier
*/
invoke: function(identifier) {
if (this._setupCallbacks[identifier]) {
for (var $i = 0, $length = this._setupCallbacks[identifier].length; $i < $length; $i++) {
this._setupCallbacks[identifier][$i]();
}
delete this._setupCallbacks[identifier];
}
this._loaded.push(identifier);
if (this._callbacks[identifier]) {
for (var $i = 0, $length = this._callbacks[identifier].length; $i < $length; $i++) {
this._callbacks[identifier][$i]();
}
delete this._callbacks[identifier];
}
},
reset: function(identifier) {
var index = this._loaded.indexOf(identifier);
if (index !== -1) {
this._loaded.splice(index, 1);
}
}
};
/**
* Provides flexible dropdowns for tab-based menus.
*/
WCF.System.FlexibleMenu = {
/**
* Initializes the WCF.System.FlexibleMenu class.
*/
init: function() { /* does nothing */ },
/**
* Registers a tab-based menu by id.
*
* Required DOM:
* <container>
* <ul style="white-space: nowrap">
* <li>tab 1</li>
* <li>tab 2</li>
* ...
* <li>tab n</li>
* </ul>
* </container>
*
* @param string containerID
*/
registerMenu: function(containerID) {
require(['WoltLabSuite/Core/Ui/FlexibleMenu'], function(UiFlexibleMenu) {
UiFlexibleMenu.register(containerID);
});
},
/**
* Rebuilds a container, will be automatically invoked on window resize and registering.
*
* @param string containerID
*/
rebuild: function(containerID) {
require(['WoltLabSuite/Core/Ui/FlexibleMenu'], function(UiFlexibleMenu) {
UiFlexibleMenu.rebuild(containerID);
});
}
};
/**
* Namespace for mobile device-related classes.
*/
WCF.System.Mobile = { };
/**
* Stores object references for global access.
*/
WCF.System.ObjectStore = {
/**
* list of objects grouped by identifier
* @var object<array>
*/
_objects: { },
/**
* Adds a new object to the collection.
*
* @param string identifier
* @param object object
*/
add: function(identifier, obj) {
if (this._objects[identifier] === undefined) {
this._objects[identifier] = [ ];
}
this._objects[identifier].push(obj);
},
/**
* Invokes a callback passing the matching objects as a parameter.
*
* @param string identifier
* @param object callback
*/
invoke: function(identifier, callback) {
if (this._objects[identifier]) {
for (var $i = 0; $i < this._objects[identifier].length; $i++) {
callback(this._objects[identifier][$i]);
}
}
}
};
/**
* Stores captcha callbacks used for captchas in AJAX contexts.
*/
WCF.System.Captcha = {
/**
* Adds a callback for a certain captcha.
*
* @param string captchaID
* @param function callback
*/
addCallback: function(captchaID, callback) {
require(['WoltLabSuite/Core/Controller/Captcha'], function(ControllerCaptcha) {
try {
ControllerCaptcha.add(captchaID, callback);
}
catch (e) {
if (e instanceof TypeError) {
console.debug('[WCF.System.Captcha] Given callback is no function');
return;
}
// ignore other errors
}
});
},
/**
* Returns the captcha data for the captcha with the given id.
*
* @return object
*/
getData: function(captchaID) {
var returnValue;
require(['WoltLabSuite/Core/Controller/Captcha'], function(ControllerCaptcha) {
try {
returnValue = ControllerCaptcha.getData(captchaID);
}
catch (e) {
console.debug('[WCF.System.Captcha] Unknow captcha id "' + captchaID + '"');
}
});
return returnValue;
},
/**
* Removes the callback with the given captcha id.
*/
removeCallback: function(captchaID) {
require(['WoltLabSuite/Core/Controller/Captcha'], function(ControllerCaptcha) {
try {
ControllerCaptcha.delete(captchaID);
}
catch (e) {
// ignore errors for unknown captchas
}
});
}
};
WCF.System.Page = { };
/**
* System notification overlays.
*
* @deprecated 3.0 - please use `Ui/Notification` instead
*
* @param string message
* @param string cssClassNames
*/
WCF.System.Notification = Class.extend({
_cssClassNames: '',
_message: '',
/**
* Creates a new system notification overlay.
*
* @param string message
* @param string cssClassNames
*/
init: function(message, cssClassNames) {
this._cssClassNames = cssClassNames || '';
this._message = message || '';
},
/**
* Shows the notification overlay.
*
* @param object callback
* @param integer duration
* @param string message
* @param string cssClassName
*/
show: function(callback, duration, message, cssClassNames) {
require(['Ui/Notification'], (function(UiNotification) {
UiNotification.show(
message || this._message,
callback,
cssClassNames || this._cssClassNames
);
}).bind(this));
}
});
/**
* Provides dialog-based confirmations.
*
* @deprecated 3.0 - please use `Ui/Confirmation` instead
*/
WCF.System.Confirmation = {
/**
* Displays a confirmation dialog.
*
* @param string message
* @param object callback
* @param object parameters
* @param jQuery template
* @param boolean messageIsHtml
*/
show: function(message, callback, parameters, template, messageIsHtml) {
if (typeof template === 'object') {
var $wrapper = $('<div />');
$wrapper.append(template);
template = $wrapper.html();
}
require(['Ui/Confirmation'], function(UiConfirmation) {
UiConfirmation.show({
legacyCallback: callback,
message: message,
parameters: parameters,
template: (template || ''),
messageIsHtml: (messageIsHtml === true)
});
});
}
};
/**
* Disables the ability to scroll the page.
*/
WCF.System.DisableScrolling = {
/**
* number of times scrolling was disabled (nested calls)
* @var integer
*/
_depth: 0,
/**
* old overflow-value of the body element
* @var string
*/
_oldOverflow: null,
/**
* Disables scrolling.
*/
disable: function () {
// do not block scrolling on touch devices
if ($.browser.touch) {
return;
}
if (this._depth === 0) {
this._oldOverflow = $(document.body).css('overflow');
$(document.body).css('overflow', 'hidden');
}
this._depth++;
},
/**
* Enables scrolling again.
* Must be called the same number of times disable() was called to enable scrolling.
*/
enable: function () {
if (this._depth === 0) return;
this._depth--;
if (this._depth === 0) {
$(document.body).css('overflow', this._oldOverflow);
}
}
};
/**
* Disables the ability to zoom the page.
*/
WCF.System.DisableZoom = {
/**
* number of times zoom was disabled (nested calls)
* @var integer
*/
_depth: 0,
/**
* old viewport settings in meta[name=viewport]
* @var string
*/
_oldViewportSettings: null,
/**
* Disables zooming.
*/
disable: function () {
if (this._depth === 0) {
var $meta = $('meta[name=viewport]');
this._oldViewportSettings = $meta.attr('content');
$meta.attr('content', this._oldViewportSettings + ',maximum-scale=1');
}
this._depth++;
},
/**
* Enables scrolling again.
* Must be called the same number of times disable() was called to enable scrolling.
*/
enable: function () {
if (this._depth === 0) return;
this._depth--;
if (this._depth === 0) {
$('meta[name=viewport]').attr('content', this._oldViewportSettings);
}
}
};
/**
* Puts an element into HTML 5 fullscreen mode.
*/
WCF.System.Fullscreen = {
/**
* Puts the given element into full screen mode.
* Note: This must be a raw HTMLElement, not a jQuery wrapped one.
* Note: This must be called from an user triggered event listener for
* security reasons.
*
* @param object Element to show full screen.
*/
enterFullscreen: function (element) {
if (element.requestFullscreen) {
element.requestFullscreen();
}
else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
}
else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
},
/**
* Toggles full screen mode. Either calls `enterFullscreen` with the given
* element, if full screen mode is not active. Calls `exitFullscreen`
* otherwise.
*/
toggleFullscreen: function (element) {
if (this.getFullscreenElement() === null) {
this.enterFullscreen(element);
}
else {
this.exitFullscreen();
}
},
/**
* Retrieves the element that is shown in full screen mode.
* Returns null if either full screen mode is not supported or
* if full screen mode is not active.
*
* @return object
*/
getFullscreenElement: function () {
if (document.fullscreenElement) {
return document.fullscreenElement;
}
else if (document.mozFullScreenElement) {
return document.mozFullScreenElement;
}
else if (document.webkitFullscreenElement) {
return document.webkitFullscreenElement;
}
else if (document.msFullscreenElement) {
return document.msFullscreenElement;
}
return null;
},
/**
* Exits full screen mode.
*/
exitFullscreen: function () {
if (document.exitFullscreen) {
document.exitFullscreen();
}
else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
},
/**
* Returns whether the full screen API is supported in this browser.
*
* @return boolean
*/
isSupported: function () {
if (document.documentElement.requestFullscreen || document.documentElement.msRequestFullscreen || document.documentElement.mozRequestFullScreen || document.documentElement.webkitRequestFullscreen) {
return true;
}
return false;
}
};
/**
* Provides the 'jump to page' overlay.
*
* @deprecated 3.0 - use `WoltLabSuite/Core/Ui/Page/JumpTo` instead
*/
WCF.System.PageNavigation = {
init: function(selector, callback) {
require(['WoltLabSuite/Core/Ui/Page/JumpTo'], function(UiPageJumpTo) {
var elements = elBySelAll(selector);
for (var i = 0, length = elements.length; i < length; i++) {
UiPageJumpTo.init(elements[i], callback);
}
});
}
};
/**
* Sends periodical requests to protect the session from expiring. By default
* it will send a request 1 minute before it would expire.
*
* @param integer seconds
*/
WCF.System.KeepAlive = Class.extend({
/**
* Initializes the WCF.System.KeepAlive class.
*
* @param integer seconds
*/
init: function(seconds) {
new WCF.PeriodicalExecuter(function(pe) {
new WCF.Action.Proxy({
autoSend: true,
data: {
actionName: 'keepAlive',
className: 'wcf\\data\\session\\SessionAction'
},
failure: function() { pe.stop(); },
showLoadingOverlay: false,
success: function(data) {
WCF.System.PushNotification.executeCallbacks(data);
},
suppressErrors: true
});
}, (seconds * 1000));
}
});
/**
* System-wide handler for push notifications.
*/
WCF.System.PushNotification = {
/**
* list of callbacks groupped by type
* @var object<array>
*/
_callbacks: { },
/**
* Adds a callback for a specific notification type.
*
* @param string type
* @param object callback
*/
addCallback: function(type, callback) {
if (this._callbacks[type] === undefined) {
this._callbacks[type] = [ ];
}
this._callbacks[type].push(callback);
},
/**
* Executes all registered callbacks by type.
*
* @param object data
*/
executeCallbacks: function(data) {
for (var $type in data.returnValues) {
if (this._callbacks[$type] !== undefined) {
for (var $i = 0; $i < this._callbacks[$type].length; $i++) {
this._callbacks[$type][$i](data.returnValues[$type]);
}
}
}
}
};
/**
* System-wide event system.
*
* @deprecated 3.0 - please use `EventHandler` instead
*/
WCF.System.Event = {
/**
* Registers a new event listener.
*
* @param string identifier
* @param string action
* @param object listener
* @return string
*/
addListener: function(identifier, action, listener) {
return window.__wcf_bc_eventHandler.add(identifier, action, listener);
},
/**
* Removes a listener, requires the uuid returned by addListener().
*
* @param string identifier
* @param string action
* @param string uuid
* @return boolean
*/
removeListener: function(identifier, action, uuid) {
return window.__wcf_bc_eventHandler.remove(identifier, action, uuid);
},
/**
* Removes all registered event listeners for given identifier and action.
*
* @param string identifier
* @param string action
* @return boolean
*/
removeAllListeners: function(identifier, action) {
return window.__wcf_bc_eventHandler.removeAll(identifier, action);
},
/**
* Fires a new event and notifies all registered event listeners.
*
* @param string identifier
* @param string action
* @param object data
*/
fireEvent: function(identifier, action, data) {
window.__wcf_bc_eventHandler.fire(identifier, action, data);
}
};
/**
* Worker support for frontend based upon DatabaseObjectActions.
*
* @param string className
* @param string title
* @param object parameters
* @param object callback
*/
WCF.System.Worker = Class.extend({
/**
* worker aborted
* @var boolean
*/
_aborted: false,
/**
* DBOAction method name
* @var string
*/
_actionName: '',
/**
* callback invoked after worker completed
* @var object
*/
_callback: null,
/**
* DBOAction class name
* @var string
*/
_className: '',
/**
* dialog object
* @var jQuery
*/
_dialog: null,
/**
* action proxy
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* dialog title
* @var string
*/
_title: '',
/**
* Initializes a new worker instance.
*
* @param string actionName
* @param string className
* @param string title
* @param object parameters
* @param object callback
* @param object confirmMessage
*/
init: function(actionName, className, title, parameters, callback) {
this._aborted = false;
this._actionName = actionName;
this._callback = callback || null;
this._className = className;
this._dialog = null;
this._proxy = new WCF.Action.Proxy({
autoSend: true,
data: {
actionName: this._actionName,
className: this._className,
parameters: parameters || { }
},
showLoadingOverlay: false,
success: $.proxy(this._success, this)
});
this._title = title;
},
/**
* Handles response from server.
*
* @param object data
*/
_success: function(data) {
// init binding
if (this._dialog === null) {
this._dialog = $('<div />').hide().appendTo(document.body);
this._dialog.wcfDialog({
closeConfirmMessage: WCF.Language.get('wcf.worker.abort.confirmMessage'),
closeViaModal: false,
onClose: $.proxy(function() {
this._aborted = true;
this._proxy.abortPrevious();
window.location.reload();
}, this),
title: this._title
});
}
if (this._aborted) {
return;
}
if (data.returnValues.template) {
this._dialog.html(data.returnValues.template);
}
// update progress
this._dialog.find('progress').attr('value', data.returnValues.progress).text(data.returnValues.progress + '%').next('span').text(data.returnValues.progress + '%');
// worker is still busy with its business, carry on
if (data.returnValues.progress < 100) {
// send request for next loop
var $parameters = data.returnValues.parameters || { };
$parameters.loopCount = data.returnValues.loopCount;
this._proxy.setOption('data', {
actionName: this._actionName,
className: this._className,
parameters: $parameters
});
this._proxy.sendRequest();
}
else if (this._callback !== null) {
this._callback(this, data);
}
else {
// exchange icon
this._dialog.find('.fa-spinner').removeClass('fa-spinner').addClass('fa-check green');
this._dialog.find('.contentHeader h1').text(WCF.Language.get('wcf.global.worker.completed'));
// display continue button
var $formSubmit = $('<div class="formSubmit" />').appendTo(this._dialog);
$('<button class="buttonPrimary">' + WCF.Language.get('wcf.global.button.next') + '</button>').appendTo($formSubmit).focus().click(function() {
if (data.returnValues.redirectURL) {
window.location = data.returnValues.redirectURL;
}
else {
window.location.reload();
}
});
this._dialog.wcfDialog('render');
}
}
});
/**
* Default implementation for inline editors.
*
* @param string elementSelector
*/
WCF.InlineEditor = Class.extend({
/**
* list of registered callbacks
* @var array<object>
*/
_callbacks: [ ],
/**
* list of dropdown selections
* @var object
*/
_dropdowns: { },
/**
* list of container elements
* @var object
*/
_elements: { },
/**
* notification object
* @var WCF.System.Notification
*/
_notification: null,
/**
* list of known options
* @var array<object>
*/
_options: [ ],
/**
* action proxy
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* list of trigger elements by element id
* @var object<object>
*/
_triggerElements: { },
/**
* list of data to update upon success
* @var array<object>
*/
_updateData: [ ],
/**
* Initializes a new inline editor.
*/
init: function(elementSelector) {
var $elements = $(elementSelector);
if (!$elements.length) {
return;
}
this._setOptions();
var $quickOption = '';
for (var $i = 0, $length = this._options.length; $i < $length; $i++) {
if (this._options[$i].isQuickOption) {
$quickOption = this._options[$i].optionName;
break;
}
}
var self = this;
$elements.each(function(index, element) {
var $element = $(element);
var $elementID = $element.wcfIdentify();
// find trigger element
var $trigger = self._getTriggerElement($element);
if ($trigger === null || $trigger.length !== 1) {
return;
}
$trigger.on(WCF_CLICK_EVENT, $.proxy(self._show, self)).data('elementID', $elementID);
if ($quickOption) {
// simulate click on target action
$trigger.disableSelection().data('optionName', $quickOption).dblclick($.proxy(self._click, self));
}
// store reference
self._elements[$elementID] = $element;
});
this._proxy = new WCF.Action.Proxy({
success: $.proxy(this._success, this)
});
WCF.CloseOverlayHandler.addCallback('WCF.InlineEditor', $.proxy(this._closeAll, this));
this._notification = new WCF.System.Notification(WCF.Language.get('wcf.global.success'), 'success');
},
/**
* Closes all inline editors.
*/
_closeAll: function() {
for (var $elementID in this._elements) {
this._hide($elementID);
}
},
/**
* Sets options for this inline editor.
*/
_setOptions: function() {
this._options = [ ];
},
/**
* Register an option callback for validation and execution.
*
* @param object callback
*/
registerCallback: function(callback) {
if ($.isFunction(callback)) {
this._callbacks.push(callback);
}
},
/**
* Returns the triggering element.
*
* @param jQuery element
* @return jQuery
*/
_getTriggerElement: function(element) {
return null;
},
/**
* Shows a dropdown menu if options are available.
*
* @param object event
*/
_show: function(event) {
event.preventDefault();
var $elementID = $(event.currentTarget).data('elementID');
// build dropdown
var $trigger = null;
if (!this._dropdowns[$elementID]) {
this._triggerElements[$elementID] = $trigger = this._getTriggerElement(this._elements[$elementID]).addClass('dropdownToggle');
var parent = $trigger[0].parentNode;
if (parent && parent.nodeName === 'LI' && parent.childElementCount === 1) {
// do not add a wrapper element if the trigger is the only child
parent.classList.add('dropdown');
}
else {
$trigger.wrap('<span class="dropdown" />');
}
this._dropdowns[$elementID] = $('<ul class="dropdownMenu" />').insertAfter($trigger);
}
this._dropdowns[$elementID].empty();
// validate options
var $hasOptions = false;
var $lastElementType = '';
for (var $i = 0, $length = this._options.length; $i < $length; $i++) {
var $option = this._options[$i];
if ($option.optionName === 'divider') {
if ($lastElementType !== '' && $lastElementType !== 'divider') {
$('<li class="dropdownDivider" />').appendTo(this._dropdowns[$elementID]);
$lastElementType = $option.optionName;
}
}
else if (this._validate($elementID, $option.optionName) || this._validateCallbacks($elementID, $option.optionName)) {
var $listItem = $('<li><span>' + $option.label + '</span></li>').appendTo(this._dropdowns[$elementID]);
$listItem.data('elementID', $elementID).data('optionName', $option.optionName).data('isQuickOption', ($option.isQuickOption ? true : false)).click($.proxy(this._click, this));
$hasOptions = true;
$lastElementType = $option.optionName;
}
}
if ($hasOptions) {
// if last child is divider, remove it
var $lastChild = this._dropdowns[$elementID].children().last();
if ($lastChild.hasClass('dropdownDivider')) {
$lastChild.remove();
}
// check if only element is a quick option
var $quickOption = null;
var $count = 0;
this._dropdowns[$elementID].children().each(function(index, child) {
var $child = $(child);
if (!$child.hasClass('dropdownDivider')) {
if ($child.data('isQuickOption')) {
$quickOption = $child;
}
else {
$count++;
}
}
});
if (!$count) {
$quickOption.trigger('click');
if (this._triggerElements[$elementID]) {
WCF.Dropdown.close(this._triggerElements[$elementID].parents('.dropdown').wcfIdentify());
}
return false;
}
}
if ($trigger !== null) {
WCF.Dropdown.initDropdown($trigger, true);
}
return false;
},
/**
* Validates an option.
*
* @param string elementID
* @param string optionName
* @returns boolean
*/
_validate: function(elementID, optionName) {
return false;
},
/**
* Validates an option provided by callbacks.
*
* @param string elementID
* @param string optionName
* @return boolean
*/
_validateCallbacks: function(elementID, optionName) {
var $length = this._callbacks.length;
if ($length) {
for (var $i = 0; $i < $length; $i++) {
if (this._callbacks[$i].validate(this._elements[elementID], optionName)) {
return true;
}
}
}
return false;
},
/**
* Handles AJAX responses.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
var $length = this._updateData.length;
if (!$length) {
return;
}
this._updateState(data);
this._updateData = [ ];
},
/**
* Update element states based upon update data.
*
* @param object data
*/
_updateState: function(data) { },
/**
* Handles clicks within dropdown.
*
* @param object event
*/
_click: function(event) {
var $listItem = $(event.currentTarget);
var $elementID = $listItem.data('elementID');
var $optionName = $listItem.data('optionName');
if (!this._execute($elementID, $optionName)) {
this._executeCallback($elementID, $optionName);
}
this._hide($elementID);
},
/**
* Executes actions associated with an option.
*
* @param string elementID
* @param string optionName
* @return boolean
*/
_execute: function(elementID, optionName) {
return false;
},
/**
* Executes actions associated with an option provided by callbacks.
*
* @param string elementID
* @param string optionName
* @return boolean
*/
_executeCallback: function(elementID, optionName) {
var $length = this._callbacks.length;
if ($length) {
for (var $i = 0; $i < $length; $i++) {
if (this._callbacks[$i].execute(this._elements[elementID], optionName)) {
return true;
}
}
}
return false;
},
/**
* Hides a dropdown menu.
*
* @param string elementID
*/
_hide: function(elementID) {
if (this._dropdowns[elementID]) {
this._dropdowns[elementID].empty().removeClass('dropdownOpen');
}
}
});
/**
* Default implementation for ajax file uploads.
*
* @deprecated Use WoltLabSuite/Core/Upload
*
* @param jquery buttonSelector
* @param jquery fileListSelector
* @param string className
* @param jquery options
*/
WCF.Upload = Class.extend({
/**
* name of the upload field
* @var string
*/
_name: '__files[]',
/**
* button selector
* @var jQuery
*/
_buttonSelector: null,
/**
* file list selector
* @var jQuery
*/
_fileListSelector: null,
/**
* upload file
* @var jQuery
*/
_fileUpload: null,
/**
* class name
* @var string
*/
_className: '',
/**
* iframe for IE<10 fallback
* @var jQuery
*/
_iframe: null,
/**
* internal file id
* @var integer
*/
_internalFileID: 0,
/**
* additional options
* @var jQuery
*/
_options: {},
/**
* upload matrix
* @var array
*/
_uploadMatrix: [],
/**
* true, if the active user's browser supports ajax file uploads
* @var boolean
*/
_supportsAJAXUpload: true,
/**
* fallback overlay for stupid browsers
* @var jquery
*/
_overlay: null,
/**
* Initializes a new upload handler.
*
* @param string buttonSelector
* @param string fileListSelector
* @param string className
* @param object options
*/
init: function(buttonSelector, fileListSelector, className, options) {
this._buttonSelector = buttonSelector;
this._fileListSelector = fileListSelector;
this._className = className;
this._internalFileID = 0;
this._options = $.extend(true, {
action: 'upload',
multiple: false,
url: 'index.php?ajax-upload/&t=' + SECURITY_TOKEN
}, options || { });
this._options.url = WCF.convertLegacyURL(this._options.url);
if (this._options.url.indexOf('index.php') === 0) {
this._options.url = WSC_API_URL + this._options.url;
}
// check for ajax upload support
var $xhr = new XMLHttpRequest();
this._supportsAJAXUpload = ($xhr && ('upload' in $xhr) && ('onprogress' in $xhr.upload));
// create upload button
this._createButton();
},
/**
* Creates the upload button.
*/
_createButton: function() {
if (this._supportsAJAXUpload) {
this._fileUpload = $('<input type="file" name="' + this._name + '" ' + (this._options.multiple ? 'multiple="true" ' : '') + '/>');
this._fileUpload.change($.proxy(this._upload, this));
var $button = $('<p class="button uploadButton"><span>' + WCF.Language.get('wcf.global.button.upload') + '</span></p>');
$button.prepend(this._fileUpload);
}
else {
var $button = $('<p class="button uploadFallbackButton"><span>' + WCF.Language.get('wcf.global.button.upload') + '</span></p>');
$button.click($.proxy(this._showOverlay, this));
}
this._insertButton($button);
},
/**
* Inserts the upload button.
*
* @param jQuery button
*/
_insertButton: function(button) {
this._buttonSelector.prepend(button);
},
/**
* Removes the upload button.
*/
_removeButton: function() {
var $selector = '.uploadButton';
if (!this._supportsAJAXUpload) {
$selector = '.uploadFallbackButton';
}
this._buttonSelector.find($selector).remove();
},
/**
* Callback for file uploads.
*
* @param object event
* @param File file
* @param Blob blob
* @return integer
*/
_upload: function(event, file, blob) {
var $uploadID = null;
var $files = [ ];
if (file) {
$files.push(file);
}
else if (blob) {
var $ext = '';
switch (blob.type) {
case 'image/png':
$ext = '.png';
break;
case 'image/jpeg':
$ext = '.jpg';
break;
case 'image/gif':
$ext = '.gif';
break;
}
$files.push({
name: 'pasted-from-clipboard' + $ext
});
}
else {
$files = this._fileUpload.prop('files');
}
if ($files.length) {
var $fd = new FormData();
$uploadID = this._createUploadMatrix($files);
// no more files left, abort
if (!this._uploadMatrix[$uploadID].length) {
return null;
}
for (var $i = 0, $length = $files.length; $i < $length; $i++) {
if (this._uploadMatrix[$uploadID][$i]) {
var $internalFileID = this._uploadMatrix[$uploadID][$i].data('internalFileID');
if (blob) {
$fd.append('__files[' + $internalFileID + ']', blob, $files[$i].name);
}
else {
$fd.append('__files[' + $internalFileID + ']', $files[$i]);
}
}
}
$fd.append('actionName', this._options.action);
$fd.append('className', this._className);
var $additionalParameters = this._getParameters();
for (var $name in $additionalParameters) {
$fd.append('parameters[' + $name + ']', $additionalParameters[$name]);
}
var self = this;
$.ajax({
type: 'POST',
url: this._options.url,
enctype: 'multipart/form-data',
data: $fd,
contentType: false,
processData: false,
success: function(data, textStatus, jqXHR) {
self._success($uploadID, data);
},
error: $.proxy(this._error, this),
xhr: function() {
var $xhr = $.ajaxSettings.xhr();
if ($xhr) {
$xhr.upload.addEventListener('progress', function(event) {
self._progress($uploadID, event);
}, false);
}
return $xhr;
}
});
}
return $uploadID;
},
/**
* Creates upload matrix for provided files.
*
* @param array<object> files
* @return integer
*/
_createUploadMatrix: function(files) {
if (files.length) {
var $uploadID = this._uploadMatrix.length;
this._uploadMatrix[$uploadID] = [ ];
for (var $i = 0, $length = files.length; $i < $length; $i++) {
var $file = files[$i];
var $li = this._initFile($file);
if (!$li.hasClass('uploadFailed')) {
$li.data('filename', $file.name).data('internalFileID', this._internalFileID++);
this._uploadMatrix[$uploadID][$i] = $li;
}
}
return $uploadID;
}
return null;
},
/**
* Callback for success event.
*
* @param integer uploadID
* @param object data
*/
_success: function(uploadID, data) { },
/**
* Callback for error event.
*
* @param jQuery jqXHR
* @param string textStatus
* @param string errorThrown
*/
_error: function(jqXHR, textStatus, errorThrown) { },
/**
* Callback for progress event.
*
* @param integer uploadID
* @param object event
*/
_progress: function(uploadID, event) {
var $percentComplete = Math.round(event.loaded * 100 / event.total);
for (var $i in this._uploadMatrix[uploadID]) {
this._uploadMatrix[uploadID][$i].find('progress').attr('value', $percentComplete);
}
},
/**
* Returns additional parameters.
*
* @return object
*/
_getParameters: function() {
return {};
},
/**
* Initializes list item for uploaded file.
*
* @return jQuery
*/
_initFile: function(file) {
return $('<li>' + file.name + ' (' + file.size + ')<progress max="100" /></li>').appendTo(this._fileListSelector);
},
/**
* Shows the fallback overlay (work in progress)
*/
_showOverlay: function() {
// create iframe
if (this._iframe === null) {
this._iframe = $('<iframe name="__fileUploadIFrame" />').hide().appendTo(document.body);
}
// create overlay
if (!this._overlay) {
this._overlay = $('<div><form enctype="multipart/form-data" method="post" action="' + this._options.url + '" target="__fileUploadIFrame" /></div>').hide().appendTo(document.body);
var $form = this._overlay.find('form');
$('<dl class="wide"><dd><input type="file" id="__fileUpload" name="' + this._name + '" ' + (this._options.multiple ? 'multiple="true" ' : '') + '/></dd></dl>').appendTo($form);
$('<div class="formSubmit"><input type="submit" value="Upload" accesskey="s" /></div></form>').appendTo($form);
$('<input type="hidden" name="isFallback" value="1" />').appendTo($form);
$('<input type="hidden" name="actionName" value="' + this._options.action + '" />').appendTo($form);
$('<input type="hidden" name="className" value="' + this._className + '" />').appendTo($form);
var $additionalParameters = this._getParameters();
for (var $name in $additionalParameters) {
$('<input type="hidden" name="' + $name + '" value="' + $additionalParameters[$name] + '" />').appendTo($form);
}
$form.submit($.proxy(function() {
var $file = {
name: this._getFilename(),
size: ''
};
var $uploadID = this._createUploadMatrix([ $file ]);
var self = this;
this._iframe.data('loading', true).off('load').load(function() { self._evaluateResponse($uploadID); });
this._overlay.wcfDialog('close');
}, this));
}
this._overlay.wcfDialog({
title: WCF.Language.get('wcf.global.button.upload')
});
},
/**
* Evaluates iframe response.
*
* @param integer uploadID
*/
_evaluateResponse: function(uploadID) {
var $returnValues = $.parseJSON(this._iframe.contents().find('pre').html());
this._success(uploadID, $returnValues);
},
/**
* Returns name of selected file.
*
* @return string
*/
_getFilename: function() {
return $('#__fileUpload').val().split('\\').pop();
}
});
/**
* Default implementation for parallel AJAX file uploads.
*
* @deprecated Use WoltLabSuite/Core/Upload
*/
WCF.Upload.Parallel = WCF.Upload.extend({
/**
* @see WCF.Upload.init()
*/
init: function(buttonSelector, fileListSelector, className, options) {
// force multiple uploads
options = $.extend(true, options || { }, {
multiple: true
});
this._super(buttonSelector, fileListSelector, className, options);
},
/**
* @see WCF.Upload._upload()
*/
_upload: function() {
var $files = this._fileUpload.prop('files');
for (var $i = 0, $length = $files.length; $i < $length; $i++) {
var $file = $files[$i];
var $formData = new FormData();
var $internalFileID = this._createUploadMatrix($file);
if (!this._uploadMatrix[$internalFileID].length) {
continue;
}
$formData.append('__files[' + $internalFileID + ']', $file);
$formData.append('actionName', this._options.action);
$formData.append('className', this._className);
var $additionalParameters = this._getParameters();
for (var $name in $additionalParameters) {
$formData.append('parameters[' + $name + ']', $additionalParameters[$name]);
}
this._sendRequest($internalFileID, $formData);
}
},
/**
* Sends an AJAX request to upload a file.
*
* @param integer internalFileID
* @param FormData formData
*/
_sendRequest: function(internalFileID, formData) {
var self = this;
$.ajax({
type: 'POST',
url: this._options.url,
enctype: 'multipart/form-data',
data: formData,
contentType: false,
processData: false,
success: function(data, textStatus, jqXHR) {
self._success(internalFileID, data);
},
error: $.proxy(this._error, this),
xhr: function() {
var $xhr = $.ajaxSettings.xhr();
if ($xhr) {
$xhr.upload.addEventListener('progress', function(event) {
self._progress(internalFileID, event);
}, false);
}
return $xhr;
}
});
},
/**
* Creates upload matrix for provided file and returns its internal file id.
*
* @param object file
* @return integer
*/
_createUploadMatrix: function(file) {
var $li = this._initFile(file);
if (!$li.hasClass('uploadFailed')) {
$li.data('filename', file.name).data('internalFileID', this._internalFileID);
this._uploadMatrix[this._internalFileID++] = $li;
return this._internalFileID - 1;
}
return null;
},
/**
* Callback for success event.
*
* @param integer internalFileID
* @param object data
*/
_success: function(internalFileID, data) { },
/**
* Callback for progress event.
*
* @param integer internalFileID
* @param object event
*/
_progress: function(internalFileID, event) {
var $percentComplete = Math.round(event.loaded * 100 / event.total);
this._uploadMatrix[internalFileID].find('progress').attr('value', $percentComplete);
},
/**
* @see WCF.Upload._showOverlay()
*/
_showOverlay: function() {
// create iframe
if (this._iframe === null) {
this._iframe = $('<iframe name="__fileUploadIFrame" />').hide().appendTo(document.body);
}
// create overlay
if (!this._overlay) {
this._overlay = $('<div><form enctype="multipart/form-data" method="post" action="' + this._options.url + '" target="__fileUploadIFrame" /></div>').hide().appendTo(document.body);
var $form = this._overlay.find('form');
$('<dl class="wide"><dd><input type="file" id="__fileUpload" name="' + this._name + '" ' + (this._options.multiple ? 'multiple="true" ' : '') + '/></dd></dl>').appendTo($form);
$('<div class="formSubmit"><input type="submit" value="Upload" accesskey="s" /></div></form>').appendTo($form);
$('<input type="hidden" name="isFallback" value="1" />').appendTo($form);
$('<input type="hidden" name="actionName" value="' + this._options.action + '" />').appendTo($form);
$('<input type="hidden" name="className" value="' + this._className + '" />').appendTo($form);
var $additionalParameters = this._getParameters();
for (var $name in $additionalParameters) {
$('<input type="hidden" name="' + $name + '" value="' + $additionalParameters[$name] + '" />').appendTo($form);
}
$form.submit($.proxy(function() {
var $file = {
name: this._getFilename(),
size: ''
};
var $internalFileID = this._createUploadMatrix($file);
var self = this;
this._iframe.data('loading', true).off('load').load(function() { self._evaluateResponse($internalFileID); });
this._overlay.wcfDialog('close');
}, this));
}
this._overlay.wcfDialog({
title: WCF.Language.get('wcf.global.button.upload')
});
},
/**
* Evaluates iframe response.
*
* @param integer internalFileID
*/
_evaluateResponse: function(internalFileID) {
var $returnValues = $.parseJSON(this._iframe.contents().find('pre').html());
this._success(internalFileID, $returnValues);
}
});
/**
* Namespace for sortables.
*/
WCF.Sortable = { };
/**
* Sortable implementation for lists.
*
* @param string containerID
* @param string className
* @param integer offset
* @param object options
*/
WCF.Sortable.List = Class.extend({
/**
* additional parameters for AJAX request
* @var object
*/
_additionalParameters: { },
/**
* action class name
* @var string
*/
_className: '',
/**
* container id
* @var string
*/
_containerID: '',
/**
* container object
* @var jQuery
*/
_container: null,
/**
* notification object
* @var WCF.System.Notification
*/
_notification: null,
/**
* show order offset
* @var integer
*/
_offset: 0,
/**
* list of options
* @var object
*/
_options: { },
/**
* proxy object
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* object structure
* @var object
*/
_structure: { },
/**
* Creates a new sortable list.
*
* @param string containerID
* @param string className
* @param integer offset
* @param object options
* @param boolean isSimpleSorting
* @param object additionalParameters
*/
init: function(containerID, className, offset, options, isSimpleSorting, additionalParameters) {
this._additionalParameters = additionalParameters || { };
this._containerID = $.wcfEscapeID(containerID);
this._container = $('#' + this._containerID);
this._className = className;
this._offset = (offset) ? offset : 0;
this._proxy = new WCF.Action.Proxy({
success: $.proxy(this._success, this)
});
this._structure = { };
// init sortable
this._options = $.extend(true, {
axis: 'y',
connectWith: '#' + this._containerID + ' .sortableList',
disableNesting: 'sortableNoNesting',
doNotClear: true,
errorClass: 'sortableInvalidTarget',
forcePlaceholderSize: true,
helper: 'clone',
items: 'li:not(.sortableNoSorting)',
opacity: .6,
placeholder: 'sortablePlaceholder',
tolerance: 'pointer',
toleranceElement: '> span'
}, options || { });
var sortableList = $('#' + this._containerID + ' .sortableList');
if (sortableList.is('tbody') && this._options.helper === 'clone') {
this._options.helper = this._tableRowHelper.bind(this);
// explicitly set column widths to avoid column resizing during dragging
var thead = sortableList.prev('thead');
if (thead) {
thead.find('th').each(function(index, element) {
element = $(element);
element.width(element.width());
});
}
}
if (isSimpleSorting) {
sortableList.sortable(this._options);
}
else {
sortableList.nestedSortable(this._options);
}
if (this._className) {
var $formSubmit = this._container.find('.formSubmit');
if (!$formSubmit.length) {
$formSubmit = this._container.next('.formSubmit');
if (!$formSubmit.length) {
console.debug("[WCF.Sortable.Simple] Unable to find form submit for saving, aborting.");
return;
}
}
$formSubmit.children('button[data-type="submit"]').click($.proxy(this._submit, this));
}
},
/**
* Fixes the width of the cells of the dragged table row.
*
* @param {Event} event
* @param {jQuery} ui
* @return {jQuery}
*/
_tableRowHelper: function(event, ui) {
ui.children('td').each(function(index, element) {
element = $(element);
element.width(element.width());
});
return ui;
},
/**
* Saves object structure.
*/
_submit: function() {
// reset structure
this._structure = { };
// build structure
this._container.find('.sortableList').each($.proxy(function(index, list) {
var $list = $(list);
var $parentID = $list.data('objectID');
if ($parentID !== undefined) {
$list.children(this._options.items).each($.proxy(function(index, listItem) {
var $objectID = $(listItem).data('objectID');
if (!this._structure[$parentID]) {
this._structure[$parentID] = [ ];
}
this._structure[$parentID].push($objectID);
}, this));
}
}, this));
// send request
var $parameters = $.extend(true, {
data: {
offset: this._offset,
structure: this._structure
}
}, this._additionalParameters);
this._proxy.setOption('data', {
actionName: 'updatePosition',
className: this._className,
interfaceName: 'wcf\\data\\ISortableAction',
parameters: $parameters
});
this._proxy.sendRequest();
},
/**
* Shows notification upon success.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
if (this._notification === null) {
this._notification = new WCF.System.Notification(WCF.Language.get('wcf.global.success.edit'));
}
this._notification.show();
}
});
WCF.Popover = Class.extend({
/**
* currently active element id
* @var string
*/
_activeElementID: '',
_identifier: '',
_popoverObj: null,
/**
* Initializes a new WCF.Popover object.
*
* @param string selector
*/
init: function(selector) {
var mobile = false;
require(['Environment'], function(Environment) {
if (Environment.platform() !== 'desktop') {
mobile = true;
}
}.bind(this));
if (mobile) return;
// assign default values
this._activeElementID = '';
this._identifier = selector;
require(['WoltLabSuite/Core/Controller/Popover'], (function(popover) {
popover.init({
attributeName: 'legacy',
className: selector,
identifier: this._identifier,
legacy: true,
loadCallback: this._legacyLoad.bind(this)
});
}).bind(this));
},
_initContainers: function() {},
_legacyLoad: function(objectId, popover) {
this._activeElementID = objectId;
this._popoverObj = popover;
this._loadContent();
},
_insertContent: function(elementId, template) {
this._popoverObj.setContent(this._identifier, elementId, template);
}
});
/**
* Provides an extensible item list with built-in search.
*
* @param string itemListSelector
* @param string searchInputSelector
*/
WCF.EditableItemList = Class.extend({
/**
* allows custom input not recognized by search to be added
* @var boolean
*/
_allowCustomInput: false,
/**
* action class name
* @var string
*/
_className: '',
/**
* internal data storage
* @var mixed
*/
_data: { },
/**
* form container
* @var jQuery
*/
_form: null,
/**
* item list container
* @var jQuery
*/
_itemList: null,
/**
* current object id
* @var integer
*/
_objectID: 0,
/**
* object type id
* @var integer
*/
_objectTypeID: 0,
/**
* search controller
* @var WCF.Search.Base
*/
_search: null,
/**
* search input element
* @var jQuery
*/
_searchInput: null,
/**
* Creates a new WCF.EditableItemList object.
*
* @param string itemListSelector
* @param string searchInputSelector
*/
init: function(itemListSelector, searchInputSelector) {
this._itemList = $(itemListSelector);
this._searchInput = $(searchInputSelector);
this._data = { };
if (!this._itemList.length || !this._searchInput.length) {
console.debug("[WCF.EditableItemList] Item list and/or search input do not exist, aborting.");
return;
}
this._objectID = this._getObjectID();
this._objectTypeID = this._getObjectTypeID();
// bind item listener
this._itemList.find('.jsEditableItem').click($.proxy(this._click, this));
// create item list
if (!this._itemList.children('ul').length) {
$('<ul />').appendTo(this._itemList);
}
this._itemList = this._itemList.children('ul');
// bind form submit
this._form = this._itemList.parents('form').submit($.proxy(this._submit, this));
if (this._allowCustomInput) {
var self = this;
this._searchInput.keydown($.proxy(this._keyDown, this)).keypress($.proxy(this._keyPress, this)).on('paste', function() {
setTimeout(function() { self._onPaste(); }, 100);
});
}
// block form submit through [ENTER]
this._searchInput.parents('.dropdown').data('preventSubmit', true);
},
/**
* Handles the key down event.
*
* @param object event
*/
_keyDown: function(event) {
if (event === null) {
return this._keyPress(null);
}
return true;
},
/**
* Handles the key press event.
*
* @param object event
*/
_keyPress: function(event) {
// 44 = [,] (charCode != keyCode)
if (event === null || event.charCode === 44 || event.charCode === $.ui.keyCode.ENTER || ($.browser.mozilla && event.keyCode === $.ui.keyCode.ENTER)) {
if (event !== null && event.charCode === $.ui.keyCode.ENTER && this._search) {
if (this._search._itemIndex !== -1) {
return false;
}
}
var $value = $.trim(this._searchInput.val());
// read everything left from caret position
if (event && event.charCode === 44) {
$value = $value.substring(0, this._searchInput.getCaret());
}
if ($value === '') {
return true;
}
this.addItem({
objectID: 0,
label: $value
});
// reset input
if (event && event.charCode === 44) {
this._searchInput.val($.trim(this._searchInput.val().substr(this._searchInput.getCaret())));
}
else {
this._searchInput.val('');
}
if (event !== null) {
event.stopPropagation();
}
return false;
}
return true;
},
/**
* Handle paste event.
*/
_onPaste: function() {
// split content by comma
var $value = $.trim(this._searchInput.val());
$value = $value.split(',');
for (var $i = 0, $length = $value.length; $i < $length; $i++) {
var $label = $.trim($value[$i]);
if ($label === '') {
continue;
}
this.addItem({
objectID: 0,
label: $label
});
}
this._searchInput.val('');
},
/**
* Loads raw data and converts it into internal structure. Override this methods
* in your derived classes.
*
* @param object data
*/
load: function(data) { },
/**
* Removes an item on click.
*
* @param object event
* @return boolean
*/
_click: function(event) {
var $element = $(event.currentTarget);
var $objectID = $element.data('objectID');
var $label = $element.data('label');
if (this._search) {
this._search.removeExcludedSearchValue($label);
}
this._removeItem($objectID, $label);
$element.remove();
event.stopPropagation();
return false;
},
/**
* Returns current object id.
*
* @return integer
*/
_getObjectID: function() {
return 0;
},
/**
* Returns current object type id.
*
* @return integer
*/
_getObjectTypeID: function() {
return 0;
},
/**
* Adds a new item to the list.
*
* @param object data
* @return boolean
*/
addItem: function(data) {
if (this._data[data.objectID]) {
if (!(data.objectID === 0 && this._allowCustomInput)) {
return true;
}
}
var $listItem = $('<li class="badge">' + WCF.String.escapeHTML(data.label) + '</li>').data('objectID', data.objectID).data('label', data.label).appendTo(this._itemList);
$listItem.click($.proxy(this._click, this));
if (this._search) {
this._search.addExcludedSearchValue(data.label);
}
this._addItem(data.objectID, data.label);
return true;
},
/**
* Clears the list of items.
*/
clearList: function() {
this._itemList.children('li').each($.proxy(function(index, element) {
var $element = $(element);
if (this._search) {
this._search.removeExcludedSearchValue($element.data('label'));
}
$element.remove();
this._removeItem($element.data('objectID'), $element.data('label'));
}, this));
},
/**
* Handles form submit, override in your class.
*/
_submit: function() {
this._keyDown(null);
},
/**
* Adds an item to internal storage.
*
* @param integer objectID
* @param string label
*/
_addItem: function(objectID, label) {
this._data[objectID] = label;
},
/**
* Removes an item from internal storage.
*
* @param integer objectID
* @param string label
*/
_removeItem: function(objectID, label) {
delete this._data[objectID];
},
/**
* Returns the search input field.
*
* @return jQuery
*/
getSearchInput: function() {
return this._searchInput;
}
});
/**
* Provides a language chooser.
*
* @param {string} containerId input element conainer id
* @param {string} chooserId input element id
* @param {int} languageId selected language id
* @param {object<int, object<string, string>>} languages data of available languages
* @param {function} callback function called after a language is selected
* @param {boolean} allowEmptyValue true if no language may be selected
*
* @deprecated 3.0 - please use `WoltLabSuite/Core/Language/Chooser` instead
*/
WCF.Language.Chooser = Class.extend({
/**
* Initializes the language chooser.
*
* @param {string} containerId input element conainer id
* @param {string} chooserId input element id
* @param {int} languageId selected language id
* @param {object<int, object<string, string>>} languages data of available languages
* @param {function} callback function called after a language is selected
* @param {boolean} allowEmptyValue true if no language may be selected
*/
init: function(containerId, chooserId, languageId, languages, callback, allowEmptyValue) {
require(['WoltLabSuite/Core/Language/Chooser'], function(LanguageChooser) {
LanguageChooser.init(containerId, chooserId, languageId, languages, callback, allowEmptyValue);
});
}
});
/**
* Namespace for style related classes.
*/
WCF.Style = { };
/**
* Converts static user panel items into interactive dropdowns.
*
* @deprecated 2.1 - Please use WCF.User.Panel.Interactive instead
*
* @param string containerID
*/
WCF.UserPanel = Class.extend({
/**
* target container
* @var jQuery
*/
_container: null,
/**
* initialization state
* @var boolean
*/
_didLoad: false,
/**
* original link element
* @var jQuery
*/
_link: null,
/**
* language variable name for 'no items'
* @var string
*/
_noItems: '',
/**
* reverts to original link if return values are empty
* @var boolean
*/
_revertOnEmpty: true,
/**
* Initialites the WCF.UserPanel class.
*
* @param string containerID
*/
init: function(containerID) {
this._container = $('#' + containerID);
this._didLoad = false;
this._revertOnEmpty = true;
if (this._container.length != 1) {
console.debug("[WCF.UserPanel] Unable to find container identfied by '" + containerID + "', aborting.");
return;
}
this._convert();
},
/**
* Converts link into an interactive dropdown menu.
*/
_convert: function() {
this._container.addClass('dropdown');
this._link = this._container.children('a').remove();
var $button = $('<a href="' + this._link.attr('href') + '" class="dropdownToggle">' + this._link.html() + '</a>').appendTo(this._container).click($.proxy(this._click, this));
var $dropdownMenu = $('<ul class="dropdownMenu" />').appendTo(this._container);
$('<li class="jsDropdownPlaceholder"><span>' + WCF.Language.get('wcf.global.loading') + '</span></li>').appendTo($dropdownMenu);
this._addDefaultItems($dropdownMenu);
this._container.dblclick($.proxy(function() {
window.location = this._link.attr('href');
return false;
}, this));
WCF.Dropdown.initDropdown($button, false);
},
/**
* Adds default items to dropdown menu.
*
* @param jQuery dropdownMenu
*/
_addDefaultItems: function(dropdownMenu) { },
/**
* Adds a dropdown divider.
*
* @param jQuery dropdownMenu
*/
_addDivider: function(dropdownMenu) {
$('<li class="dropdownDivider" />').appendTo(dropdownMenu);
},
/**
* Handles clicks on the dropdown item.
*
* @param object event
*/
_click: function(event) {
event.preventDefault();
if (this._didLoad) {
return;
}
new WCF.Action.Proxy({
autoSend: true,
data: this._getParameters(),
success: $.proxy(this._success, this)
});
this._didLoad = true;
},
/**
* Returns a list of parameters for AJAX request.
*
* @return object
*/
_getParameters: function() {
return { };
},
/**
* Handles successful AJAX requests.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
var $dropdownMenu = WCF.Dropdown.getDropdownMenu(this._container.wcfIdentify());
$dropdownMenu.children('.jsDropdownPlaceholder').remove();
if (data.returnValues && data.returnValues.template) {
$('' + data.returnValues.template).prependTo($dropdownMenu);
// update badge
this._updateBadge(data.returnValues.totalCount);
this._after($dropdownMenu);
}
else {
$('<li><span>' + WCF.Language.get(this._noItems) + '</span></li>').prependTo($dropdownMenu);
// remove badge
this._updateBadge(0);
}
},
/**
* Updates badge count.
*
* @param integer count
*/
_updateBadge: function(count) {
count = parseInt(count) || 0;
if (count) {
var $badge = this._container.find('.badge');
if (!$badge.length) {
$badge = $('<span class="badge badgeUpdate" />').appendTo(this._container.children('.dropdownToggle'));
$badge.before(' ');
}
$badge.html(count);
}
else {
this._container.find('.badge').remove();
}
},
/**
* Execute actions after the dropdown menu has been populated.
*
* @param object dropdownMenu
*/
_after: function(dropdownMenu) { }
});
jQuery.fn.extend({
// shim for 'ui.wcfDialog'
wcfDialog: function(method) {
var args = arguments;
require(['Dom/Util', 'Ui/Dialog'], (function(DomUtil, UiDialog) {
var id = DomUtil.identify(this[0]);
if (method === 'close') {
UiDialog.close(id);
}
else if (method === 'render') {
UiDialog.rebuild(id);
}
else if (method === 'option') {
if (args.length === 3 && args[1] === 'title' && typeof args[2] === 'string') {
UiDialog.setTitle(id, args[2]);
}
}
else {
if (this[0].parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
// if element is not already part of the DOM, UiDialog.open() will fail
document.body.appendChild(this[0]);
}
UiDialog.openStatic(id, null, (args.length === 1 && typeof args[0] === 'object') ? args[0] : {});
}
}).bind(this));
return this;
}
});
/**
* Provides a slideshow for lists.
*/
$.widget('ui.wcfSlideshow', {
/**
* button list object
* @var jQuery
*/
_buttonList: null,
/**
* number of items
* @var integer
*/
_count: 0,
/**
* item index
* @var integer
*/
_index: 0,
/**
* item list object
* @var jQuery
*/
_itemList: null,
/**
* list of items
* @var jQuery
*/
_items: null,
/**
* timer object
* @var WCF.PeriodicalExecuter
*/
_timer: null,
/**
* list item width
* @var integer
*/
_width: 0,
/**
* list of options
* @var object
*/
options: {
/* enables automatic cycling of items */
cycle: true,
/* cycle interval in seconds */
cycleInterval: 5,
/* gap between items in pixels */
itemGap: 50
},
/**
* Creates a new instance of ui.wcfSlideshow.
*/
_create: function() {
this._itemList = this.element.children('ul');
this._items = this._itemList.children('li');
this._count = this._items.length;
this._index = 0;
if (this._count > 1) {
this._initSlideshow();
}
},
/**
* Initializes the slideshow.
*/
_initSlideshow: function() {
// calculate item dimensions
var $itemHeight = $(this._items.get(0)).outerHeight();
this._items.addClass('slideshowItem');
this._width = this.element.css('height', $itemHeight).innerWidth();
this._itemList.addClass('slideshowItemList').css('left', 0);
this._items.each($.proxy(function(index, item) {
$(item).show().css({
height: $itemHeight,
left: ((this._width + this.options.itemGap) * index),
width: this._width
});
}, this));
this.element.css({
height: $itemHeight,
width: this._width
}).hover($.proxy(this._hoverIn, this), $.proxy(this._hoverOut, this));
// create toggle buttons
this._buttonList = $('<ul class="slideshowButtonList" />').appendTo(this.element);
for (var $i = 0; $i < this._count; $i++) {
var $link = $('<li><a><span class="icon icon16 fa-circle" /></a></li>').data('index', $i).click($.proxy(this._click, this)).appendTo(this._buttonList);
if ($i == 0) {
$link.find('.icon').addClass('active');
}
}
this._resetTimer();
$(window).resize($.proxy(this._resize, this));
},
/**
* Rebuilds slideshow height in case the initial height contained resources affecting the
* element height, but loading has not completed on slideshow init.
*/
rebuildHeight: function() {
var $firstItem = $(this._items.get(0)).css('height', 'auto');
var $itemHeight = $firstItem.outerHeight();
this._items.css('height', $itemHeight + 'px');
this.element.css('height', $itemHeight + 'px');
},
/**
* Handles browser resizing
*/
_resize: function() {
this._width = this.element.css('width', 'auto').innerWidth();
this._items.each($.proxy(function(index, item) {
$(item).css({
left: ((this._width + this.options.itemGap) * index),
width: this._width
});
}, this));
this._index--;
this.moveTo(null);
},
/**
* Disables cycling while hovering.
*/
_hoverIn: function() {
if (this._timer !== null) {
this._timer.stop();
}
},
/**
* Enables cycling after mouse out.
*/
_hoverOut: function() {
this._resetTimer();
},
/**
* Resets cycle timer.
*/
_resetTimer: function() {
if (!this.options.cycle) {
return;
}
if (this._timer !== null) {
this._timer.stop();
}
var self = this;
this._timer = new WCF.PeriodicalExecuter(function() {
self.moveTo(null);
}, this.options.cycleInterval * 1000);
},
/**
* Handles clicks on the select buttons.
*
* @param object event
*/
_click: function(event) {
this.moveTo($(event.currentTarget).data('index'));
this._resetTimer();
},
/**
* Moves to a specified item index, NULL will move to the next item in list.
*
* @param integer index
*/
moveTo: function(index) {
this._index = (index === null) ? this._index + 1 : index;
if (this._index == this._count) {
this._index = 0;
}
$(this._buttonList.find('.icon').removeClass('active').get(this._index)).addClass('active');
this._itemList.css('left', this._index * (this._width + this.options.itemGap) * -1);
this._trigger('moveTo', null, { index: this._index });
},
/**
* Returns item by index or null if index is invalid.
*
* @return jQuery
*/
getItem: function(index) {
if (this._items[index]) {
return this._items[index];
}
return null;
}
});
jQuery.fn.extend({
datepicker: function(method) {
var element = this[0], parameters = Array.prototype.slice.call(arguments, 1);
switch (method) {
case 'destroy':
window.__wcf_bc_datePicker.destroy(element);
break;
case 'getDate':
return window.__wcf_bc_datePicker.getDate(element);
break;
case 'option':
if (parameters[0] === 'onClose') {
return function() {};
}
console.warn("datepicker('option') supports only 'onClose'.");
break;
case 'setDate':
window.__wcf_bc_datePicker.setDate(element, parameters[0]);
break;
case 'setOption':
if (parameters[0] === 'onClose') {
window.__wcf_bc_datePicker.setCloseCallback(element, parameters[1]);
}
else {
console.warn("datepicker('setOption') supports only 'onClose'.");
}
break;
default:
console.debug("Unsupported method '" + method + "' for datepicker()");
break;
}
return this;
}
});
jQuery.fn.extend({
wcfTabs: function(method) {
var element = this[0], parameters = Array.prototype.slice.call(arguments, 1);
require(['Dom/Util', 'WoltLabSuite/Core/Ui/TabMenu'], function(DomUtil, TabMenu) {
var container = TabMenu.getTabMenu(DomUtil.identify(element));
if (container !== null) {
container[method].apply(container, parameters);
}
});
}
});
/**
* jQuery widget implementation of the wcf pagination.
*
* @deprecated 3.0 - use `WoltLabSuite/Core/Ui/Pagination` instead
*/
$.widget('ui.wcfPages', {
_api: null,
SHOW_LINKS: 11,
SHOW_SUB_LINKS: 20,
options: {
// vars
activePage: 1,
maxPage: 1
},
/**
* Creates the pages widget.
*/
_create: function() {
require(['WoltLabSuite/Core/Ui/Pagination'], (function(UiPagination) {
this._api = new UiPagination(this.element[0], {
activePage: this.options.activePage,
maxPage: this.options.maxPage,
callbackShouldSwitch: (function(pageNo) {
var result = this._trigger('shouldSwitch', undefined, {
nextPage: pageNo
});
return (result !== false);
}).bind(this),
callbackSwitch: (function(pageNo) {
this._trigger('switched', undefined, {
activePage: pageNo
});
}).bind(this)
});
}).bind(this));
},
/**
* Destroys the pages widget.
*/
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments);
this._api = null;
this.element[0].innerHTML = '';
},
/**
* Sets the given option to the given value.
* See the jQuery UI widget documentation for more.
*/
_setOption: function(key, value) {
if (key == 'activePage') {
if (value != this.options[key] && value > 0 && value <= this.options.maxPage) {
// you can prevent the page switching by returning false or by event.preventDefault()
// in a shouldSwitch-callback. e.g. if an AJAX request is already running.
var $result = this._trigger('shouldSwitch', undefined, {
nextPage: value
});
if ($result || $result !== undefined) {
this._api.switchPage(value);
}
else {
this._trigger('notSwitched', undefined, {
activePage: value
});
}
}
}
return this;
}
});
/**
* Namespace for category related classes.
*/
WCF.Category = { };
/**
* Handles selection of categories.
*/
WCF.Category.NestedList = Class.extend({
/**
* list of categories
* @var object
*/
_categories: { },
/**
* Initializes the WCF.Category.NestedList object.
*/
init: function() {
var self = this;
$('.jsCategory').each(function(index, category) {
var $category = $(category).data('parentCategoryID', null).change($.proxy(self._updateSelection, self));
self._categories[$category.val()] = $category;
// find child categories
var $childCategoryIDs = [ ];
$category.parents('li').find('.jsChildCategory').each(function(innerIndex, childCategory) {
var $childCategory = $(childCategory).data('parentCategoryID', $category.val()).change($.proxy(self._updateSelection, self));
self._categories[$childCategory.val()] = $childCategory;
$childCategoryIDs.push($childCategory.val());
if ($childCategory.is(':checked')) {
$category.prop('checked', 'checked');
}
});
$category.data('childCategoryIDs', $childCategoryIDs);
});
},
/**
* Updates selection of categories.
*
* @param object event
*/
_updateSelection: function(event) {
var $category = $(event.currentTarget);
var $parentCategoryID = $category.data('parentCategoryID');
if ($category.is(':checked')) {
// child category
if ($parentCategoryID !== null) {
// mark parent category as checked
this._categories[$parentCategoryID].prop('checked', 'checked');
}
}
else {
// top-level category
if ($parentCategoryID === null) {
// unmark all child categories
var $childCategoryIDs = $category.data('childCategoryIDs');
for (var $i = 0, $length = $childCategoryIDs.length; $i < $length; $i++) {
this._categories[$childCategoryIDs[$i]].prop('checked', false);
}
}
}
}
});
/**
* Handles selection of categories.
*/
WCF.Category.FlexibleCategoryList = Class.extend({
/**
* category list container
* @var jQuery
*/
_list: null,
/**
* list of children per category id
* @var object<integer>
*/
_categories: { },
init: function(elementID) {
this._list = $('#' + elementID);
this._buildStructure();
this._list.find('input:checked').each(function() {
$(this).trigger('change');
});
if (this._list.children('li').length < 2) {
this._list.addClass('flexibleCategoryListDisabled');
return;
}
},
_buildStructure: function() {
var self = this;
this._list.find('.jsCategory').each(function(i, category) {
var $category = $(category).change(self._updateSelection.bind(self));
var $categoryID = parseInt($category.val());
var $childCategories = [ ];
$category.parents('li:eq(0)').find('.jsChildCategory').each(function(j, childCategory) {
var $childCategory = $(childCategory);
$childCategory.data('parentCategory', $category).change(self._updateSelection.bind(self));
var $childCategoryID = parseInt($childCategory.val());
$childCategories.push($childCategory);
var $subChildCategories = [ ];
$childCategory.parents('li:eq(0)').find('.jsSubChildCategory').each(function(k, subChildCategory) {
var $subChildCategory = $(subChildCategory);
$subChildCategory.data('parentCategory', $childCategory).change(self._updateSelection.bind(self));
$subChildCategories.push($subChildCategory);
});
self._categories[$childCategoryID] = $subChildCategories;
});
self._categories[$categoryID] = $childCategories;
});
},
_updateSelection: function(event) {
var $category = $(event.currentTarget);
var $categoryID = parseInt($category.val());
var $parentCategory = $category.data('parentCategory');
if ($category.is(':checked')) {
if ($parentCategory) {
$parentCategory.prop('checked', 'checked');
$parentCategory = $parentCategory.data('parentCategory');
if ($parentCategory) {
$parentCategory.prop('checked', 'checked');
}
}
}
else {
// uncheck child categories
if (this._categories[$categoryID]) {
for (var $i = 0, $length = this._categories[$categoryID].length; $i < $length; $i++) {
var $childCategory = this._categories[$categoryID][$i];
$childCategory.prop('checked', false);
var $childCategoryID = parseInt($childCategory.val());
if (this._categories[$childCategoryID]) {
for (var $j = 0, $innerLength = this._categories[$childCategoryID].length; $j < $innerLength; $j++) {
this._categories[$childCategoryID][$j].prop('checked', false);
}
}
}
}
// uncheck direct parent if it has no more checked children
if ($parentCategory) {
var $parentCategoryID = parseInt($parentCategory.val());
for (var $i = 0, $length = this._categories[$parentCategoryID].length; $i < $length; $i++) {
if (this._categories[$parentCategoryID][$i].prop('checked')) {
// at least one child is checked, break
return;
}
}
$parentCategory = $parentCategory.data('parentCategory');
if ($parentCategory) {
$parentCategoryID = parseInt($parentCategory.val());
for (var $i = 0, $length = this._categories[$parentCategoryID].length; $i < $length; $i++) {
if (this._categories[$parentCategoryID][$i].prop('checked')) {
// at least one child is checked, break
return;
}
}
}
}
}
}
});
/**
* Initializes WCF.Condition namespace.
*/
WCF.Condition = { };
/**
* Initialize WCF.Notice namespace.
*/
WCF.Notice = { };
/**
* Encapsulate eval() within an own function to prevent problems
* with optimizing and minifiny JS.
*
* @param mixed expression
* @returns mixed
*/
function wcfEval(expression) {
return eval(expression);
}
| wcfsetup/install/files/js/WCF.js | "use strict";
/**
* Class and function collection for WCF.
*
* Major Contributors: Markus Bartz, Tim Duesterhus, Matthias Schmidt and Marcel Werk
*
* @author Alexander Ebert
* @copyright 2001-2015 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
*/
(function() {
// store original implementation
var $jQueryData = jQuery.fn.data;
/**
* Override jQuery.fn.data() to support custom 'ID' suffix which will
* be translated to '-id' at runtime.
*
* @see jQuery.fn.data()
*/
jQuery.fn.data = function(key, value) {
if (key) {
switch (typeof key) {
case 'object':
for (var $key in key) {
if ($key.match(/ID$/)) {
var $value = key[$key];
delete key[$key];
$key = $key.replace(/ID$/, '-id');
key[$key] = $value;
}
}
arguments[0] = key;
break;
case 'string':
if (key.match(/ID$/)) {
arguments[0] = key.replace(/ID$/, '-id');
}
break;
}
}
// call jQuery's own data method
var $data = $jQueryData.apply(this, arguments);
// handle .data() call without arguments
if (key === undefined) {
for (var $key in $data) {
if ($key.match(/Id$/)) {
$data[$key.replace(/Id$/, 'ID')] = $data[$key];
delete $data[$key];
}
}
}
return $data;
};
// provide a sane window.console implementation
if (!window.console) window.console = { };
var consoleProperties = [ "log",/* "debug",*/ "info", "warn", "exception", "assert", "dir", "dirxml", "trace", "group", "groupEnd", "groupCollapsed", "profile", "profileEnd", "count", "clear", "time", "timeEnd", "timeStamp", "table", "error" ];
for (var i = 0; i < consoleProperties.length; i++) {
if (typeof (console[consoleProperties[i]]) === 'undefined') {
console[consoleProperties[i]] = function () { };
}
}
if (typeof(console.debug) === 'undefined') {
// forward console.debug to console.log (IE9)
console.debug = function(string) { console.log(string); };
}
})();
/**
* Provides a hashCode() method for strings, similar to Java's String.hashCode().
*
* @see http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
*/
String.prototype.hashCode = function() {
var $char;
var $hash = 0;
if (this.length) {
for (var $i = 0, $length = this.length; $i < $length; $i++) {
$char = this.charCodeAt($i);
$hash = (($hash << 5) - $hash) + $char;
$hash = $hash & $hash; // convert to 32bit integer
}
}
return $hash;
};
/**
* Adds a Fisher-Yates shuffle algorithm for arrays.
*
* @see http://stackoverflow.com/a/2450976
*/
window.shuffle = function(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return this;
};
/**
* User-Agent based browser detection and touch detection.
*/
(function(jQuery) {
var ua = navigator.userAgent.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
var matched = {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
var browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = jQuery.browser || { };
jQuery.browser = $.extend(jQuery.browser, browser);
jQuery.browser.touch = (!!('ontouchstart' in window) || (!!('msMaxTouchPoints' in window.navigator) && window.navigator.msMaxTouchPoints > 0));
// detect smartphones
jQuery.browser.smartphone = ($('html').css('caption-side') == 'bottom');
// properly detect IE11
if (jQuery.browser.mozilla && ua.match(/trident/)) {
jQuery.browser.mozilla = false;
jQuery.browser.msie = true;
}
// detect iOS devices
jQuery.browser.iOS = /\((ipad|iphone|ipod);/.test(ua);
if (jQuery.browser.iOS) {
$('html').addClass('iOS');
}
// dectect Android
jQuery.browser.android = (ua.indexOf('android') !== -1);
// allow plugins to detect the used editor, value should be the same as the $.browser.<editorName> key
jQuery.browser.editor = 'redactor';
// CKEditor support (removed in WCF 2.1), do NOT remove this variable for the sake for compatibility
jQuery.browser.ckeditor = false;
// Redactor support
jQuery.browser.redactor = true;
// work-around for zoom bug on iOS when using .focus()
if (jQuery.browser.iOS) {
jQuery.fn.focus = function(data, fn) {
return arguments.length > 0 ? this.on('focus', null, data, fn) : this.trigger('focus');
};
}
})(jQuery);
/**
* Initialize WCF namespace
*/
// non strict equals by intent
if (window.WCF == null) window.WCF = { };
/**
* Extends jQuery with additional methods.
*/
$.extend(true, {
/**
* Removes the given value from the given array and returns the array.
*
* @param array array
* @param mixed element
* @return array
*/
removeArrayValue: function(array, value) {
return $.grep(array, function(element, index) {
return value !== element;
});
},
/**
* Escapes an ID to work with jQuery selectors.
*
* @see http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_element_by_an_ID_that_has_characters_used_in_CSS_notation.3F
* @param string id
* @return string
*/
wcfEscapeID: function(id) {
return id.replace(/(:|\.)/g, '\\$1');
},
/**
* Returns true if given ID exists within DOM.
*
* @param string id
* @return boolean
*/
wcfIsset: function(id) {
return !!$('#' + $.wcfEscapeID(id)).length;
},
/**
* Returns the length of an object.
*
* @param object targetObject
* @return integer
*/
getLength: function(targetObject) {
var $length = 0;
for (var $key in targetObject) {
if (targetObject.hasOwnProperty($key)) {
$length++;
}
}
return $length;
}
});
/**
* Extends jQuery's chainable methods.
*/
$.fn.extend({
/**
* Returns tag name of first jQuery element.
*
* @returns string
*/
getTagName: function() {
return (this.length) ? this.get(0).tagName.toLowerCase() : '';
},
/**
* Returns the dimensions for current element.
*
* @see http://api.jquery.com/hidden-selector/
* @param string type
* @return object
*/
getDimensions: function(type) {
var css = { };
var dimensions = { };
var wasHidden = false;
// show element to retrieve dimensions and restore them later
if (this.is(':hidden')) {
css = WCF.getInlineCSS(this);
wasHidden = true;
this.css({
display: 'block',
visibility: 'hidden'
});
}
switch (type) {
case 'inner':
dimensions = {
height: this.innerHeight(),
width: this.innerWidth()
};
break;
case 'outer':
dimensions = {
height: this.outerHeight(),
width: this.outerWidth()
};
break;
default:
dimensions = {
height: this.height(),
width: this.width()
};
break;
}
// restore previous settings
if (wasHidden) {
WCF.revertInlineCSS(this, css, [ 'display', 'visibility' ]);
}
return dimensions;
},
/**
* Returns the offsets for current element, defaults to position
* relative to document.
*
* @see http://api.jquery.com/hidden-selector/
* @param string type
* @return object
*/
getOffsets: function(type) {
var css = { };
var offsets = { };
var wasHidden = false;
// show element to retrieve dimensions and restore them later
if (this.is(':hidden')) {
css = WCF.getInlineCSS(this);
wasHidden = true;
this.css({
display: 'block',
visibility: 'hidden'
});
}
switch (type) {
case 'offset':
offsets = this.offset();
break;
case 'position':
default:
offsets = this.position();
break;
}
// restore previous settings
if (wasHidden) {
WCF.revertInlineCSS(this, css, [ 'display', 'visibility' ]);
}
return offsets;
},
/**
* Changes element's position to 'absolute' or 'fixed' while maintaining it's
* current position relative to viewport. Optionally removes element from
* current DOM-node and moving it into body-element (useful for drag & drop)
*
* @param boolean rebase
* @return object
*/
makePositioned: function(position, rebase) {
if (position != 'absolute' && position != 'fixed') {
position = 'absolute';
}
var $currentPosition = this.getOffsets('position');
this.css({
position: position,
left: $currentPosition.left,
margin: 0,
top: $currentPosition.top
});
if (rebase) {
this.remove().appentTo('body');
}
return this;
},
/**
* Disables a form element.
*
* @return jQuery
*/
disable: function() {
return this.attr('disabled', 'disabled');
},
/**
* Enables a form element.
*
* @return jQuery
*/
enable: function() {
return this.removeAttr('disabled');
},
/**
* Returns the element's id. If none is set, a random unique
* ID will be assigned.
*
* @return string
*/
wcfIdentify: function() {
return window.bc_wcfDomUtil.identify(this[0]);
},
/**
* Returns the caret position of current element. If the element
* does not equal input[type=text], input[type=password] or
* textarea, -1 is returned.
*
* @return integer
*/
getCaret: function() {
if (this.is('input')) {
if (this.attr('type') != 'text' && this.attr('type') != 'password') {
return -1;
}
}
else if (!this.is('textarea')) {
return -1;
}
var $position = 0;
var $element = this.get(0);
if (document.selection) { // IE 8
// set focus to enable caret on this element
this.focus();
var $selection = document.selection.createRange();
$selection.moveStart('character', -this.val().length);
$position = $selection.text.length;
}
else if ($element.selectionStart || $element.selectionStart == '0') { // Opera, Chrome, Firefox, Safari, IE 9+
$position = parseInt($element.selectionStart);
}
return $position;
},
/**
* Sets the caret position of current element. If the element
* does not equal input[type=text], input[type=password] or
* textarea, false is returned.
*
* @param integer position
* @return boolean
*/
setCaret: function (position) {
if (this.is('input')) {
if (this.attr('type') != 'text' && this.attr('type') != 'password') {
return false;
}
}
else if (!this.is('textarea')) {
return false;
}
var $element = this.get(0);
// set focus to enable caret on this element
this.focus();
if (document.selection) { // IE 8
var $selection = document.selection.createRange();
$selection.moveStart('character', position);
$selection.moveEnd('character', 0);
$selection.select();
}
else if ($element.selectionStart || $element.selectionStart == '0') { // Opera, Chrome, Firefox, Safari, IE 9+
$element.selectionStart = position;
$element.selectionEnd = position;
}
return true;
},
/**
* Shows an element by sliding and fading it into viewport.
*
* @param string direction
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfDropIn: function(direction, callback, duration) {
if (!direction) direction = 'up';
if (!duration || !parseInt(duration)) duration = 200;
return this.show(WCF.getEffect(this, 'drop'), { direction: direction }, duration, callback);
},
/**
* Hides an element by sliding and fading it out the viewport.
*
* @param string direction
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfDropOut: function(direction, callback, duration) {
if (!direction) direction = 'down';
if (!duration || !parseInt(duration)) duration = 200;
return this.hide(WCF.getEffect(this, 'drop'), { direction: direction }, duration, callback);
},
/**
* Shows an element by blinding it up.
*
* @param string direction
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfBlindIn: function(direction, callback, duration) {
if (!direction) direction = 'vertical';
if (!duration || !parseInt(duration)) duration = 200;
return this.show(WCF.getEffect(this, 'blind'), { direction: direction }, duration, callback);
},
/**
* Hides an element by blinding it down.
*
* @param string direction
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfBlindOut: function(direction, callback, duration) {
if (!direction) direction = 'vertical';
if (!duration || !parseInt(duration)) duration = 200;
return this.hide(WCF.getEffect(this, 'blind'), { direction: direction }, duration, callback);
},
/**
* Highlights an element.
*
* @param object options
* @param object callback
* @returns jQuery
*/
wcfHighlight: function(options, callback) {
return this.effect('highlight', options, 600, callback);
},
/**
* Shows an element by fading it in.
*
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfFadeIn: function(callback, duration) {
if (!duration || !parseInt(duration)) duration = 200;
return this.show(WCF.getEffect(this, 'fade'), { }, duration, callback);
},
/**
* Hides an element by fading it out.
*
* @param object callback
* @param integer duration
* @returns jQuery
*/
wcfFadeOut: function(callback, duration) {
if (!duration || !parseInt(duration)) duration = 200;
return this.hide(WCF.getEffect(this, 'fade'), { }, duration, callback);
},
/**
* Returns a CSS property as raw number.
*
* @param string property
*/
cssAsNumber: function(property) {
if (this.length) {
var $property = this.css(property);
if ($property !== undefined) {
return parseInt($property.replace(/px$/, ''));
}
}
return 0;
},
/**
* @deprecated Use perfectScrollbar directly.
*
* This is taken from the jQuery adaptor of perfect scrollbar.
* Copyright (c) 2015 Hyunje Alex Jun and other contributors
* Licensed under the MIT License
*/
perfectScrollbar: function (settingOrCommand) {
var ps = require('perfect-scrollbar');
return this.each(function () {
if (typeof settingOrCommand === 'object' ||
typeof settingOrCommand === 'undefined') {
// If it's an object or none, initialize.
var settings = settingOrCommand;
if (!$(this).data('psID'))
ps.initialize(this, settings);
} else {
// Unless, it may be a command.
var command = settingOrCommand;
if (command === 'update') {
ps.update(this);
} else if (command === 'destroy') {
ps.destroy(this);
}
}
return jQuery(this);
});
}
});
/**
* WoltLab Suite Core methods
*/
$.extend(WCF, {
/**
* count of active dialogs
* @var integer
*/
activeDialogs: 0,
/**
* Counter for dynamic element ids
*
* @var integer
*/
_idCounter: 0,
/**
* Returns a dynamically created id.
*
* @see https://github.com/sstephenson/prototype/blob/5e5cfff7c2c253eaf415c279f9083b4650cd4506/src/prototype/dom/dom.js#L1789
* @return string
*/
getRandomID: function() {
return window.bc_wcfDomUtil.getUniqueId();
},
/**
* Wrapper for $.inArray which returns boolean value instead of
* index value, similar to PHP's in_array().
*
* @param mixed needle
* @param array haystack
* @return boolean
*/
inArray: function(needle, haystack) {
return ($.inArray(needle, haystack) != -1);
},
/**
* Adjusts effect for partially supported elements.
*
* @param jQuery object
* @param string effect
* @return string
*/
getEffect: function(object, effect) {
// most effects are not properly supported on table rows, use highlight instead
if (object.is('tr')) {
return 'highlight';
}
return effect;
},
/**
* Returns inline CSS for given element.
*
* @param jQuery element
* @return object
*/
getInlineCSS: function(element) {
var $inlineStyles = { };
var $style = element.attr('style');
// no style tag given or empty
if (!$style) {
return { };
}
$style = $style.split(';');
for (var $i = 0, $length = $style.length; $i < $length; $i++) {
var $fragment = $.trim($style[$i]);
if ($fragment == '') {
continue;
}
$fragment = $fragment.split(':');
$inlineStyles[$.trim($fragment[0])] = $.trim($fragment[1]);
}
return $inlineStyles;
},
/**
* Reverts inline CSS or negates a previously set property.
*
* @param jQuery element
* @param object inlineCSS
* @param array<string> targetProperties
*/
revertInlineCSS: function(element, inlineCSS, targetProperties) {
for (var $i = 0, $length = targetProperties.length; $i < $length; $i++) {
var $property = targetProperties[$i];
// revert inline CSS
if (inlineCSS[$property]) {
element.css($property, inlineCSS[$property]);
}
else {
// negate inline CSS
element.css($property, '');
}
}
},
/**
* @deprecated Use WoltLabSuite/Core/Core.getUuid().
*/
getUUID: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
},
/**
* Converts a base64 encoded file into a native Blob.
*
* @param string base64data
* @param string contentType
* @param integer sliceSize
* @return Blob
*/
base64toBlob: function(base64data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var $byteCharacters = atob(base64data);
var $byteArrays = [ ];
for (var $offset = 0; $offset < $byteCharacters.length; $offset += sliceSize) {
var $slice = $byteCharacters.slice($offset, $offset + sliceSize);
var $byteNumbers = new Array($slice.length);
for (var $i = 0; $i < $slice.length; $i++) {
$byteNumbers[$i] = $slice.charCodeAt($i);
}
var $byteArray = new Uint8Array($byteNumbers);
$byteArrays.push($byteArray);
}
return new Blob($byteArrays, { type: contentType });
},
/**
* Converts legacy URLs to the URL schema used by WCF 2.1.
*
* @param string url
* @return string
*/
convertLegacyURL: function(url) {
if (URL_LEGACY_MODE) {
return url;
}
return url.replace(/^index\.php\/(.*?)\/\?/, function(match, controller) {
var $parts = controller.split(/([A-Z][a-z0-9]+)/);
var $controller = '';
for (var $i = 0, $length = $parts.length; $i < $length; $i++) {
var $part = $parts[$i].trim();
if ($part.length) {
if ($controller.length) $controller += '-';
$controller += $part.toLowerCase();
}
}
return 'index.php?' + $controller + '/&';
});
}
});
/**
* Browser related functions.
*/
WCF.Browser = {
/**
* determines if browser is chrome
* @var boolean
*/
_isChrome: null,
/**
* Returns true, if browser is Chrome, Chromium or using GoogleFrame for Internet Explorer.
*
* @return boolean
*/
isChrome: function() {
if (this._isChrome === null) {
this._isChrome = false;
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
this._isChrome = true;
}
}
return this._isChrome;
}
};
/**
* Dropdown API
*
* @deprecated 3.0 - please use `Ui/SimpleDropdown` instead
*/
WCF.Dropdown = {
/**
* Initializes dropdowns.
*/
init: function(api) {
window.bc_wcfSimpleDropdown.initAll();
},
/**
* Initializes a dropdown.
*
* @param jQuery button
* @param boolean isLazyInitialization
*/
initDropdown: function(button, isLazyInitialization) {
window.bc_wcfSimpleDropdown.init(button[0], isLazyInitialization);
},
/**
* Removes the dropdown with the given container id.
*
* @param string containerID
*/
removeDropdown: function(containerID) {
window.bc_wcfSimpleDropdown.remove(containerID);
},
/**
* Initializes a dropdown fragment which behaves like a usual dropdown
* but is not controlled by a trigger element.
*
* @param jQuery dropdown
* @param jQuery dropdownMenu
*/
initDropdownFragment: function(dropdown, dropdownMenu) {
window.bc_wcfSimpleDropdown.initFragment(dropdown[0], dropdownMenu[0]);
},
/**
* Registers a callback notified upon dropdown state change.
*
* @param string identifier
* @var object callback
*/
registerCallback: function(identifier, callback) {
window.bc_wcfSimpleDropdown.registerCallback(identifier, callback);
},
/**
* Toggles a dropdown.
*
* @param object event
* @param string targetID
*/
_toggle: function(event, targetID) {
window.bc_wcfSimpleDropdown._toggle(event, targetID);
},
/**
* Toggles a dropdown.
*
* @param string containerID
*/
toggleDropdown: function(containerID) {
window.bc_wcfSimpleDropdown._toggle(null, containerID);
},
/**
* Returns dropdown by container id.
*
* @param string containerID
* @return jQuery
*/
getDropdown: function(containerID) {
var dropdown = window.bc_wcfSimpleDropdown.getDropdown(containerID);
return (dropdown) ? $(dropdown) : null;
},
/**
* Returns dropdown menu by container id.
*
* @param string containerID
* @return jQuery
*/
getDropdownMenu: function(containerID) {
var menu = window.bc_wcfSimpleDropdown.getDropdownMenu(containerID);
return (menu) ? $(menu) : null;
},
/**
* Sets alignment for given container id.
*
* @param string containerID
*/
setAlignmentByID: function(containerID) {
window.bc_wcfSimpleDropdown.setAlignmentById(containerID);
},
/**
* Sets alignment for dropdown.
*
* @param jQuery dropdown
* @param jQuery dropdownMenu
*/
setAlignment: function(dropdown, dropdownMenu) {
window.bc_wcfSimpleDropdown.setAlignment(dropdown[0], dropdownMenu[0]);
},
/**
* Closes all dropdowns.
*/
_closeAll: function() {
window.bc_wcfSimpleDropdown.closeAll();
},
/**
* Closes a dropdown without notifying callbacks.
*
* @param string containerID
*/
close: function(containerID) {
window.bc_wcfSimpleDropdown.close(containerID);
},
/**
* Destroies an existing dropdown menu.
*
* @param string containerID
* @return boolean
*/
destroy: function(containerID) {
window.bc_wcfSimpleDropdown.destroy(containerID);
}
};
/**
* Namespace for interactive dropdowns.
*/
WCF.Dropdown.Interactive = { };
/**
* General interface to create and manage interactive dropdowns.
*/
WCF.Dropdown.Interactive.Handler = {
/**
* global container for interactive dropdowns
* @var jQuery
*/
_dropdownContainer: null,
/**
* list of dropdown instances by identifier
* @var object<WCF.Dropdown.Interactive.Instance>
*/
_dropdownMenus: { },
/**
* Creates a new interactive dropdown instance.
*
* @param jQuery triggerElement
* @param string identifier
* @param object options
* @return WCF.Dropdown.Interactive.Instance
*/
create: function(triggerElement, identifier, options) {
if (this._dropdownContainer === null) {
this._dropdownContainer = $('<div class="dropdownMenuContainer" />').appendTo(document.body);
WCF.CloseOverlayHandler.addCallback('WCF.Dropdown.Interactive.Handler', $.proxy(this.closeAll, this));
window.addEventListener('scroll', this.closeAll.bind(this));
}
var $instance = new WCF.Dropdown.Interactive.Instance(this._dropdownContainer, triggerElement, identifier, options);
this._dropdownMenus[identifier] = $instance;
return $instance;
},
/**
* Opens an interactive dropdown, returns false if identifier is unknown.
*
* @param string identifier
* @return boolean
*/
open: function(identifier) {
if (this._dropdownMenus[identifier]) {
this._dropdownMenus[identifier].open();
return true;
}
return false;
},
/**
* Closes an interactive dropdown, returns false if identifier is unknown.
*
* @param string identifier
* @return boolean
*/
close: function(identifier) {
if (this._dropdownMenus[identifier]) {
this._dropdownMenus[identifier].close();
return true;
}
return false;
},
/**
* Closes all interactive dropdowns.
*/
closeAll: function() {
$.each(this._dropdownMenus, function(identifier, instance) {
instance.close();
});
}
};
/**
* Represents and manages a single interactive dropdown instance.
*
* @param jQuery dropdownContainer
* @param jQuery triggerElement
* @param string identifier
* @param object options
*/
WCF.Dropdown.Interactive.Instance = Class.extend({
/**
* dropdown container
* @var jQuery
*/
_container: null,
/**
* inner item list
* @var jQuery
*/
_itemList: null,
/**
* header link list
* @var jQuery
*/
_linkList: null,
/**
* option list
* @var object
*/
_options: { },
/**
* arrow pointer
* @var jQuery
*/
_pointer: null,
/**
* trigger element
* @var jQuery
*/
_triggerElement: null,
/**
* Represents and manages a single interactive dropdown instance.
*
* @param jQuery dropdownContainer
* @param jQuery triggerElement
* @param string identifier
* @param object options
*/
init: function(dropdownContainer, triggerElement, identifier, options) {
this._options = options || { };
this._triggerElement = triggerElement;
var $itemContainer = null;
if (options.staticDropdown === true) {
this._container = this._triggerElement.find('.interactiveDropdownStatic:eq(0)').data('source', identifier).click(function(event) { event.stopPropagation(); });
}
else {
this._container = $('<div class="interactiveDropdown" data-source="' + identifier + '" />').click(function(event) { event.stopPropagation(); });
var $header = $('<div class="interactiveDropdownHeader" />').appendTo(this._container);
$('<span class="interactiveDropdownTitle">' + options.title + '</span>').appendTo($header);
this._linkList = $('<ul class="interactiveDropdownLinks inlineList"></ul>').appendTo($header);
$itemContainer = $('<div class="interactiveDropdownItemsContainer" />').appendTo(this._container);
this._itemList = $('<ul class="interactiveDropdownItems" />').appendTo($itemContainer);
$('<a href="' + options.showAllLink + '" class="interactiveDropdownShowAll">' + WCF.Language.get('wcf.user.panel.showAll') + '</a>').appendTo(this._container);
}
this._pointer = $('<span class="elementPointer"><span /></span>').appendTo(this._container);
require(['Environment'], function(Environment) {
if (Environment.platform() === 'desktop' && $itemContainer !== null) {
// use jQuery scrollbar on desktop, mobile browsers have a similar display built-in
$itemContainer.perfectScrollbar({
suppressScrollX: true
});
}
});
this._container.appendTo(dropdownContainer);
},
/**
* Returns the dropdown container.
*
* @return jQuery
*/
getContainer: function() {
return this._container;
},
/**
* Returns the inner item list.
*
* @return jQuery
*/
getItemList: function() {
return this._itemList;
},
/**
* Returns the header link list.
*
* @return jQuery
*/
getLinkList: function() {
return this._linkList;
},
/**
* Opens the dropdown.
*/
open: function() {
WCF.Dropdown._closeAll();
this._triggerElement.addClass('open');
this._container.addClass('open');
this.render();
},
/**
* Closes the dropdown
*/
close: function() {
this._triggerElement.removeClass('open');
this._container.removeClass('open');
},
/**
* Returns true if dropdown instance is visible.
*
* @returns {boolean}
*/
isOpen: function() {
return this._triggerElement.hasClass('open');
},
/**
* Toggles the dropdown state, returns true if dropdown is open afterwards, else false.
*
* @return boolean
*/
toggle: function() {
if (this._container.hasClass('open')) {
this.close();
return false;
}
else {
WCF.Dropdown.Interactive.Handler.closeAll();
this.open();
return true;
}
},
/**
* Resets the inner item list and closes the dropdown.
*/
resetItems: function() {
this._itemList.empty();
this.close();
},
/**
* Renders the dropdown.
*/
render: function() {
if (window.matchMedia('(max-width: 767px)').matches) {
this._container.css({
bottom: '',
left: '',
right: '',
top: elById('pageHeader').clientHeight + 'px'
});
}
else {
require(['Ui/Alignment'], (function(UiAlignment) {
UiAlignment.set(this._container[0], this._triggerElement[0], {
horizontal: 'right',
pointer: true
});
}).bind(this));
}
},
/**
* Rebuilds the desktop scrollbar.
*/
rebuildScrollbar: function() {
require(['Environment'], function(Environment) {
if (Environment.platform() === 'desktop') {
var $itemContainer = this._itemList.parent();
// do NOT use 'update', seems to be broken
$itemContainer.perfectScrollbar('destroy');
$itemContainer.perfectScrollbar({
suppressScrollX: true
});
}
}.bind(this));
}
});
/**
* Clipboard API
*
* @deprecated 3.0 - please use `WoltLabSuite/Core/Controller/Clipboard` instead
*/
WCF.Clipboard = {
/**
* Initializes the clipboard API.
*
* @param string page
* @param integer hasMarkedItems
* @param object actionObjects
* @param integer pageObjectID
*/
init: function(page, hasMarkedItems, actionObjects, pageObjectID) {
require(['WoltLabSuite/Core/Controller/Clipboard'], function(ControllerClipboard) {
ControllerClipboard.setup({
hasMarkedItems: (hasMarkedItems > 0),
pageClassName: page,
pageObjectId: pageObjectID
});
});
},
/**
* Reloads the list of marked items.
*/
reload: function() {
require(['WoltLabSuite/Core/Controller/Clipboard'], function(ControllerClipboard) {
ControllerClipboard.reload();
});
}
};
/**
* @deprecated Use WoltLabSuite/Core/Timer/Repeating
*/
WCF.PeriodicalExecuter = Class.extend({
/**
* callback for each execution cycle
* @var object
*/
_callback: null,
/**
* interval
* @var integer
*/
_delay: 0,
/**
* interval id
* @var integer
*/
_intervalID: null,
/**
* execution state
* @var boolean
*/
_isExecuting: false,
/**
* Initializes a periodical executer.
*
* @param function callback
* @param integer delay
*/
init: function(callback, delay) {
if (!$.isFunction(callback)) {
console.debug('[WCF.PeriodicalExecuter] Given callback is invalid, aborting.');
return;
}
this._callback = callback;
this._interval = delay;
this.resume();
},
/**
* Executes callback.
*/
_execute: function() {
if (!this._isExecuting) {
try {
this._isExecuting = true;
this._callback(this);
this._isExecuting = false;
}
catch (e) {
this._isExecuting = false;
throw e;
}
}
},
/**
* Terminates loop.
*/
stop: function() {
if (!this._intervalID) {
return;
}
clearInterval(this._intervalID);
},
/**
* Resumes the interval-based callback execution.
*
* @deprecated 2.1 - use restart() instead
*/
resume: function() {
this.restart();
},
/**
* Restarts the interval-based callback execution.
*/
restart: function() {
if (this._intervalID) {
this.stop();
}
this._intervalID = setInterval($.proxy(this._execute, this), this._interval);
},
/**
* Sets the interval and restarts the interval.
*
* @param integer interval
*/
setInterval: function(interval) {
this._interval = interval;
this.restart();
}
});
/**
* Handler for loading overlays
*
* @deprecated 3.0 - Please use WoltLabSuite/Core/Ajax/Status
*/
WCF.LoadingOverlayHandler = {
/**
* Adds one loading-request and shows the loading overlay if nessercery
*/
show: function() {
require(['WoltLabSuite/Core/Ajax/Status'], function(AjaxStatus) {
AjaxStatus.show();
});
},
/**
* Removes one loading-request and hides loading overlay if there're no more pending requests
*/
hide: function() {
require(['WoltLabSuite/Core/Ajax/Status'], function(AjaxStatus) {
AjaxStatus.hide();
});
},
/**
* Updates a icon to/from spinner
*
* @param jQuery target
* @pram boolean loading
*/
updateIcon: function(target, loading) {
var $method = (loading === undefined || loading ? 'addClass' : 'removeClass');
target.find('.icon')[$method]('fa-spinner');
if (target.hasClass('icon')) {
target[$method]('fa-spinner');
}
}
};
/**
* Namespace for AJAXProxies
*/
WCF.Action = {};
/**
* Basic implementation for AJAX-based proxyies
*
* @deprecated 3.0 - please use `WoltLabSuite/Core/Ajax.api()` instead
*
* @param object options
*/
WCF.Action.Proxy = Class.extend({
_ajaxRequest: null,
/**
* Initializes AJAXProxy.
*
* @param object options
*/
init: function(options) {
this._ajaxRequest = null;
options = $.extend(true, {
autoSend: false,
data: { },
dataType: 'json',
after: null,
init: null,
jsonp: 'callback',
async: true,
failure: null,
showLoadingOverlay: true,
success: null,
suppressErrors: false,
type: 'POST',
url: 'index.php?ajax-proxy/&t=' + SECURITY_TOKEN,
aborted: null,
autoAbortPrevious: false
}, options);
if (options.dataType === 'jsonp') {
require(['AjaxJsonp'], function(AjaxJsonp) {
AjaxJsonp.send(options.url, options.success, options.failure, {
parameterName: options.jsonp
});
});
}
else {
require(['AjaxRequest'], (function(AjaxRequest) {
this._ajaxRequest = new AjaxRequest({
data: options.data,
type: options.type,
url: options.url,
responseType: (options.dataType === 'json' ? 'application/json' : ''),
autoAbort: options.autoAbortPrevious,
ignoreError: options.suppressErrors,
silent: !options.showLoadingOverlay,
failure: options.failure,
finalize: options.after,
success: options.success
});
if (options.autoSend) {
this._ajaxRequest.sendRequest();
}
}).bind(this));
}
},
/**
* Sends an AJAX request.
*
* @param abortPrevious boolean
*/
sendRequest: function(abortPrevious) {
require(['AjaxRequest'], (function(AjaxRequest) {
if (this._ajaxRequest !== null) {
this._ajaxRequest.sendRequest(abortPrevious);
}
}).bind(this));
},
/**
* Aborts the previous request
*/
abortPrevious: function() {
require(['AjaxRequest'], (function(AjaxRequest) {
if (this._ajaxRequest !== null) {
this._ajaxRequest.abortPrevious();
}
}).bind(this));
},
/**
* Sets options, MUST be used to set parameters before sending request
* if calling from child classes.
*
* @param string optionName
* @param mixed optionData
*/
setOption: function(optionName, optionData) {
require(['AjaxRequest'], (function(AjaxRequest) {
if (this._ajaxRequest !== null) {
this._ajaxRequest.setOption(optionName, optionData);
}
}).bind(this));
},
// legacy methods, no longer supported
showLoadingOverlayOnce: function() {},
suppressErrors: function() {},
_failure: function(jqXHR, textStatus, errorThrown) {},
_success: function(data, textStatus, jqXHR) {},
_after: function() {}
});
/**
* Basic implementation for simple proxy access using bound elements.
*
* @param object options
* @param object callbacks
*/
WCF.Action.SimpleProxy = Class.extend({
/**
* Initializes SimpleProxy.
*
* @param object options
* @param object callbacks
*/
init: function(options, callbacks) {
/**
* action-specific options
*/
this.options = $.extend(true, {
action: '',
className: '',
elements: null,
eventName: 'click'
}, options);
/**
* proxy-specific options
*/
this.callbacks = $.extend(true, {
after: null,
failure: null,
init: null,
success: null
}, callbacks);
if (!this.options.elements) return;
// initialize proxy
this.proxy = new WCF.Action.Proxy(this.callbacks);
// bind event listener
this.options.elements.each($.proxy(function(index, element) {
$(element).bind(this.options.eventName, $.proxy(this._handleEvent, this));
}, this));
},
/**
* Handles event actions.
*
* @param object event
*/
_handleEvent: function(event) {
this.proxy.setOption('data', {
actionName: this.options.action,
className: this.options.className,
objectIDs: [ $(event.target).data('objectID') ]
});
this.proxy.sendRequest();
}
});
/**
* Basic implementation for AJAXProxy-based deletion.
*
* @param string className
* @param string containerSelector
* @param string buttonSelector
*/
WCF.Action.Delete = Class.extend({
/**
* delete button selector
* @var string
*/
_buttonSelector: '',
/**
* action class name
* @var string
*/
_className: '',
/**
* container selector
* @var string
*/
_containerSelector: '',
/**
* list of known container ids
* @var array<string>
*/
_containers: [ ],
/**
* Initializes 'delete'-Proxy.
*
* @param string className
* @param string containerSelector
* @param string buttonSelector
*/
init: function(className, containerSelector, buttonSelector) {
this._containerSelector = containerSelector;
this._className = className;
this._buttonSelector = (buttonSelector) ? buttonSelector : '.jsDeleteButton';
this.proxy = new WCF.Action.Proxy({
success: $.proxy(this._success, this)
});
this._initElements();
WCF.DOMNodeInsertedHandler.addCallback('WCF.Action.Delete' + this._className.hashCode(), $.proxy(this._initElements, this));
},
/**
* Initializes available element containers.
*/
_initElements: function() {
$(this._containerSelector).each((function(index, container) {
var $container = $(container);
var $containerID = $container.wcfIdentify();
if (!WCF.inArray($containerID, this._containers)) {
var $deleteButton = $container.find(this._buttonSelector);
if ($deleteButton.length) {
this._containers.push($containerID);
$deleteButton.click($.proxy(this._click, this));
}
}
}).bind(this));
},
/**
* Sends AJAX request.
*
* @param object event
*/
_click: function(event) {
var $target = $(event.currentTarget);
event.preventDefault();
if ($target.data('confirmMessageHtml') || $target.data('confirmMessage')) {
WCF.System.Confirmation.show($target.data('confirmMessageHtml') ? $target.data('confirmMessageHtml') : $target.data('confirmMessage'), $.proxy(this._execute, this), { target: $target }, undefined, $target.data('confirmMessageHtml') ? true : false);
}
else {
WCF.LoadingOverlayHandler.updateIcon($target);
this._sendRequest($target);
}
},
/**
* Is called if the delete effect has been triggered on the given element.
*
* @param jQuery element
*/
_didTriggerEffect: function(element) {
// does nothing
},
/**
* Executes deletion.
*
* @param string action
* @param object parameters
*/
_execute: function(action, parameters) {
if (action === 'cancel') {
return;
}
WCF.LoadingOverlayHandler.updateIcon(parameters.target);
this._sendRequest(parameters.target);
},
/**
* Sends the request
*
* @param jQuery object
*/
_sendRequest: function(object) {
this.proxy.setOption('data', {
actionName: 'delete',
className: this._className,
interfaceName: 'wcf\\data\\IDeleteAction',
objectIDs: [ $(object).data('objectID') ]
});
this.proxy.sendRequest();
},
/**
* Deletes items from containers.
*
* @param object data
* @param string textStatus
* @param object jqXHR
*/
_success: function(data, textStatus, jqXHR) {
this.triggerEffect(data.objectIDs);
},
/**
* Triggers the delete effect for the objects with the given ids.
*
* @param array objectIDs
*/
triggerEffect: function(objectIDs) {
for (var $index in this._containers) {
var $container = $('#' + this._containers[$index]);
var $button = $container.find(this._buttonSelector);
if (WCF.inArray($button.data('objectID'), objectIDs)) {
var self = this;
$container.wcfBlindOut('up',function() {
var $container = $(this).remove();
self._containers.splice(self._containers.indexOf($container.wcfIdentify()), 1);
self._didTriggerEffect($container);
if ($button.data('eventName')) {
WCF.System.Event.fireEvent('com.woltlab.wcf.action.delete', $button.data('eventName'), {
button: $button,
container: $container
});
}
});
}
}
}
});
/**
* Basic implementation for deletion of nested elements.
*
* The implementation requires the nested elements to be grouped as numbered lists
* (ol lists). The child elements of the deleted elements are moved to the parent
* element of the deleted element.
*
* @see WCF.Action.Delete
*/
WCF.Action.NestedDelete = WCF.Action.Delete.extend({
/**
* @see WCF.Action.Delete.triggerEffect()
*/
triggerEffect: function(objectIDs) {
for (var $index in this._containers) {
var $container = $('#' + this._containers[$index]);
if (WCF.inArray($container.find(this._buttonSelector).data('objectID'), objectIDs)) {
// move children up
if ($container.has('ol').has('li').length) {
if ($container.is(':only-child')) {
$container.parent().replaceWith($container.find('> ol'));
}
else {
$container.replaceWith($container.find('> ol > li'));
}
this._containers.splice(this._containers.indexOf($container.wcfIdentify()), 1);
this._didTriggerEffect($container);
}
else {
var self = this;
$container.wcfBlindOut('up', function() {
$(this).remove();
self._containers.splice(self._containers.indexOf($(this).wcfIdentify()), 1);
self._didTriggerEffect($(this));
});
}
}
}
}
});
/**
* Basic implementation for AJAXProxy-based toggle actions.
*
* @param string className
* @param jQuery containerList
* @param string buttonSelector
*/
WCF.Action.Toggle = Class.extend({
/**
* toogle button selector
* @var string
*/
_buttonSelector: '.jsToggleButton',
/**
* action class name
* @var string
*/
_className: '',
/**
* container selector
* @var string
*/
_containerSelector: '',
/**
* list of known container ids
* @var array<string>
*/
_containers: [ ],
/**
* Initializes 'toggle'-Proxy
*
* @param string className
* @param string containerSelector
* @param string buttonSelector
*/
init: function(className, containerSelector, buttonSelector) {
this._containerSelector = containerSelector;
this._className = className;
this._buttonSelector = (buttonSelector) ? buttonSelector : '.jsToggleButton';
this._containers = [ ];
// initialize proxy
var options = {
success: $.proxy(this._success, this)
};
this.proxy = new WCF.Action.Proxy(options);
// bind event listener
this._initElements();
WCF.DOMNodeInsertedHandler.addCallback('WCF.Action.Toggle' + this._className.hashCode(), $.proxy(this._initElements, this));
},
/**
* Initializes available element containers.
*/
_initElements: function() {
$(this._containerSelector).each($.proxy(function(index, container) {
var $container = $(container);
var $containerID = $container.wcfIdentify();
if (!WCF.inArray($containerID, this._containers)) {
this._containers.push($containerID);
$container.find(this._buttonSelector).click($.proxy(this._click, this));
}
}, this));
},
/**
* Sends AJAX request.
*
* @param object event
*/
_click: function(event) {
var $target = $(event.currentTarget);
event.preventDefault();
if ($target.data('confirmMessageHtml') || $target.data('confirmMessage')) {
WCF.System.Confirmation.show($target.data('confirmMessageHtml') ? $target.data('confirmMessageHtml') : $target.data('confirmMessage'), $.proxy(this._execute, this), { target: $target }, undefined, $target.data('confirmMessageHtml') ? true : false);
}
else {
WCF.LoadingOverlayHandler.updateIcon($target);
this._sendRequest($target);
}
},
/**
* Executes toggeling.
*
* @param string action
* @param object parameters
*/
_execute: function(action, parameters) {
if (action === 'cancel') {
return;
}
WCF.LoadingOverlayHandler.updateIcon(parameters.target);
this._sendRequest(parameters.target);
},
_sendRequest: function(object) {
this.proxy.setOption('data', {
actionName: 'toggle',
className: this._className,
interfaceName: 'wcf\\data\\IToggleAction',
objectIDs: [ $(object).data('objectID') ]
});
this.proxy.sendRequest();
},
/**
* Toggles status icons.
*
* @param object data
* @param string textStatus
* @param object jqXHR
*/
_success: function(data, textStatus, jqXHR) {
this.triggerEffect(data.objectIDs);
},
/**
* Triggers the toggle effect for the objects with the given ids.
*
* @param array objectIDs
*/
triggerEffect: function(objectIDs) {
for (var $index in this._containers) {
var $container = $('#' + this._containers[$index]);
var $toggleButton = $container.find(this._buttonSelector);
if (WCF.inArray($toggleButton.data('objectID'), objectIDs)) {
$container.wcfHighlight();
this._toggleButton($container, $toggleButton);
}
}
},
/**
* Tiggers the toggle effect on a button
*
* @param jQuery $container
* @param jQuery $toggleButton
*/
_toggleButton: function($container, $toggleButton) {
var $newTitle = '';
// toggle icon source
WCF.LoadingOverlayHandler.updateIcon($toggleButton, false);
if ($toggleButton.hasClass('fa-square-o')) {
$toggleButton.removeClass('fa-square-o').addClass('fa-check-square-o');
$newTitle = ($toggleButton.data('disableTitle') ? $toggleButton.data('disableTitle') : WCF.Language.get('wcf.global.button.disable'));
$toggleButton.attr('title', $newTitle);
}
else {
$toggleButton.removeClass('fa-check-square-o').addClass('fa-square-o');
$newTitle = ($toggleButton.data('enableTitle') ? $toggleButton.data('enableTitle') : WCF.Language.get('wcf.global.button.enable'));
$toggleButton.attr('title', $newTitle);
}
// toggle css class
$container.toggleClass('disabled');
}
});
/**
* Executes provided callback if scroll threshold is reached. Usuable to determine
* if user reached the bottom of an element to load new elements on the fly.
*
* If you do not provide a value for 'reference' and 'target' it will assume you're
* monitoring page scrolls, otherwise a valid jQuery selector must be provided for both.
*
* @param integer threshold
* @param object callback
* @param string reference
* @param string target
*/
WCF.Action.Scroll = Class.extend({
/**
* callback used once threshold is reached
* @var object
*/
_callback: null,
/**
* reference object
* @var jQuery
*/
_reference: null,
/**
* target object
* @var jQuery
*/
_target: null,
/**
* threshold value
* @var integer
*/
_threshold: 0,
/**
* Initializes a new WCF.Action.Scroll object.
*
* @param integer threshold
* @param object callback
* @param string reference
* @param string target
*/
init: function(threshold, callback, reference, target) {
this._threshold = parseInt(threshold);
if (this._threshold === 0) {
console.debug("[WCF.Action.Scroll] Given threshold is invalid, aborting.");
return;
}
if ($.isFunction(callback)) this._callback = callback;
if (this._callback === null) {
console.debug("[WCF.Action.Scroll] Given callback is invalid, aborting.");
return;
}
// bind element references
this._reference = $((reference) ? reference : window);
this._target = $((target) ? target : document);
// watch for scroll event
this.start();
// check if browser navigated back and jumped to offset before JavaScript was loaded
this._scroll();
},
/**
* Calculates if threshold is reached and notifies callback.
*/
_scroll: function() {
var $targetHeight = this._target.height();
var $topOffset = this._reference.scrollTop();
var $referenceHeight = this._reference.height();
// calculate if defined threshold is visible
if (($targetHeight - ($referenceHeight + $topOffset)) < this._threshold) {
this._callback(this);
}
},
/**
* Enables scroll monitoring, may be used to resume.
*/
start: function() {
this._reference.on('scroll', $.proxy(this._scroll, this));
},
/**
* Disables scroll monitoring, e.g. no more elements loadable.
*/
stop: function() {
this._reference.off('scroll');
}
});
/**
* Namespace for date-related functions.
*/
WCF.Date = {};
/**
* Provides a date picker for date input fields.
*
* @deprecated 3.0 - no longer required
*/
WCF.Date.Picker = { init: function() {} };
/**
* Provides utility functions for date operations.
*
* @deprecated 3.0 - use `DateUtil` instead
*/
WCF.Date.Util = {
/**
* Returns UTC timestamp, if date is not given, current time will be used.
*
* @param Date date
* @return integer
*
* @deprecated 3.0 - use `DateUtil::gmdate()` instead
*/
gmdate: function(date) {
var $date = (date) ? date : new Date();
return Math.round(Date.UTC(
$date.getUTCFullYear(),
$date.getUTCMonth(),
$date.getUTCDay(),
$date.getUTCHours(),
$date.getUTCMinutes(),
$date.getUTCSeconds()
) / 1000);
},
/**
* Returns a Date object with precise offset (including timezone and local timezone).
* Parameters timestamp and offset must be in miliseconds!
*
* @param integer timestamp
* @param integer offset
* @return Date
*
* @deprecated 3.0 - use `DateUtil::getTimezoneDate()` instead
*/
getTimezoneDate: function(timestamp, offset) {
var $date = new Date(timestamp);
var $localOffset = $date.getTimezoneOffset() * 60000;
return new Date((timestamp + $localOffset + offset));
}
};
/**
* Hash-like dictionary. Based upon idead from Prototype's hash
*
* @see https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/hash.js
*/
WCF.Dictionary = Class.extend({
/**
* list of variables
* @var object
*/
_variables: { },
/**
* Initializes a new dictionary.
*/
init: function() {
this._variables = { };
},
/**
* Adds an entry.
*
* @param string key
* @param mixed value
*/
add: function(key, value) {
this._variables[key] = value;
},
/**
* Adds a traditional object to current dataset.
*
* @param object object
*/
addObject: function(object) {
for (var $key in object) {
this.add($key, object[$key]);
}
},
/**
* Adds a dictionary to current dataset.
*
* @param object dictionary
*/
addDictionary: function(dictionary) {
dictionary.each($.proxy(function(pair) {
this.add(pair.key, pair.value);
}, this));
},
/**
* Retrieves the value of an entry or returns null if key is not found.
*
* @param string key
* @returns mixed
*/
get: function(key) {
if (this.isset(key)) {
return this._variables[key];
}
return null;
},
/**
* Returns true if given key is a valid entry.
*
* @param string key
*/
isset: function(key) {
return this._variables.hasOwnProperty(key);
},
/**
* Removes an entry.
*
* @param string key
*/
remove: function(key) {
delete this._variables[key];
},
/**
* Iterates through dictionary.
*
* Usage:
* var $hash = new WCF.Dictionary();
* $hash.add('foo', 'bar');
* $hash.each(function(pair) {
* // alerts: foo = bar
* alert(pair.key + ' = ' + pair.value);
* });
*
* @param function callback
*/
each: function(callback) {
if (!$.isFunction(callback)) {
return;
}
for (var $key in this._variables) {
var $value = this._variables[$key];
var $pair = {
key: $key,
value: $value
};
callback($pair);
}
},
/**
* Returns the amount of items.
*
* @return integer
*/
count: function() {
return $.getLength(this._variables);
},
/**
* Returns true if dictionary is empty.
*
* @return integer
*/
isEmpty: function() {
return !this.count();
}
});
// non strict equals by intent
if (window.WCF.Language == null) {
/**
* @deprecated Use WoltLabSuite/Core/Language
*/
WCF.Language = {
add: function(key, value) {
require(['Language'], function(Language) {
Language.add(key, value);
});
},
addObject: function(object) {
require(['Language'], function(Language) {
Language.addObject(object);
});
},
get: function(key, parameters) {
// This cannot be sanely provided as a compatibility wrapper.
throw new Error('Call to deprecated WCF.Language.get("' + key + '")');
}
};
}
/**
* Handles multiple language input fields.
*
* @param string elementID
* @param boolean forceSelection
* @param object values
* @param object availableLanguages
*/
WCF.MultipleLanguageInput = Class.extend({
/**
* list of available languages
* @var object
*/
_availableLanguages: {},
/**
* button element
* @var jQuery
*/
_button: null,
/**
* initialization state
* @var boolean
*/
_didInit: false,
/**
* target input element
* @var jQuery
*/
_element: null,
/**
* true, if data was entered after initialization
* @var boolean
*/
_insertedDataAfterInit: false,
/**
* enables multiple language ability
* @var boolean
*/
_isEnabled: false,
/**
* enforce multiple language ability
* @var boolean
*/
_forceSelection: false,
/**
* currently active language id
* @var integer
*/
_languageID: 0,
/**
* language selection list
* @var jQuery
*/
_list: null,
/**
* list of language values on init
* @var object
*/
_values: null,
/**
* Initializes multiple language ability for given element id.
*
* @param integer elementID
* @param boolean forceSelection
* @param boolean isEnabled
* @param object values
* @param object availableLanguages
*/
init: function(elementID, forceSelection, values, availableLanguages) {
this._button = null;
this._element = $('#' + $.wcfEscapeID(elementID));
this._forceSelection = forceSelection;
this._values = values;
this._availableLanguages = availableLanguages;
// unescape values
if ($.getLength(this._values)) {
for (var $key in this._values) {
this._values[$key] = WCF.String.unescapeHTML(this._values[$key]);
}
}
// default to current user language
this._languageID = LANGUAGE_ID;
if (this._element.length == 0) {
console.debug("[WCF.MultipleLanguageInput] element id '" + elementID + "' is unknown");
return;
}
// build selection handler
var $enableOnInit = ($.getLength(this._values) > 0) ? true : false;
this._insertedDataAfterInit = $enableOnInit;
this._prepareElement($enableOnInit);
// listen for submit event
this._element.parents('form').submit($.proxy(this._submit, this));
this._didInit = true;
},
/**
* Builds language handler.
*
* @param boolean enableOnInit
*/
_prepareElement: function(enableOnInit) {
this._element.wrap('<div class="dropdown preInput" />');
var $wrapper = this._element.parent();
this._button = $('<p class="button dropdownToggle"><span>' + WCF.Language.get('wcf.global.button.disabledI18n') + '</span></p>').prependTo($wrapper);
// insert list
this._list = $('<ul class="dropdownMenu"></ul>').insertAfter(this._button);
// add a special class if next item is a textarea
if (this._button.nextAll('textarea').length) {
this._button.addClass('dropdownCaptionTextarea');
}
else {
this._button.addClass('dropdownCaption');
}
// insert available languages
for (var $languageID in this._availableLanguages) {
$('<li><span>' + this._availableLanguages[$languageID] + '</span></li>').data('languageID', $languageID).click($.proxy(this._changeLanguage, this)).appendTo(this._list);
}
// disable language input
if (!this._forceSelection) {
$('<li class="dropdownDivider" />').appendTo(this._list);
$('<li><span>' + WCF.Language.get('wcf.global.button.disabledI18n') + '</span></li>').click($.proxy(this._disable, this)).appendTo(this._list);
}
WCF.Dropdown.initDropdown(this._button, enableOnInit);
if (enableOnInit || this._forceSelection) {
this._isEnabled = true;
// pre-select current language
this._list.children('li').each($.proxy(function(index, listItem) {
var $listItem = $(listItem);
if ($listItem.data('languageID') == this._languageID) {
$listItem.trigger('click');
}
}, this));
}
WCF.Dropdown.registerCallback($wrapper.wcfIdentify(), $.proxy(this._handleAction, this));
},
/**
* Handles dropdown actions.
*
* @param string containerID
* @param string action
*/
_handleAction: function(containerID, action) {
if (action === 'open') {
this._enable();
}
else {
this._closeSelection();
}
},
/**
* Enables the language selection or shows the selection if already enabled.
*
* @param object event
*/
_enable: function(event) {
if (!this._isEnabled) {
var $button = (this._button.is('p')) ? this._button.children('span:eq(0)') : this._button;
$button.addClass('active');
this._isEnabled = true;
}
// toggle list
if (this._list.is(':visible')) {
this._showSelection();
}
},
/**
* Shows the language selection.
*/
_showSelection: function() {
if (this._isEnabled) {
// display status for each language
this._list.children('li').each($.proxy(function(index, listItem) {
var $listItem = $(listItem);
var $languageID = $listItem.data('languageID');
if ($languageID) {
if (this._values[$languageID] && this._values[$languageID] != '') {
$listItem.removeClass('missingValue');
}
else {
$listItem.addClass('missingValue');
}
}
}, this));
}
},
/**
* Closes the language selection.
*/
_closeSelection: function() {
this._disable();
},
/**
* Changes the currently active language.
*
* @param object event
*/
_changeLanguage: function(event) {
var $button = $(event.currentTarget);
this._insertedDataAfterInit = true;
// save current value
if (this._didInit) {
this._values[this._languageID] = this._element.val();
}
// set new language
this._languageID = $button.data('languageID');
if (this._values[this._languageID]) {
this._element.val(this._values[this._languageID]);
}
else {
this._element.val('');
}
// update marking
this._list.children('li').removeClass('active');
$button.addClass('active');
// update label
this._button.children('span').addClass('active').text(this._availableLanguages[this._languageID]);
// close selection and set focus on input element
if (this._didInit) {
this._element.blur().focus();
}
},
/**
* Disables language selection for current element.
*
* @param object event
*/
_disable: function(event) {
if (event === undefined && this._insertedDataAfterInit) {
event = null;
}
if (this._forceSelection || !this._list || event === null) {
return;
}
// remove active marking
this._button.children('span').removeClass('active').text(WCF.Language.get('wcf.global.button.disabledI18n'));
// update element value
if (this._values[LANGUAGE_ID]) {
this._element.val(this._values[LANGUAGE_ID]);
}
else {
// no value for current language found, proceed with empty input
this._element.val();
}
if (event) {
this._list.children('li').removeClass('active');
$(event.currentTarget).addClass('active');
}
this._element.blur().focus();
this._insertedDataAfterInit = false;
this._isEnabled = false;
this._values = { };
},
/**
* Prepares language variables on before submit.
*/
_submit: function() {
// insert hidden form elements on before submit
if (!this._isEnabled) {
return 0xDEADBEEF;
}
// fetch active value
if (this._languageID) {
this._values[this._languageID] = this._element.val();
}
var $form = $(this._element.parents('form')[0]);
var $elementID = this._element.wcfIdentify();
for (var $languageID in this._availableLanguages) {
if (this._values[$languageID] === undefined) {
this._values[$languageID] = '';
}
$('<input type="hidden" name="' + $elementID + '_i18n[' + $languageID + ']" value="' + WCF.String.escapeHTML(this._values[$languageID]) + '" />').appendTo($form);
}
// remove name attribute to prevent conflict with i18n values
this._element.removeAttr('name');
}
});
/**
* Number utilities.
* @deprecated Use WoltLabSuite/Core/NumberUtil
*/
WCF.Number = {
/**
* Rounds a number to a given number of decimal places. Defaults to 0.
*
* @param number number
* @param decimalPlaces number of decimal places
* @return number
*/
round: function (number, decimalPlaces) {
decimalPlaces = Math.pow(10, (decimalPlaces || 0));
return Math.round(number * decimalPlaces) / decimalPlaces;
}
};
/**
* String utilities.
* @deprecated Use WoltLabSuite/Core/StringUtil
*/
WCF.String = {
/**
* Adds thousands separators to a given number.
*
* @see http://stackoverflow.com/a/6502556/782822
* @param mixed number
* @return string
*/
addThousandsSeparator: function(number) {
return String(number).replace(/(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1' + WCF.Language.get('wcf.global.thousandsSeparator'));
},
/**
* Escapes special HTML-characters within a string
*
* @param string string
* @return string
*/
escapeHTML: function (string) {
return String(string).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
},
/**
* Escapes a String to work with RegExp.
*
* @see https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/regexp.js#L25
* @param string string
* @return string
*/
escapeRegExp: function(string) {
return String(string).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
},
/**
* Rounds number to given count of floating point digits, localizes decimal-point and inserts thousands-separators
*
* @param mixed number
* @return string
*/
formatNumeric: function(number, decimalPlaces) {
number = String(WCF.Number.round(number, decimalPlaces || 2));
var numberParts = number.split('.');
number = this.addThousandsSeparator(numberParts[0]);
if (numberParts.length > 1) number += WCF.Language.get('wcf.global.decimalPoint') + numberParts[1];
number = number.replace('-', '\u2212');
return number;
},
/**
* Makes a string's first character lowercase
*
* @param string string
* @return string
*/
lcfirst: function(string) {
return String(string).substring(0, 1).toLowerCase() + string.substring(1);
},
/**
* Makes a string's first character uppercase
*
* @param string string
* @return string
*/
ucfirst: function(string) {
return String(string).substring(0, 1).toUpperCase() + string.substring(1);
},
/**
* Unescapes special HTML-characters within a string
*
* @param string string
* @return string
*/
unescapeHTML: function (string) {
return String(string).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
};
/**
* Basic implementation for WCF TabMenus. Use the data attributes 'active' to specify the
* tab which should be shown on init. Furthermore you may specify a 'store' data-attribute
* which will be filled with the currently selected tab.
*/
WCF.TabMenu = {
/**
* Initializes all TabMenus
*/
init: function() {
require(['WoltLabSuite/Core/Ui/TabMenu'], function(UiTabMenu) {
UiTabMenu.setup();
});
},
/**
* Reloads the tab menus.
*/
reload: function() {
this.init();
}
};
/**
* Templates that may be fetched more than once with different variables.
* Based upon ideas from Prototype's template.
*
* Usage:
* var myTemplate = new WCF.Template('{$hello} World');
* myTemplate.fetch({ hello: 'Hi' }); // Hi World
* myTemplate.fetch({ hello: 'Hello' }); // Hello World
*
* my2ndTemplate = new WCF.Template('{@$html}{$html}');
* my2ndTemplate.fetch({ html: '<b>Test</b>' }); // <b>Test</b><b>Test</b>
*
* var my3rdTemplate = new WCF.Template('You can use {literal}{$variable}{/literal}-Tags here');
* my3rdTemplate.fetch({ variable: 'Not shown' }); // You can use {$variable}-Tags here
*
* @param template template-content
* @see https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/template.js
*/
WCF.Template = Class.extend({
/**
* Prepares template
*
* @param $template template-content
*/
init: function(template) {
var $literals = new WCF.Dictionary();
var $tagID = 0;
// escape \ and ' and newlines
template = template.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/(\r\n|\n|\r)/g, '\\n');
// save literal-tags
template = template.replace(/\{literal\}(.*?)\{\/literal\}/g, $.proxy(function(match) {
// hopefully no one uses this string in one of his templates
var id = '@@@@@@@@@@@'+Math.random()+'@@@@@@@@@@@';
$literals.add(id, match.replace(/\{\/?literal\}/g, ''));
return id;
}, this));
// remove comments
template = template.replace(/\{\*.*?\*\}/g, '');
var parseParameterList = function(parameterString) {
var $chars = parameterString.split('');
var $parameters = { };
var $inName = true;
var $name = '';
var $value = '';
var $doubleQuoted = false;
var $singleQuoted = false;
var $escaped = false;
for (var $i = 0, $max = $chars.length; $i < $max; $i++) {
var $char = $chars[$i];
if ($inName && $char != '=' && $char != ' ') $name += $char;
else if ($inName && $char == '=') {
$inName = false;
$singleQuoted = false;
$doubleQuoted = false;
$escaped = false;
}
else if (!$inName && !$singleQuoted && !$doubleQuoted && $char == ' ') {
$inName = true;
$parameters[$name] = $value;
$value = $name = '';
}
else if (!$inName && $singleQuoted && !$escaped && $char == "'") {
$singleQuoted = false;
$value += $char;
}
else if (!$inName && !$singleQuoted && !$doubleQuoted && $char == "'") {
$singleQuoted = true;
$value += $char;
}
else if (!$inName && $doubleQuoted && !$escaped && $char == '"') {
$doubleQuoted = false;
$value += $char;
}
else if (!$inName && !$singleQuoted && !$doubleQuoted && $char == '"') {
$doubleQuoted = true;
$value += $char;
}
else if (!$inName && ($doubleQuoted || $singleQuoted) && !$escaped && $char == '\\') {
$escaped = true;
$value += $char;
}
else if (!$inName) {
$escaped = false;
$value += $char;
}
}
$parameters[$name] = $value;
if ($doubleQuoted || $singleQuoted || $escaped) throw new Error('Syntax error in parameterList: "' + parameterString + '"');
return $parameters;
};
var unescape = function(string) {
return string.replace(/\\n/g, "\n").replace(/\\\\/g, '\\').replace(/\\'/g, "'");
};
template = template.replace(/\{(\$[^\}]+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "' + WCF.String.escapeHTML(" + content + ") + '";
})
// Numeric Variable
.replace(/\{#(\$[^\}]+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "' + WCF.String.formatNumeric(" + content + ") + '";
})
// Variable without escaping
.replace(/\{@(\$[^\}]+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "' + " + content + " + '";
})
// {lang}foo{/lang}
.replace(/\{lang\}(.+?)\{\/lang\}/g, function(_, content) {
return "' + WCF.Language.get('" + content + "', v) + '";
})
// {include}
.replace(/\{include (.+?)\}/g, function(_, content) {
content = content.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
var $parameters = parseParameterList(content);
if (typeof $parameters['file'] === 'undefined') throw new Error('Missing file attribute in include-tag');
$parameters['file'] = $parameters['file'].replace(/\$([^.\[\(\)\]\s]+)/g, "(v.$1)");
return "' + " + $parameters['file'] + ".fetch(v) + '";
})
// {if}
.replace(/\{if (.+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "';\n" +
"if (" + content + ") {\n" +
" $output += '";
})
// {elseif}
.replace(/\{else ?if (.+?)\}/g, function(_, content) {
content = unescape(content.replace(/\$([^.\[\(\)\]\s]+)/g, "(v['$1'])"));
return "';\n" +
"}\n" +
"else if (" + content + ") {\n" +
" $output += '";
})
// {implode}
.replace(/\{implode (.+?)\}/g, function(_, content) {
$tagID++;
content = content.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
var $parameters = parseParameterList(content);
if (typeof $parameters['from'] === 'undefined') throw new Error('Missing from attribute in implode-tag');
if (typeof $parameters['item'] === 'undefined') throw new Error('Missing item attribute in implode-tag');
if (typeof $parameters['glue'] === 'undefined') $parameters['glue'] = "', '";
$parameters['from'] = $parameters['from'].replace(/\$([^.\[\(\)\]\s]+)/g, "(v.$1)");
return "';\n"+
"var $implode_" + $tagID + " = false;\n" +
"for ($implodeKey_" + $tagID + " in " + $parameters['from'] + ") {\n" +
" v[" + $parameters['item'] + "] = " + $parameters['from'] + "[$implodeKey_" + $tagID + "];\n" +
(typeof $parameters['key'] !== 'undefined' ? " v[" + $parameters['key'] + "] = $implodeKey_" + $tagID + ";\n" : "") +
" if ($implode_" + $tagID + ") $output += " + $parameters['glue'] + ";\n" +
" $implode_" + $tagID + " = true;\n" +
" $output += '";
})
// {foreach}
.replace(/\{foreach (.+?)\}/g, function(_, content) {
$tagID++;
content = content.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
var $parameters = parseParameterList(content);
if (typeof $parameters['from'] === 'undefined') throw new Error('Missing from attribute in foreach-tag');
if (typeof $parameters['item'] === 'undefined') throw new Error('Missing item attribute in foreach-tag');
$parameters['from'] = $parameters['from'].replace(/\$([^.\[\(\)\]\s]+)/g, "(v.$1)");
return "';\n" +
"$foreach_"+$tagID+" = false;\n" +
"for ($foreachKey_" + $tagID + " in " + $parameters['from'] + ") {\n" +
" $foreach_"+$tagID+" = true;\n" +
" break;\n" +
"}\n" +
"if ($foreach_"+$tagID+") {\n" +
" for ($foreachKey_" + $tagID + " in " + $parameters['from'] + ") {\n" +
" v[" + $parameters['item'] + "] = " + $parameters['from'] + "[$foreachKey_" + $tagID + "];\n" +
(typeof $parameters['key'] !== 'undefined' ? " v[" + $parameters['key'] + "] = $foreachKey_" + $tagID + ";\n" : "") +
" $output += '";
})
// {foreachelse}
.replace(/\{foreachelse\}/g,
"';\n" +
" }\n" +
"}\n" +
"else {\n" +
" {\n" +
" $output += '"
)
// {/foreach}
.replace(/\{\/foreach\}/g,
"';\n" +
" }\n" +
"}\n" +
"$output += '"
)
// {else}
.replace(/\{else\}/g,
"';\n" +
"}\n" +
"else {\n" +
" $output += '"
)
// {/if} and {/implode}
.replace(/\{\/(if|implode)\}/g,
"';\n" +
"}\n" +
"$output += '"
);
// call callback
for (var key in WCF.Template.callbacks) {
template = WCF.Template.callbacks[key](template);
}
// insert delimiter tags
template = template.replace('{ldelim}', '{').replace('{rdelim}', '}');
$literals.each(function(pair) {
template = template.replace(pair.key, pair.value);
});
template = "$output += '" + template + "';";
try {
this.fetch = new Function("v", "v = window.$.extend({}, v, { __wcf: window.WCF, __window: window }); var $output = ''; " + template + ' return $output;');
}
catch (e) {
console.debug("var $output = ''; " + template + ' return $output;');
throw e;
}
},
/**
* Fetches the template with the given variables.
*
* @param v variables to insert
* @return parsed template
*/
fetch: function(v) {
// this will be replaced in the init function
}
});
/**
* Array of callbacks that will be called after parsing the included tags. Only applies to Templates compiled after the callback was added.
*
* @var array<Function>
*/
WCF.Template.callbacks = [ ];
/**
* Toggles options.
*
* @param string element
* @param array showItems
* @param array hideItems
* @param function callback
*/
WCF.ToggleOptions = Class.extend({
/**
* target item
*
* @var jQuery
*/
_element: null,
/**
* list of items to be shown
*
* @var array
*/
_showItems: [],
/**
* list of items to be hidden
*
* @var array
*/
_hideItems: [],
/**
* callback after options were toggled
*
* @var function
*/
_callback: null,
/**
* Initializes option toggle.
*
* @param string element
* @param array showItems
* @param array hideItems
* @param function callback
*/
init: function(element, showItems, hideItems, callback) {
this._element = $('#' + element);
this._showItems = showItems;
this._hideItems = hideItems;
if (callback !== undefined) {
this._callback = callback;
}
// bind event
this._element.click($.proxy(this._toggle, this));
// execute toggle on init
this._toggle();
},
/**
* Toggles items.
*/
_toggle: function() {
if (!this._element.prop('checked')) return;
for (var $i = 0, $length = this._showItems.length; $i < $length; $i++) {
var $item = this._showItems[$i];
$('#' + $item).show();
}
for (var $i = 0, $length = this._hideItems.length; $i < $length; $i++) {
var $item = this._hideItems[$i];
$('#' + $item).hide();
}
if (this._callback !== null) {
this._callback();
}
}
});
/**
* Namespace for all kind of collapsible containers.
*/
WCF.Collapsible = {};
/**
* Simple implementation for collapsible content, neither does it
* store its state nor does it allow AJAX callbacks to fetch content.
*/
WCF.Collapsible.Simple = {
/**
* Initializes collapsibles.
*/
init: function() {
$('.jsCollapsible').each($.proxy(function(index, button) {
this._initButton(button);
}, this));
},
/**
* Binds an event listener on all buttons triggering the collapsible.
*
* @param object button
*/
_initButton: function(button) {
var $button = $(button);
var $isOpen = $button.data('isOpen');
if (!$isOpen) {
// hide container on init
$('#' + $button.data('collapsibleContainer')).hide();
}
$button.click($.proxy(this._toggle, this));
},
/**
* Toggles collapsible containers on click.
*
* @param object event
*/
_toggle: function(event) {
var $button = $(event.currentTarget);
var $isOpen = $button.data('isOpen');
var $target = $('#' + $.wcfEscapeID($button.data('collapsibleContainer')));
if ($isOpen) {
$target.stop().wcfBlindOut('vertical', $.proxy(function() {
this._toggleImage($button);
}, this));
$isOpen = false;
}
else {
$target.stop().wcfBlindIn('vertical', $.proxy(function() {
this._toggleImage($button);
}, this));
$isOpen = true;
}
$button.data('isOpen', $isOpen);
// suppress event
event.stopPropagation();
return false;
},
/**
* Toggles image of target button.
*
* @param jQuery button
*/
_toggleImage: function(button) {
var $icon = button.find('span.icon');
if (button.data('isOpen')) {
$icon.removeClass('fa-chevron-right').addClass('fa-chevron-down');
}
else {
$icon.removeClass('fa-chevron-down').addClass('fa-chevron-right');
}
}
};
/**
* Basic implementation for collapsible containers with AJAX support. Results for open
* and closed state will be cached.
*
* @param string className
*/
WCF.Collapsible.Remote = Class.extend({
/**
* class name
* @var string
*/
_className: '',
/**
* list of active containers
* @var object
*/
_containers: {},
/**
* container meta data
* @var object
*/
_containerData: {},
/**
* action proxy
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* Initializes the controller for collapsible containers with AJAX support.
*
* @param string className
*/
init: function(className) {
this._className = className;
this._proxy = new WCF.Action.Proxy({
success: $.proxy(this._success, this)
});
// initialize each container
this._init();
WCF.DOMNodeInsertedHandler.addCallback('WCF.Collapsible.Remote', $.proxy(this._init, this));
},
/**
* Initializes a collapsible container.
*
* @param string containerID
*/
_init: function(containerID) {
this._getContainers().each($.proxy(function(index, container) {
var $container = $(container);
var $containerID = $container.wcfIdentify();
if (this._containers[$containerID] === undefined) {
this._containers[$containerID] = $container;
this._initContainer($containerID);
}
}, this));
},
/**
* Initializes a collapsible container.
*
* @param string containerID
*/
_initContainer: function(containerID) {
var $target = this._getTarget(containerID);
var $buttonContainer = this._getButtonContainer(containerID);
var $button = this._createButton(containerID, $buttonContainer);
// store container meta data
this._containerData[containerID] = {
button: $button,
buttonContainer: $buttonContainer,
isOpen: this._containers[containerID].data('isOpen'),
target: $target
};
// add 'jsCollapsed' CSS class
if (!this._containers[containerID].data('isOpen')) {
$('#' + containerID).addClass('jsCollapsed');
}
},
/**
* Returns a collection of collapsible containers.
*
* @return jQuery
*/
_getContainers: function() { },
/**
* Returns the target element for current collapsible container.
*
* @param integer containerID
* @return jQuery
*/
_getTarget: function(containerID) { },
/**
* Returns the button container for current collapsible container.
*
* @param integer containerID
* @return jQuery
*/
_getButtonContainer: function(containerID) { },
/**
* Creates the toggle button.
*
* @param integer containerID
* @param jQuery buttonContainer
*/
_createButton: function(containerID, buttonContainer) {
var $isOpen = this._containers[containerID].data('isOpen');
var $button = $('<span class="collapsibleButton jsTooltip pointer icon icon16 fa-chevron-down" title="'+WCF.Language.get('wcf.global.button.collapsible')+'">').prependTo(buttonContainer);
$button.data('containerID', containerID).click($.proxy(this._toggleContainer, this));
return $button;
},
/**
* Toggles a container.
*
* @param object event
*/
_toggleContainer: function(event) {
var $button = $(event.currentTarget);
var $containerID = $button.data('containerID');
var $isOpen = this._containerData[$containerID].isOpen;
var $state = ($isOpen) ? 'open' : 'close';
var $newState = ($isOpen) ? 'close' : 'open';
// fetch content state via AJAX
this._proxy.setOption('data', {
actionName: 'loadContainer',
className: this._className,
interfaceName: 'wcf\\data\\ILoadableContainerAction',
objectIDs: [ this._getObjectID($containerID) ],
parameters: $.extend(true, {
containerID: $containerID,
currentState: $state,
newState: $newState
}, this._getAdditionalParameters($containerID))
});
this._proxy.sendRequest();
// toogle 'jsCollapsed' CSS class
$('#' + $containerID).toggleClass('jsCollapsed');
// set spinner for current button
// this._exchangeIcon($button);
},
/**
* Exchanges button icon.
*
* @param jQuery button
* @param string newIcon
*/
_exchangeIcon: function(button, newIcon) {
newIcon = newIcon || 'spinner';
button.removeClass('fa-chevron-down fa-chevron-right fa-spinner').addClass('fa-' + newIcon);
},
/**
* Returns the object id for current container.
*
* @param integer containerID
* @return integer
*/
_getObjectID: function(containerID) {
return $('#' + containerID).data('objectID');
},
/**
* Returns additional parameters.
*
* @param integer containerID
* @return object
*/
_getAdditionalParameters: function(containerID) {
return {};
},
/**
* Updates container content.
*
* @param integer containerID
* @param string newContent
* @param string newState
*/
_updateContent: function(containerID, newContent, newState) {
this._containerData[containerID].target.html(newContent);
},
/**
* Sets content upon successfull AJAX request.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
// validate container id
if (!data.returnValues.containerID) return;
var $containerID = data.returnValues.containerID;
// check if container id is known
if (!this._containers[$containerID]) return;
// update content storage
this._containerData[$containerID].isOpen = (data.returnValues.isOpen) ? true : false;
var $newState = (data.returnValues.isOpen) ? 'open' : 'close';
// update container content
this._updateContent($containerID, $.trim(data.returnValues.content), $newState);
// update icon
this._exchangeIcon(this._containerData[$containerID].button, (data.returnValues.isOpen ? 'chevron-down' : 'chevron-right'));
}
});
/**
* Basic implementation for collapsible containers with AJAX support. Requires collapsible
* content to be available in DOM already, if you want to load content on the fly use
* WCF.Collapsible.Remote instead.
*/
WCF.Collapsible.SimpleRemote = WCF.Collapsible.Remote.extend({
/**
* Initializes an AJAX-based collapsible handler.
*
* @param string className
*/
init: function(className) {
this._super(className);
// override settings for action proxy
this._proxy = new WCF.Action.Proxy({
showLoadingOverlay: false
});
},
/**
* @see WCF.Collapsible.Remote._initContainer()
*/
_initContainer: function(containerID) {
this._super(containerID);
// hide container on init if applicable
if (!this._containerData[containerID].isOpen) {
this._containerData[containerID].target.hide();
this._exchangeIcon(this._containerData[containerID].button, 'chevron-right');
}
},
/**
* Toggles container visibility.
*
* @param object event
*/
_toggleContainer: function(event) {
var $button = $(event.currentTarget);
var $containerID = $button.data('containerID');
var $isOpen = this._containerData[$containerID].isOpen;
var $currentState = ($isOpen) ? 'open' : 'close';
var $newState = ($isOpen) ? 'close' : 'open';
this._proxy.setOption('data', {
actionName: 'toggleContainer',
className: this._className,
interfaceName: 'wcf\\data\\IToggleContainerAction',
objectIDs: [ this._getObjectID($containerID) ],
parameters: $.extend(true, {
containerID: $containerID,
currentState: $currentState,
newState: $newState
}, this._getAdditionalParameters($containerID))
});
this._proxy.sendRequest();
// exchange icon
this._exchangeIcon(this._containerData[$containerID].button, ($newState === 'open' ? 'chevron-down' : 'chevron-right'));
// toggle container
if ($newState === 'open') {
this._containerData[$containerID].target.show();
}
else {
this._containerData[$containerID].target.hide();
}
// toogle 'jsCollapsed' CSS class
$('#' + $containerID).toggleClass('jsCollapsed');
// update container data
this._containerData[$containerID].isOpen = ($newState === 'open' ? true : false);
}
});
/**
* Holds userdata of the current user
*
* @deprecated use WCF/WoltLab/User
*/
WCF.User = {
/**
* id of the active user
* @var integer
*/
userID: 0,
/**
* name of the active user
* @var string
*/
username: '',
/**
* Initializes userdata
*
* @param integer userID
* @param string username
*/
init: function(userID, username) {
this.userID = userID;
this.username = username;
}
};
/**
* Namespace for effect-related functions.
*/
WCF.Effect = {};
/**
* Scrolls to a specific element offset, optionally handling menu height.
*/
WCF.Effect.Scroll = Class.extend({
/**
* Scrolls to a specific element offset.
*
* @param jQuery element
* @param boolean excludeMenuHeight
* @param boolean disableAnimation
* @return boolean
*/
scrollTo: function(element, excludeMenuHeight, disableAnimation) {
if (!element.length) {
return true;
}
var $elementOffset = element.getOffsets('offset').top;
var $documentHeight = $(document).height();
var $windowHeight = $(window).height();
if ($elementOffset > $documentHeight - $windowHeight) {
$elementOffset = $documentHeight - $windowHeight;
if ($elementOffset < 0) {
$elementOffset = 0;
}
}
if (disableAnimation === true) {
$('html,body').scrollTop($elementOffset);
}
else {
$('html,body').animate({ scrollTop: $elementOffset }, 400, function (x, t, b, c, d) {
return -c * ( ( t = t / d - 1 ) * t * t * t - 1) + b;
});
}
return false;
}
});
/**
* Handles clicks outside an overlay, hitting body-tag through bubbling.
*
* You should always remove callbacks before disposing the attached element,
* preventing errors from blocking the iteration. Furthermore you should
* always handle clicks on your overlay's container and return 'false' to
* prevent bubbling.
*
* @deprecated 3.0 - please use `Ui/CloseOverlay` instead
*/
WCF.CloseOverlayHandler = {
/**
* Adds a new callback.
*
* @param string identifier
* @param object callback
*/
addCallback: function(identifier, callback) {
require(['Ui/CloseOverlay'], function(UiCloseOverlay) {
UiCloseOverlay.add(identifier, callback);
});
},
/**
* Removes a callback from list.
*
* @param string identifier
*/
removeCallback: function(identifier) {
require(['Ui/CloseOverlay'], function(UiCloseOverlay) {
UiCloseOverlay.remove(identifier);
});
},
/**
* Triggers the callbacks programmatically.
*/
forceExecution: function() {
require(['Ui/CloseOverlay'], function(UiCloseOverlay) {
UiCloseOverlay.execute();
});
}
};
/**
* @deprecated Use WoltLabSuite/Core/Dom/Change/Listener
*/
WCF.DOMNodeInsertedHandler = {
addCallback: function(identifier, callback) {
require(['WoltLabSuite/Core/Dom/Change/Listener'], function (ChangeListener) {
ChangeListener.add('__legacy__', callback);
});
},
_executeCallbacks: function() {
require(['WoltLabSuite/Core/Dom/Change/Listener'], function (ChangeListener) {
ChangeListener.trigger();
});
},
execute: function() {
this._executeCallbacks();
}
};
/**
* Notifies objects once a DOM node was removed.
*/
WCF.DOMNodeRemovedHandler = {
/**
* list of callbacks
* @var WCF.Dictionary
*/
_callbacks: new WCF.Dictionary(),
/**
* prevent infinite loop if a callback manipulates DOM
* @var boolean
*/
_isExecuting: false,
/**
* indicates that overlay handler is listening to DOMNodeRemoved events on body-tag
* @var boolean
*/
_isListening: false,
/**
* Adds a new callback.
*
* @param string identifier
* @param object callback
*/
addCallback: function(identifier, callback) {
this._bindListener();
if (this._callbacks.isset(identifier)) {
console.debug("[WCF.DOMNodeRemovedHandler] identifier '" + identifier + "' is already bound to a callback");
return false;
}
this._callbacks.add(identifier, callback);
},
/**
* Removes a callback from list.
*
* @param string identifier
*/
removeCallback: function(identifier) {
if (this._callbacks.isset(identifier)) {
this._callbacks.remove(identifier);
}
},
/**
* Binds click event handler.
*/
_bindListener: function() {
if (this._isListening) return;
if (window.MutationObserver) {
var $mutationObserver = new MutationObserver((function(mutations) {
var $triggerEvent = false;
mutations.forEach((function(mutation) {
if (mutation.removedNodes.length) {
$triggerEvent = true;
}
}).bind(this));
if ($triggerEvent) {
this._executeCallbacks({ });
}
}).bind(this));
$mutationObserver.observe(document.body, {
childList: true,
subtree: true
});
}
else {
$(document).bind('DOMNodeRemoved', $.proxy(this._executeCallbacks, this));
}
this._isListening = true;
},
/**
* Executes callbacks if a DOM node is removed.
*/
_executeCallbacks: function(event) {
if (this._isExecuting) return;
// do not track events while executing callbacks
this._isExecuting = true;
this._callbacks.each(function(pair) {
// execute callback
pair.value(event);
});
// enable listener again
this._isExecuting = false;
}
};
/**
* Namespace for option handlers.
*/
WCF.Option = { };
/**
* Handles option selection.
*/
WCF.Option.Handler = Class.extend({
/**
* Initializes the WCF.Option.Handler class.
*/
init: function() {
this._initOptions();
WCF.DOMNodeInsertedHandler.addCallback('WCF.Option.Handler', $.proxy(this._initOptions, this));
},
/**
* Initializes all options.
*/
_initOptions: function() {
$('.jsEnablesOptions').each($.proxy(this._initOption, this));
},
/**
* Initializes an option.
*
* @param integer index
* @param object option
*/
_initOption: function(index, option) {
// execute action on init
this._change(option);
// bind event listener
$(option).change($.proxy(this._handleChange, this));
},
/**
* Applies whenever an option is changed.
*
* @param object event
*/
_handleChange: function(event) {
this._change($(event.target));
},
/**
* Enables or disables options on option value change.
*
* @param object option
*/
_change: function(option) {
option = $(option);
var $disableOptions = eval(option.data('disableOptions'));
var $enableOptions = eval(option.data('enableOptions'));
// determine action by type
switch(option.getTagName()) {
case 'input':
switch(option.attr('type')) {
case 'checkbox':
this._execute(option.prop('checked'), $disableOptions, $enableOptions);
break;
case 'radio':
if (option.prop('checked')) {
var isActive = true;
if (option.data('isBoolean') && option.val() != 1) {
isActive = false;
}
this._execute(isActive, $disableOptions, $enableOptions);
}
break;
}
break;
case 'select':
var $value = option.val();
var $disableOptions = $enableOptions = [];
if (option.data('disableOptions').length > 0) {
for (var $index in option.data('disableOptions')) {
var $item = option.data('disableOptions')[$index];
if ($item.value == $value) {
$disableOptions.push($item.option);
}
}
}
if (option.data('enableOptions').length > 0) {
for (var $index in option.data('enableOptions')) {
var $item = option.data('enableOptions')[$index];
if ($item.value == $value) {
$enableOptions.push($item.option);
}
}
}
this._execute(true, $disableOptions, $enableOptions);
break;
}
},
/**
* Enables or disables options.
*
* @param boolean isActive
* @param array disableOptions
* @param array enableOptions
*/
_execute: function(isActive, disableOptions, enableOptions) {
if (disableOptions.length > 0) {
for (var $i = 0, $size = disableOptions.length; $i < $size; $i++) {
var $target = disableOptions[$i];
if ($.wcfIsset($target)) {
this._enableOption($target, !isActive);
}
else {
var $dl = $('.' + $target + 'Input');
if ($dl.length) {
this._enableOptions($dl.children('dd').find('input, select, textarea'), !isActive);
}
}
}
}
if (enableOptions.length > 0) {
for (var $i = 0, $size = enableOptions.length; $i < $size; $i++) {
var $target = enableOptions[$i];
if ($.wcfIsset($target)) {
this._enableOption($target, isActive);
}
else {
var $dl = $('.' + $target + 'Input');
if ($dl.length) {
this._enableOptions($dl.children('dd').find('input, select, textarea'), isActive);
}
}
}
}
},
/**
* Enables/Disables an option.
*
* @param string target
* @param boolean enable
*/
_enableOption: function(target, enable) {
this._enableOptionElement($('#' + $.wcfEscapeID(target)), enable);
},
/**
* Enables/Disables an option element.
*
* @param string target
* @param boolean enable
*/
_enableOptionElement: function(element, enable) {
element = $(element);
var $tagName = element.getTagName();
if ($tagName == 'select' || ($tagName == 'input' && (element.attr('type') == 'checkbox' || element.attr('type') == 'file' || element.attr('type') == 'radio'))) {
if (enable) element.enable();
else element.disable();
}
else {
if (enable) element.removeAttr('readonly');
else element.attr('readonly', true);
}
if (enable) {
element.closest('dl').removeClass('disabled');
}
else {
element.closest('dl').addClass('disabled');
}
},
/**
* Enables/Disables an option consisting of multiple form elements.
*
* @param string target
* @param boolean enable
*/
_enableOptions: function(targets, enable) {
for (var $i = 0, $length = targets.length; $i < $length; $i++) {
this._enableOptionElement(targets[$i], enable);
}
}
});
WCF.PageVisibilityHandler = {
/**
* list of callbacks
* @var WCF.Dictionary
*/
_callbacks: new WCF.Dictionary(),
/**
* indicates that event listeners are bound
* @var boolean
*/
_isListening: false,
/**
* name of window's hidden property
* @var string
*/
_hiddenFieldName: '',
/**
* Adds a new callback.
*
* @param string identifier
* @param object callback
*/
addCallback: function(identifier, callback) {
this._bindListener();
if (this._callbacks.isset(identifier)) {
console.debug("[WCF.PageVisibilityHandler] identifier '" + identifier + "' is already bound to a callback");
return false;
}
this._callbacks.add(identifier, callback);
},
/**
* Removes a callback from list.
*
* @param string identifier
*/
removeCallback: function(identifier) {
if (this._callbacks.isset(identifier)) {
this._callbacks.remove(identifier);
}
},
/**
* Binds click event handler.
*/
_bindListener: function() {
if (this._isListening) return;
var $eventName = null;
if (typeof document.hidden !== "undefined") {
this._hiddenFieldName = "hidden";
$eventName = "visibilitychange";
}
else if (typeof document.mozHidden !== "undefined") {
this._hiddenFieldName = "mozHidden";
$eventName = "mozvisibilitychange";
}
else if (typeof document.msHidden !== "undefined") {
this._hiddenFieldName = "msHidden";
$eventName = "msvisibilitychange";
}
else if (typeof document.webkitHidden !== "undefined") {
this._hiddenFieldName = "webkitHidden";
$eventName = "webkitvisibilitychange";
}
if ($eventName === null) {
console.debug("[WCF.PageVisibilityHandler] This browser does not support the page visibility API.");
}
else {
$(document).on($eventName, $.proxy(this._executeCallbacks, this));
}
this._isListening = true;
},
/**
* Executes callbacks if page is hidden/visible again.
*/
_executeCallbacks: function(event) {
if (this._isExecuting) return;
// do not track events while executing callbacks
this._isExecuting = true;
var $state = document[this._hiddenFieldName];
this._callbacks.each(function(pair) {
// execute callback
pair.value($state);
});
// enable listener again
this._isExecuting = false;
}
};
/**
* Namespace for table related classes.
*/
WCF.Table = { };
/**
* Handles empty tables which can be used in combination with WCF.Action.Proxy.
*/
WCF.Table.EmptyTableHandler = Class.extend({
/**
* handler options
* @var object
*/
_options: {},
/**
* class name of the relevant rows
* @var string
*/
_rowClassName: '',
/**
* Initalizes a new WCF.Table.EmptyTableHandler object.
*
* @param jQuery tableContainer
* @param string rowClassName
* @param object options
*/
init: function(tableContainer, rowClassName, options) {
this._rowClassName = rowClassName;
this._tableContainer = tableContainer;
this._options = $.extend(true, {
emptyMessage: null,
messageType: 'info',
refreshPage: false,
updatePageNumber: false
}, options || { });
WCF.DOMNodeRemovedHandler.addCallback('WCF.Table.EmptyTableHandler.' + rowClassName, $.proxy(this._remove, this));
},
/**
* Returns the current number of table rows.
*
* @return integer
*/
_getRowCount: function() {
return this._tableContainer.find('table tr.' + this._rowClassName).length;
},
/**
* Handles an empty table.
*/
_handleEmptyTable: function() {
if (this._options.emptyMessage) {
// insert message
this._tableContainer.replaceWith($('<p />').addClass(this._options.messageType).text(this._options.emptyMessage));
}
else if (this._options.refreshPage) {
// refresh page
if (this._options.updatePageNumber) {
// calculate the new page number
var pageNumberURLComponents = window.location.href.match(/(\?|&)pageNo=(\d+)/g);
if (pageNumberURLComponents) {
var currentPageNumber = pageNumberURLComponents[pageNumberURLComponents.length - 1].match(/\d+/g);
if (this._options.updatePageNumber > 0) {
currentPageNumber++;
}
else {
currentPageNumber--;
}
window.location = window.location.href.replace(pageNumberURLComponents[pageNumberURLComponents.length - 1], pageNumberURLComponents[pageNumberURLComponents.length - 1][0] + 'pageNo=' + currentPageNumber);
}
}
else {
window.location.reload();
}
}
else {
// simply remove the table container
this._tableContainer.remove();
}
},
/**
* Handles the removal of a DOM node.
*/
_remove: function(event) {
if ($.getLength(event)) {
var element = $(event.target);
// check if DOM element is relevant
if (element.hasClass(this._rowClassName)) {
var tbody = element.parents('tbody:eq(0)');
// check if table will be empty if DOM node is removed
if (tbody.children('tr').length == 1) {
this._handleEmptyTable();
}
}
}
else if (!this._getRowCount()) {
this._handleEmptyTable();
}
}
});
/**
* Namespace for search related classes.
*/
WCF.Search = {};
/**
* Performs a quick search.
*
* @deprecated 3.0 - please use `WoltLabSuite/Core/Ui/Search/Input` instead
*/
WCF.Search.Base = Class.extend({
/**
* notification callback
* @var object
*/
_callback: null,
/**
* represents index of search string (relative to original caret position)
* @var integer
*/
_caretAt: -1,
/**
* class name
* @var string
*/
_className: '',
/**
* comma seperated list
* @var boolean
*/
_commaSeperated: false,
/**
* delay in miliseconds before a request is send to the server
* @var integer
*/
_delay: 0,
/**
* list with values that are excluded from seaching
* @var array
*/
_excludedSearchValues: [],
/**
* count of available results
* @var integer
*/
_itemCount: 0,
/**
* item index, -1 if none is selected
* @var integer
*/
_itemIndex: -1,
/**
* result list
* @var jQuery
*/
_list: null,
/**
* old search string, used for comparison
* @var array<string>
*/
_oldSearchString: [ ],
/**
* action proxy
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* search input field
* @var jQuery
*/
_searchInput: null,
/**
* minimum search input length, MUST be 1 or higher
* @var integer
*/
_triggerLength: 3,
/**
* delay timer
* @var WCF.PeriodicalExecuter
*/
_timer: null,
/**
* Initializes a new search.
*
* @param jQuery searchInput
* @param object callback
* @param array excludedSearchValues
* @param boolean commaSeperated
* @param boolean showLoadingOverlay
*/
init: function(searchInput, callback, excludedSearchValues, commaSeperated, showLoadingOverlay) {
if (callback !== null && callback !== undefined && !$.isFunction(callback)) {
console.debug("[WCF.Search.Base] The given callback is invalid, aborting.");
return;
}
this._callback = (callback) ? callback : null;
this._caretAt = -1;
this._delay = 0;
this._excludedSearchValues = [];
if (excludedSearchValues) {
this._excludedSearchValues = excludedSearchValues;
}
this._searchInput = $(searchInput);
if (!this._searchInput.length) {
console.debug("[WCF.Search.Base] Selector '" + searchInput + "' for search input is invalid, aborting.");
return;
}
this._searchInput.keydown($.proxy(this._keyDown, this)).keyup($.proxy(this._keyUp, this)).wrap('<span class="dropdown" />');
if ($.browser.mozilla && $.browser.touch) {
this._searchInput.on('input', $.proxy(this._keyUp, this));
}
this._list = $('<ul class="dropdownMenu" />').insertAfter(this._searchInput);
this._commaSeperated = (commaSeperated) ? true : false;
this._oldSearchString = [ ];
this._itemCount = 0;
this._itemIndex = -1;
this._proxy = new WCF.Action.Proxy({
showLoadingOverlay: (showLoadingOverlay !== true ? false : true),
success: $.proxy(this._success, this),
autoAbortPrevious: true
});
if (this._searchInput.is('input')) {
this._searchInput.attr('autocomplete', 'off');
}
this._searchInput.blur($.proxy(this._blur, this));
WCF.Dropdown.initDropdownFragment(this._searchInput.parent(), this._list);
},
/**
* Closes the dropdown after a short delay.
*/
_blur: function() {
var self = this;
new WCF.PeriodicalExecuter(function(pe) {
if (self._list.is(':visible')) {
self._clearList(false);
}
pe.stop();
}, 250);
},
/**
* Blocks execution of 'Enter' event.
*
* @param object event
*/
_keyDown: function(event) {
if (event.which === $.ui.keyCode.ENTER) {
var $dropdown = this._searchInput.parents('.dropdown');
if ($dropdown.data('disableAutoFocus')) {
if (this._itemIndex !== -1) {
event.preventDefault();
}
}
else if ($dropdown.data('preventSubmit') || this._itemIndex !== -1) {
event.preventDefault();
}
}
},
/**
* Performs a search upon key up.
*
* @param object event
*/
_keyUp: function(event) {
// handle arrow keys and return key
switch (event.which) {
case 37: // arrow-left
case 39: // arrow-right
return;
break;
case 38: // arrow up
this._selectPreviousItem();
return;
break;
case 40: // arrow down
this._selectNextItem();
return;
break;
case 13: // return key
return this._selectElement(event);
break;
}
var $content = this._getSearchString(event);
if ($content === '') {
this._clearList(false);
}
else if ($content.length >= this._triggerLength) {
var $parameters = {
data: {
excludedSearchValues: this._excludedSearchValues,
searchString: $content
}
};
if (this._delay) {
if (this._timer !== null) {
this._timer.stop();
}
var self = this;
this._timer = new WCF.PeriodicalExecuter(function() {
self._queryServer($parameters);
self._timer.stop();
self._timer = null;
}, this._delay);
}
else {
this._queryServer($parameters);
}
}
else {
// input below trigger length
this._clearList(false);
}
},
/**
* Queries the server.
*
* @param object parameters
*/
_queryServer: function(parameters) {
this._searchInput.parents('.searchBar').addClass('loading');
this._proxy.setOption('data', {
actionName: 'getSearchResultList',
className: this._className,
interfaceName: 'wcf\\data\\ISearchAction',
parameters: this._getParameters(parameters)
});
this._proxy.sendRequest();
},
/**
* Sets query delay in miliseconds.
*
* @param integer delay
*/
setDelay: function(delay) {
this._delay = delay;
},
/**
* Selects the next item in list.
*/
_selectNextItem: function() {
if (this._itemCount === 0) {
return;
}
// remove previous marking
this._itemIndex++;
if (this._itemIndex === this._itemCount) {
this._itemIndex = 0;
}
this._highlightSelectedElement();
},
/**
* Selects the previous item in list.
*/
_selectPreviousItem: function() {
if (this._itemCount === 0) {
return;
}
this._itemIndex--;
if (this._itemIndex === -1) {
this._itemIndex = this._itemCount - 1;
}
this._highlightSelectedElement();
},
/**
* Highlights the active item.
*/
_highlightSelectedElement: function() {
this._list.find('li').removeClass('dropdownNavigationItem');
this._list.find('li:eq(' + this._itemIndex + ')').addClass('dropdownNavigationItem');
},
/**
* Selects the active item by pressing the return key.
*
* @param object event
* @return boolean
*/
_selectElement: function(event) {
if (this._itemCount === 0) {
return true;
}
this._list.find('li.dropdownNavigationItem').trigger('click');
return false;
},
/**
* Returns search string.
*
* @return string
*/
_getSearchString: function(event) {
var $searchString = $.trim(this._searchInput.val());
if (this._commaSeperated) {
var $keyCode = event.keyCode || event.which;
if ($keyCode == $.ui.keyCode.COMMA) {
// ignore event if char is ','
return '';
}
var $current = $searchString.split(',');
var $length = $current.length;
for (var $i = 0; $i < $length; $i++) {
// remove whitespaces at the beginning or end
$current[$i] = $.trim($current[$i]);
}
for (var $i = 0; $i < $length; $i++) {
var $part = $current[$i];
if (this._oldSearchString[$i]) {
// compare part
if ($part != this._oldSearchString[$i]) {
// current part was changed
$searchString = $part;
this._caretAt = $i;
break;
}
}
else {
// new part was added
$searchString = $part;
break;
}
}
this._oldSearchString = $current;
}
return $searchString;
},
/**
* Returns parameters for quick search.
*
* @param object parameters
* @return object
*/
_getParameters: function(parameters) {
return parameters;
},
/**
* Evalutes search results.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
this._clearList(false);
this._searchInput.parents('.searchBar').removeClass('loading');
if ($.getLength(data.returnValues)) {
for (var $i in data.returnValues) {
var $item = data.returnValues[$i];
this._createListItem($item);
}
}
else if (!this._handleEmptyResult()) {
return;
}
WCF.CloseOverlayHandler.addCallback('WCF.Search.Base', $.proxy(function() { this._clearList(); }, this));
var $containerID = this._searchInput.parents('.dropdown').wcfIdentify();
if (!WCF.Dropdown.getDropdownMenu($containerID).hasClass('dropdownOpen')) {
WCF.Dropdown.toggleDropdown($containerID);
}
// pre-select first item
this._itemIndex = -1;
if (!WCF.Dropdown.getDropdown($containerID).data('disableAutoFocus')) {
this._selectNextItem();
}
},
/**
* Handles empty result lists, should return false if dropdown should be hidden.
*
* @return boolean
*/
_handleEmptyResult: function() {
return false;
},
/**
* Creates a new list item.
*
* @param object item
* @return jQuery
*/
_createListItem: function(item) {
var $listItem = $('<li><span>' + WCF.String.escapeHTML(item.label) + '</span></li>').appendTo(this._list);
$listItem.data('objectID', item.objectID).data('label', item.label).click($.proxy(this._executeCallback, this));
this._itemCount++;
return $listItem;
},
/**
* Executes callback upon result click.
*
* @param object event
*/
_executeCallback: function(event) {
var $clearSearchInput = false;
var $listItem = $(event.currentTarget);
// notify callback
if (this._commaSeperated) {
// auto-complete current part
var $result = $listItem.data('label');
this._oldSearchString[this._caretAt] = $result;
this._searchInput.val(this._oldSearchString.join(', '));
if ($.browser.webkit) {
// chrome won't display the new value until the textarea is rendered again
// this quick fix forces chrome to render it again, even though it changes nothing
this._searchInput.css({ display: 'block' });
}
// set focus on input field again
var $position = this._searchInput.val().toLowerCase().indexOf($result.toLowerCase()) + $result.length;
this._searchInput.focus().setCaret($position);
}
else {
if (this._callback === null) {
this._searchInput.val($listItem.data('label'));
}
else {
$clearSearchInput = (this._callback($listItem.data()) === true) ? true : false;
}
}
// close list and revert input
this._clearList($clearSearchInput);
},
/**
* Closes the suggestion list and clears search input on demand.
*
* @param boolean clearSearchInput
*/
_clearList: function(clearSearchInput) {
if (clearSearchInput && !this._commaSeperated) {
this._searchInput.val('');
}
// close dropdown
WCF.Dropdown.getDropdown(this._searchInput.parents('.dropdown').wcfIdentify()).removeClass('dropdownOpen');
WCF.Dropdown.getDropdownMenu(this._searchInput.parents('.dropdown').wcfIdentify()).removeClass('dropdownOpen');
this._list.end().empty();
WCF.CloseOverlayHandler.removeCallback('WCF.Search.Base');
// reset item navigation
this._itemCount = 0;
this._itemIndex = -1;
},
/**
* Adds an excluded search value.
*
* @param string value
*/
addExcludedSearchValue: function(value) {
if (!WCF.inArray(value, this._excludedSearchValues)) {
this._excludedSearchValues.push(value);
}
},
/**
* Removes an excluded search value.
*
* @param string value
*/
removeExcludedSearchValue: function(value) {
var index = $.inArray(value, this._excludedSearchValues);
if (index != -1) {
this._excludedSearchValues.splice(index, 1);
}
}
});
/**
* Provides quick search for users and user groups.
*
* @see WCF.Search.Base
* @deprecated 3.0 - please use `WoltLabSuite/Core/Ui/User/Search/Input` instead
*/
WCF.Search.User = WCF.Search.Base.extend({
/**
* @see WCF.Search.Base._className
*/
_className: 'wcf\\data\\user\\UserAction',
/**
* include user groups in search
* @var boolean
*/
_includeUserGroups: false,
/**
* @see WCF.Search.Base.init()
*/
init: function(searchInput, callback, includeUserGroups, excludedSearchValues, commaSeperated) {
this._includeUserGroups = includeUserGroups;
this._super(searchInput, callback, excludedSearchValues, commaSeperated);
},
/**
* @see WCF.Search.Base._getParameters()
*/
_getParameters: function(parameters) {
parameters.data.includeUserGroups = this._includeUserGroups ? 1 : 0;
return parameters;
},
/**
* @see WCF.Search.Base._createListItem()
*/
_createListItem: function(item) {
var $listItem = this._super(item);
var $icon = null;
if (item.icon) {
$icon = $(item.icon);
}
else if (this._includeUserGroups && item.type === 'group') {
$icon = $('<span class="icon icon16 fa-users" />');
}
if ($icon) {
var $label = $listItem.find('span').detach();
var $box16 = $('<div />').addClass('box16').appendTo($listItem);
$box16.append($icon);
$box16.append($('<div />').append($label));
}
// insert item type
$listItem.data('type', item.type);
return $listItem;
}
});
/**
* Namespace for system-related classes.
*/
WCF.System = { };
/**
* Namespace for dependency-related classes.
*/
WCF.System.Dependency = { };
/**
* JavaScript Dependency Manager.
*/
WCF.System.Dependency.Manager = {
/**
* list of callbacks grouped by identifier
* @var object
*/
_callbacks: { },
/**
* list of loaded identifiers
* @var array<string>
*/
_loaded: [ ],
/**
* list of setup callbacks grouped by identifier
* @var object
*/
_setupCallbacks: { },
/**
* Registers a callback for given identifier, will be executed after all setup
* callbacks have been invoked.
*
* @param string identifier
* @param object callback
*/
register: function(identifier, callback) {
if (!$.isFunction(callback)) {
console.debug("[WCF.System.Dependency.Manager] Callback for identifier '" + identifier + "' is invalid, aborting.");
return;
}
// already loaded, invoke now
if (WCF.inArray(identifier, this._loaded)) {
setTimeout(function() {
callback();
}, 1);
}
else {
if (!this._callbacks[identifier]) {
this._callbacks[identifier] = [ ];
}
this._callbacks[identifier].push(callback);
}
},
/**
* Registers a setup callback for given identifier, will be invoked
* prior to all other callbacks.
*
* @param string identifier
* @param object callback
*/
setup: function(identifier, callback) {
if (!$.isFunction(callback)) {
console.debug("[WCF.System.Dependency.Manager] Setup callback for identifier '" + identifier + "' is invalid, aborting.");
return;
}
if (!this._setupCallbacks[identifier]) {
this._setupCallbacks[identifier] = [ ];
}
this._setupCallbacks[identifier].push(callback);
},
/**
* Invokes all callbacks for given identifier and marks it as loaded.
*
* @param string identifier
*/
invoke: function(identifier) {
if (this._setupCallbacks[identifier]) {
for (var $i = 0, $length = this._setupCallbacks[identifier].length; $i < $length; $i++) {
this._setupCallbacks[identifier][$i]();
}
delete this._setupCallbacks[identifier];
}
this._loaded.push(identifier);
if (this._callbacks[identifier]) {
for (var $i = 0, $length = this._callbacks[identifier].length; $i < $length; $i++) {
this._callbacks[identifier][$i]();
}
delete this._callbacks[identifier];
}
},
reset: function(identifier) {
var index = this._loaded.indexOf(identifier);
if (index !== -1) {
this._loaded.splice(index, 1);
}
}
};
/**
* Provides flexible dropdowns for tab-based menus.
*/
WCF.System.FlexibleMenu = {
/**
* Initializes the WCF.System.FlexibleMenu class.
*/
init: function() { /* does nothing */ },
/**
* Registers a tab-based menu by id.
*
* Required DOM:
* <container>
* <ul style="white-space: nowrap">
* <li>tab 1</li>
* <li>tab 2</li>
* ...
* <li>tab n</li>
* </ul>
* </container>
*
* @param string containerID
*/
registerMenu: function(containerID) {
require(['WoltLabSuite/Core/Ui/FlexibleMenu'], function(UiFlexibleMenu) {
UiFlexibleMenu.register(containerID);
});
},
/**
* Rebuilds a container, will be automatically invoked on window resize and registering.
*
* @param string containerID
*/
rebuild: function(containerID) {
require(['WoltLabSuite/Core/Ui/FlexibleMenu'], function(UiFlexibleMenu) {
UiFlexibleMenu.rebuild(containerID);
});
}
};
/**
* Namespace for mobile device-related classes.
*/
WCF.System.Mobile = { };
/**
* Stores object references for global access.
*/
WCF.System.ObjectStore = {
/**
* list of objects grouped by identifier
* @var object<array>
*/
_objects: { },
/**
* Adds a new object to the collection.
*
* @param string identifier
* @param object object
*/
add: function(identifier, obj) {
if (this._objects[identifier] === undefined) {
this._objects[identifier] = [ ];
}
this._objects[identifier].push(obj);
},
/**
* Invokes a callback passing the matching objects as a parameter.
*
* @param string identifier
* @param object callback
*/
invoke: function(identifier, callback) {
if (this._objects[identifier]) {
for (var $i = 0; $i < this._objects[identifier].length; $i++) {
callback(this._objects[identifier][$i]);
}
}
}
};
/**
* Stores captcha callbacks used for captchas in AJAX contexts.
*/
WCF.System.Captcha = {
/**
* Adds a callback for a certain captcha.
*
* @param string captchaID
* @param function callback
*/
addCallback: function(captchaID, callback) {
require(['WoltLabSuite/Core/Controller/Captcha'], function(ControllerCaptcha) {
try {
ControllerCaptcha.add(captchaID, callback);
}
catch (e) {
if (e instanceof TypeError) {
console.debug('[WCF.System.Captcha] Given callback is no function');
return;
}
// ignore other errors
}
});
},
/**
* Returns the captcha data for the captcha with the given id.
*
* @return object
*/
getData: function(captchaID) {
var returnValue;
require(['WoltLabSuite/Core/Controller/Captcha'], function(ControllerCaptcha) {
try {
returnValue = ControllerCaptcha.getData(captchaID);
}
catch (e) {
console.debug('[WCF.System.Captcha] Unknow captcha id "' + captchaID + '"');
}
});
return returnValue;
},
/**
* Removes the callback with the given captcha id.
*/
removeCallback: function(captchaID) {
require(['WoltLabSuite/Core/Controller/Captcha'], function(ControllerCaptcha) {
try {
ControllerCaptcha.delete(captchaID);
}
catch (e) {
// ignore errors for unknown captchas
}
});
}
};
WCF.System.Page = { };
/**
* System notification overlays.
*
* @deprecated 3.0 - please use `Ui/Notification` instead
*
* @param string message
* @param string cssClassNames
*/
WCF.System.Notification = Class.extend({
_cssClassNames: '',
_message: '',
/**
* Creates a new system notification overlay.
*
* @param string message
* @param string cssClassNames
*/
init: function(message, cssClassNames) {
this._cssClassNames = cssClassNames || '';
this._message = message || '';
},
/**
* Shows the notification overlay.
*
* @param object callback
* @param integer duration
* @param string message
* @param string cssClassName
*/
show: function(callback, duration, message, cssClassNames) {
require(['Ui/Notification'], (function(UiNotification) {
UiNotification.show(
message || this._message,
callback,
cssClassNames || this._cssClassNames
);
}).bind(this));
}
});
/**
* Provides dialog-based confirmations.
*
* @deprecated 3.0 - please use `Ui/Confirmation` instead
*/
WCF.System.Confirmation = {
/**
* Displays a confirmation dialog.
*
* @param string message
* @param object callback
* @param object parameters
* @param jQuery template
* @param boolean messageIsHtml
*/
show: function(message, callback, parameters, template, messageIsHtml) {
if (typeof template === 'object') {
var $wrapper = $('<div />');
$wrapper.append(template);
template = $wrapper.html();
}
require(['Ui/Confirmation'], function(UiConfirmation) {
UiConfirmation.show({
legacyCallback: callback,
message: message,
parameters: parameters,
template: (template || ''),
messageIsHtml: (messageIsHtml === true)
});
});
}
};
/**
* Disables the ability to scroll the page.
*/
WCF.System.DisableScrolling = {
/**
* number of times scrolling was disabled (nested calls)
* @var integer
*/
_depth: 0,
/**
* old overflow-value of the body element
* @var string
*/
_oldOverflow: null,
/**
* Disables scrolling.
*/
disable: function () {
// do not block scrolling on touch devices
if ($.browser.touch) {
return;
}
if (this._depth === 0) {
this._oldOverflow = $(document.body).css('overflow');
$(document.body).css('overflow', 'hidden');
}
this._depth++;
},
/**
* Enables scrolling again.
* Must be called the same number of times disable() was called to enable scrolling.
*/
enable: function () {
if (this._depth === 0) return;
this._depth--;
if (this._depth === 0) {
$(document.body).css('overflow', this._oldOverflow);
}
}
};
/**
* Disables the ability to zoom the page.
*/
WCF.System.DisableZoom = {
/**
* number of times zoom was disabled (nested calls)
* @var integer
*/
_depth: 0,
/**
* old viewport settings in meta[name=viewport]
* @var string
*/
_oldViewportSettings: null,
/**
* Disables zooming.
*/
disable: function () {
if (this._depth === 0) {
var $meta = $('meta[name=viewport]');
this._oldViewportSettings = $meta.attr('content');
$meta.attr('content', this._oldViewportSettings + ',maximum-scale=1');
}
this._depth++;
},
/**
* Enables scrolling again.
* Must be called the same number of times disable() was called to enable scrolling.
*/
enable: function () {
if (this._depth === 0) return;
this._depth--;
if (this._depth === 0) {
$('meta[name=viewport]').attr('content', this._oldViewportSettings);
}
}
};
/**
* Puts an element into HTML 5 fullscreen mode.
*/
WCF.System.Fullscreen = {
/**
* Puts the given element into full screen mode.
* Note: This must be a raw HTMLElement, not a jQuery wrapped one.
* Note: This must be called from an user triggered event listener for
* security reasons.
*
* @param object Element to show full screen.
*/
enterFullscreen: function (element) {
if (element.requestFullscreen) {
element.requestFullscreen();
}
else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
}
else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
},
/**
* Toggles full screen mode. Either calls `enterFullscreen` with the given
* element, if full screen mode is not active. Calls `exitFullscreen`
* otherwise.
*/
toggleFullscreen: function (element) {
if (this.getFullscreenElement() === null) {
this.enterFullscreen(element);
}
else {
this.exitFullscreen();
}
},
/**
* Retrieves the element that is shown in full screen mode.
* Returns null if either full screen mode is not supported or
* if full screen mode is not active.
*
* @return object
*/
getFullscreenElement: function () {
if (document.fullscreenElement) {
return document.fullscreenElement;
}
else if (document.mozFullScreenElement) {
return document.mozFullScreenElement;
}
else if (document.webkitFullscreenElement) {
return document.webkitFullscreenElement;
}
else if (document.msFullscreenElement) {
return document.msFullscreenElement;
}
return null;
},
/**
* Exits full screen mode.
*/
exitFullscreen: function () {
if (document.exitFullscreen) {
document.exitFullscreen();
}
else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
},
/**
* Returns whether the full screen API is supported in this browser.
*
* @return boolean
*/
isSupported: function () {
if (document.documentElement.requestFullscreen || document.documentElement.msRequestFullscreen || document.documentElement.mozRequestFullScreen || document.documentElement.webkitRequestFullscreen) {
return true;
}
return false;
}
};
/**
* Provides the 'jump to page' overlay.
*
* @deprecated 3.0 - use `WoltLabSuite/Core/Ui/Page/JumpTo` instead
*/
WCF.System.PageNavigation = {
init: function(selector, callback) {
require(['WoltLabSuite/Core/Ui/Page/JumpTo'], function(UiPageJumpTo) {
var elements = elBySelAll(selector);
for (var i = 0, length = elements.length; i < length; i++) {
UiPageJumpTo.init(elements[i], callback);
}
});
}
};
/**
* Sends periodical requests to protect the session from expiring. By default
* it will send a request 1 minute before it would expire.
*
* @param integer seconds
*/
WCF.System.KeepAlive = Class.extend({
/**
* Initializes the WCF.System.KeepAlive class.
*
* @param integer seconds
*/
init: function(seconds) {
new WCF.PeriodicalExecuter(function(pe) {
new WCF.Action.Proxy({
autoSend: true,
data: {
actionName: 'keepAlive',
className: 'wcf\\data\\session\\SessionAction'
},
failure: function() { pe.stop(); },
showLoadingOverlay: false,
success: function(data) {
WCF.System.PushNotification.executeCallbacks(data);
},
suppressErrors: true
});
}, (seconds * 1000));
}
});
/**
* System-wide handler for push notifications.
*/
WCF.System.PushNotification = {
/**
* list of callbacks groupped by type
* @var object<array>
*/
_callbacks: { },
/**
* Adds a callback for a specific notification type.
*
* @param string type
* @param object callback
*/
addCallback: function(type, callback) {
if (this._callbacks[type] === undefined) {
this._callbacks[type] = [ ];
}
this._callbacks[type].push(callback);
},
/**
* Executes all registered callbacks by type.
*
* @param object data
*/
executeCallbacks: function(data) {
for (var $type in data.returnValues) {
if (this._callbacks[$type] !== undefined) {
for (var $i = 0; $i < this._callbacks[$type].length; $i++) {
this._callbacks[$type][$i](data.returnValues[$type]);
}
}
}
}
};
/**
* System-wide event system.
*
* @deprecated 3.0 - please use `EventHandler` instead
*/
WCF.System.Event = {
/**
* Registers a new event listener.
*
* @param string identifier
* @param string action
* @param object listener
* @return string
*/
addListener: function(identifier, action, listener) {
return window.__wcf_bc_eventHandler.add(identifier, action, listener);
},
/**
* Removes a listener, requires the uuid returned by addListener().
*
* @param string identifier
* @param string action
* @param string uuid
* @return boolean
*/
removeListener: function(identifier, action, uuid) {
return window.__wcf_bc_eventHandler.remove(identifier, action, uuid);
},
/**
* Removes all registered event listeners for given identifier and action.
*
* @param string identifier
* @param string action
* @return boolean
*/
removeAllListeners: function(identifier, action) {
return window.__wcf_bc_eventHandler.removeAll(identifier, action);
},
/**
* Fires a new event and notifies all registered event listeners.
*
* @param string identifier
* @param string action
* @param object data
*/
fireEvent: function(identifier, action, data) {
window.__wcf_bc_eventHandler.fire(identifier, action, data);
}
};
/**
* Worker support for frontend based upon DatabaseObjectActions.
*
* @param string className
* @param string title
* @param object parameters
* @param object callback
*/
WCF.System.Worker = Class.extend({
/**
* worker aborted
* @var boolean
*/
_aborted: false,
/**
* DBOAction method name
* @var string
*/
_actionName: '',
/**
* callback invoked after worker completed
* @var object
*/
_callback: null,
/**
* DBOAction class name
* @var string
*/
_className: '',
/**
* dialog object
* @var jQuery
*/
_dialog: null,
/**
* action proxy
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* dialog title
* @var string
*/
_title: '',
/**
* Initializes a new worker instance.
*
* @param string actionName
* @param string className
* @param string title
* @param object parameters
* @param object callback
* @param object confirmMessage
*/
init: function(actionName, className, title, parameters, callback) {
this._aborted = false;
this._actionName = actionName;
this._callback = callback || null;
this._className = className;
this._dialog = null;
this._proxy = new WCF.Action.Proxy({
autoSend: true,
data: {
actionName: this._actionName,
className: this._className,
parameters: parameters || { }
},
showLoadingOverlay: false,
success: $.proxy(this._success, this)
});
this._title = title;
},
/**
* Handles response from server.
*
* @param object data
*/
_success: function(data) {
// init binding
if (this._dialog === null) {
this._dialog = $('<div />').hide().appendTo(document.body);
this._dialog.wcfDialog({
closeConfirmMessage: WCF.Language.get('wcf.worker.abort.confirmMessage'),
closeViaModal: false,
onClose: $.proxy(function() {
this._aborted = true;
this._proxy.abortPrevious();
window.location.reload();
}, this),
title: this._title
});
}
if (this._aborted) {
return;
}
if (data.returnValues.template) {
this._dialog.html(data.returnValues.template);
}
// update progress
this._dialog.find('progress').attr('value', data.returnValues.progress).text(data.returnValues.progress + '%').next('span').text(data.returnValues.progress + '%');
// worker is still busy with its business, carry on
if (data.returnValues.progress < 100) {
// send request for next loop
var $parameters = data.returnValues.parameters || { };
$parameters.loopCount = data.returnValues.loopCount;
this._proxy.setOption('data', {
actionName: this._actionName,
className: this._className,
parameters: $parameters
});
this._proxy.sendRequest();
}
else if (this._callback !== null) {
this._callback(this, data);
}
else {
// exchange icon
this._dialog.find('.fa-spinner').removeClass('fa-spinner').addClass('fa-check green');
this._dialog.find('.contentHeader h1').text(WCF.Language.get('wcf.global.worker.completed'));
// display continue button
var $formSubmit = $('<div class="formSubmit" />').appendTo(this._dialog);
$('<button class="buttonPrimary">' + WCF.Language.get('wcf.global.button.next') + '</button>').appendTo($formSubmit).focus().click(function() {
if (data.returnValues.redirectURL) {
window.location = data.returnValues.redirectURL;
}
else {
window.location.reload();
}
});
this._dialog.wcfDialog('render');
}
}
});
/**
* Default implementation for inline editors.
*
* @param string elementSelector
*/
WCF.InlineEditor = Class.extend({
/**
* list of registered callbacks
* @var array<object>
*/
_callbacks: [ ],
/**
* list of dropdown selections
* @var object
*/
_dropdowns: { },
/**
* list of container elements
* @var object
*/
_elements: { },
/**
* notification object
* @var WCF.System.Notification
*/
_notification: null,
/**
* list of known options
* @var array<object>
*/
_options: [ ],
/**
* action proxy
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* list of trigger elements by element id
* @var object<object>
*/
_triggerElements: { },
/**
* list of data to update upon success
* @var array<object>
*/
_updateData: [ ],
/**
* Initializes a new inline editor.
*/
init: function(elementSelector) {
var $elements = $(elementSelector);
if (!$elements.length) {
return;
}
this._setOptions();
var $quickOption = '';
for (var $i = 0, $length = this._options.length; $i < $length; $i++) {
if (this._options[$i].isQuickOption) {
$quickOption = this._options[$i].optionName;
break;
}
}
var self = this;
$elements.each(function(index, element) {
var $element = $(element);
var $elementID = $element.wcfIdentify();
// find trigger element
var $trigger = self._getTriggerElement($element);
if ($trigger === null || $trigger.length !== 1) {
return;
}
$trigger.on(WCF_CLICK_EVENT, $.proxy(self._show, self)).data('elementID', $elementID);
if ($quickOption) {
// simulate click on target action
$trigger.disableSelection().data('optionName', $quickOption).dblclick($.proxy(self._click, self));
}
// store reference
self._elements[$elementID] = $element;
});
this._proxy = new WCF.Action.Proxy({
success: $.proxy(this._success, this)
});
WCF.CloseOverlayHandler.addCallback('WCF.InlineEditor', $.proxy(this._closeAll, this));
this._notification = new WCF.System.Notification(WCF.Language.get('wcf.global.success'), 'success');
},
/**
* Closes all inline editors.
*/
_closeAll: function() {
for (var $elementID in this._elements) {
this._hide($elementID);
}
},
/**
* Sets options for this inline editor.
*/
_setOptions: function() {
this._options = [ ];
},
/**
* Register an option callback for validation and execution.
*
* @param object callback
*/
registerCallback: function(callback) {
if ($.isFunction(callback)) {
this._callbacks.push(callback);
}
},
/**
* Returns the triggering element.
*
* @param jQuery element
* @return jQuery
*/
_getTriggerElement: function(element) {
return null;
},
/**
* Shows a dropdown menu if options are available.
*
* @param object event
*/
_show: function(event) {
event.preventDefault();
var $elementID = $(event.currentTarget).data('elementID');
// build dropdown
var $trigger = null;
if (!this._dropdowns[$elementID]) {
this._triggerElements[$elementID] = $trigger = this._getTriggerElement(this._elements[$elementID]).addClass('dropdownToggle');
var parent = $trigger[0].parentNode;
if (parent && parent.nodeName === 'LI' && parent.childElementCount === 1) {
// do not add a wrapper element if the trigger is the only child
parent.classList.add('dropdown');
}
else {
$trigger.wrap('<span class="dropdown" />');
}
this._dropdowns[$elementID] = $('<ul class="dropdownMenu" />').insertAfter($trigger);
}
this._dropdowns[$elementID].empty();
// validate options
var $hasOptions = false;
var $lastElementType = '';
for (var $i = 0, $length = this._options.length; $i < $length; $i++) {
var $option = this._options[$i];
if ($option.optionName === 'divider') {
if ($lastElementType !== '' && $lastElementType !== 'divider') {
$('<li class="dropdownDivider" />').appendTo(this._dropdowns[$elementID]);
$lastElementType = $option.optionName;
}
}
else if (this._validate($elementID, $option.optionName) || this._validateCallbacks($elementID, $option.optionName)) {
var $listItem = $('<li><span>' + $option.label + '</span></li>').appendTo(this._dropdowns[$elementID]);
$listItem.data('elementID', $elementID).data('optionName', $option.optionName).data('isQuickOption', ($option.isQuickOption ? true : false)).click($.proxy(this._click, this));
$hasOptions = true;
$lastElementType = $option.optionName;
}
}
if ($hasOptions) {
// if last child is divider, remove it
var $lastChild = this._dropdowns[$elementID].children().last();
if ($lastChild.hasClass('dropdownDivider')) {
$lastChild.remove();
}
// check if only element is a quick option
var $quickOption = null;
var $count = 0;
this._dropdowns[$elementID].children().each(function(index, child) {
var $child = $(child);
if (!$child.hasClass('dropdownDivider')) {
if ($child.data('isQuickOption')) {
$quickOption = $child;
}
else {
$count++;
}
}
});
if (!$count) {
$quickOption.trigger('click');
if (this._triggerElements[$elementID]) {
WCF.Dropdown.close(this._triggerElements[$elementID].parents('.dropdown').wcfIdentify());
}
return false;
}
}
if ($trigger !== null) {
WCF.Dropdown.initDropdown($trigger, true);
}
return false;
},
/**
* Validates an option.
*
* @param string elementID
* @param string optionName
* @returns boolean
*/
_validate: function(elementID, optionName) {
return false;
},
/**
* Validates an option provided by callbacks.
*
* @param string elementID
* @param string optionName
* @return boolean
*/
_validateCallbacks: function(elementID, optionName) {
var $length = this._callbacks.length;
if ($length) {
for (var $i = 0; $i < $length; $i++) {
if (this._callbacks[$i].validate(this._elements[elementID], optionName)) {
return true;
}
}
}
return false;
},
/**
* Handles AJAX responses.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
var $length = this._updateData.length;
if (!$length) {
return;
}
this._updateState(data);
this._updateData = [ ];
},
/**
* Update element states based upon update data.
*
* @param object data
*/
_updateState: function(data) { },
/**
* Handles clicks within dropdown.
*
* @param object event
*/
_click: function(event) {
var $listItem = $(event.currentTarget);
var $elementID = $listItem.data('elementID');
var $optionName = $listItem.data('optionName');
if (!this._execute($elementID, $optionName)) {
this._executeCallback($elementID, $optionName);
}
this._hide($elementID);
},
/**
* Executes actions associated with an option.
*
* @param string elementID
* @param string optionName
* @return boolean
*/
_execute: function(elementID, optionName) {
return false;
},
/**
* Executes actions associated with an option provided by callbacks.
*
* @param string elementID
* @param string optionName
* @return boolean
*/
_executeCallback: function(elementID, optionName) {
var $length = this._callbacks.length;
if ($length) {
for (var $i = 0; $i < $length; $i++) {
if (this._callbacks[$i].execute(this._elements[elementID], optionName)) {
return true;
}
}
}
return false;
},
/**
* Hides a dropdown menu.
*
* @param string elementID
*/
_hide: function(elementID) {
if (this._dropdowns[elementID]) {
this._dropdowns[elementID].empty().removeClass('dropdownOpen');
}
}
});
/**
* Default implementation for ajax file uploads.
*
* @deprecated Use WoltLabSuite/Core/Upload
*
* @param jquery buttonSelector
* @param jquery fileListSelector
* @param string className
* @param jquery options
*/
WCF.Upload = Class.extend({
/**
* name of the upload field
* @var string
*/
_name: '__files[]',
/**
* button selector
* @var jQuery
*/
_buttonSelector: null,
/**
* file list selector
* @var jQuery
*/
_fileListSelector: null,
/**
* upload file
* @var jQuery
*/
_fileUpload: null,
/**
* class name
* @var string
*/
_className: '',
/**
* iframe for IE<10 fallback
* @var jQuery
*/
_iframe: null,
/**
* internal file id
* @var integer
*/
_internalFileID: 0,
/**
* additional options
* @var jQuery
*/
_options: {},
/**
* upload matrix
* @var array
*/
_uploadMatrix: [],
/**
* true, if the active user's browser supports ajax file uploads
* @var boolean
*/
_supportsAJAXUpload: true,
/**
* fallback overlay for stupid browsers
* @var jquery
*/
_overlay: null,
/**
* Initializes a new upload handler.
*
* @param string buttonSelector
* @param string fileListSelector
* @param string className
* @param object options
*/
init: function(buttonSelector, fileListSelector, className, options) {
this._buttonSelector = buttonSelector;
this._fileListSelector = fileListSelector;
this._className = className;
this._internalFileID = 0;
this._options = $.extend(true, {
action: 'upload',
multiple: false,
url: 'index.php?ajax-upload/&t=' + SECURITY_TOKEN
}, options || { });
this._options.url = WCF.convertLegacyURL(this._options.url);
if (this._options.url.indexOf('index.php') === 0) {
this._options.url = WSC_API_URL + this._options.url;
}
// check for ajax upload support
var $xhr = new XMLHttpRequest();
this._supportsAJAXUpload = ($xhr && ('upload' in $xhr) && ('onprogress' in $xhr.upload));
// create upload button
this._createButton();
},
/**
* Creates the upload button.
*/
_createButton: function() {
if (this._supportsAJAXUpload) {
this._fileUpload = $('<input type="file" name="' + this._name + '" ' + (this._options.multiple ? 'multiple="true" ' : '') + '/>');
this._fileUpload.change($.proxy(this._upload, this));
var $button = $('<p class="button uploadButton"><span>' + WCF.Language.get('wcf.global.button.upload') + '</span></p>');
$button.prepend(this._fileUpload);
}
else {
var $button = $('<p class="button uploadFallbackButton"><span>' + WCF.Language.get('wcf.global.button.upload') + '</span></p>');
$button.click($.proxy(this._showOverlay, this));
}
this._insertButton($button);
},
/**
* Inserts the upload button.
*
* @param jQuery button
*/
_insertButton: function(button) {
this._buttonSelector.prepend(button);
},
/**
* Removes the upload button.
*/
_removeButton: function() {
var $selector = '.uploadButton';
if (!this._supportsAJAXUpload) {
$selector = '.uploadFallbackButton';
}
this._buttonSelector.find($selector).remove();
},
/**
* Callback for file uploads.
*
* @param object event
* @param File file
* @param Blob blob
* @return integer
*/
_upload: function(event, file, blob) {
var $uploadID = null;
var $files = [ ];
if (file) {
$files.push(file);
}
else if (blob) {
var $ext = '';
switch (blob.type) {
case 'image/png':
$ext = '.png';
break;
case 'image/jpeg':
$ext = '.jpg';
break;
case 'image/gif':
$ext = '.gif';
break;
}
$files.push({
name: 'pasted-from-clipboard' + $ext
});
}
else {
$files = this._fileUpload.prop('files');
}
if ($files.length) {
var $fd = new FormData();
$uploadID = this._createUploadMatrix($files);
// no more files left, abort
if (!this._uploadMatrix[$uploadID].length) {
return null;
}
for (var $i = 0, $length = $files.length; $i < $length; $i++) {
if (this._uploadMatrix[$uploadID][$i]) {
var $internalFileID = this._uploadMatrix[$uploadID][$i].data('internalFileID');
if (blob) {
$fd.append('__files[' + $internalFileID + ']', blob, $files[$i].name);
}
else {
$fd.append('__files[' + $internalFileID + ']', $files[$i]);
}
}
}
$fd.append('actionName', this._options.action);
$fd.append('className', this._className);
var $additionalParameters = this._getParameters();
for (var $name in $additionalParameters) {
$fd.append('parameters[' + $name + ']', $additionalParameters[$name]);
}
var self = this;
$.ajax({
type: 'POST',
url: this._options.url,
enctype: 'multipart/form-data',
data: $fd,
contentType: false,
processData: false,
success: function(data, textStatus, jqXHR) {
self._success($uploadID, data);
},
error: $.proxy(this._error, this),
xhr: function() {
var $xhr = $.ajaxSettings.xhr();
if ($xhr) {
$xhr.upload.addEventListener('progress', function(event) {
self._progress($uploadID, event);
}, false);
}
return $xhr;
}
});
}
return $uploadID;
},
/**
* Creates upload matrix for provided files.
*
* @param array<object> files
* @return integer
*/
_createUploadMatrix: function(files) {
if (files.length) {
var $uploadID = this._uploadMatrix.length;
this._uploadMatrix[$uploadID] = [ ];
for (var $i = 0, $length = files.length; $i < $length; $i++) {
var $file = files[$i];
var $li = this._initFile($file);
if (!$li.hasClass('uploadFailed')) {
$li.data('filename', $file.name).data('internalFileID', this._internalFileID++);
this._uploadMatrix[$uploadID][$i] = $li;
}
}
return $uploadID;
}
return null;
},
/**
* Callback for success event.
*
* @param integer uploadID
* @param object data
*/
_success: function(uploadID, data) { },
/**
* Callback for error event.
*
* @param jQuery jqXHR
* @param string textStatus
* @param string errorThrown
*/
_error: function(jqXHR, textStatus, errorThrown) { },
/**
* Callback for progress event.
*
* @param integer uploadID
* @param object event
*/
_progress: function(uploadID, event) {
var $percentComplete = Math.round(event.loaded * 100 / event.total);
for (var $i in this._uploadMatrix[uploadID]) {
this._uploadMatrix[uploadID][$i].find('progress').attr('value', $percentComplete);
}
},
/**
* Returns additional parameters.
*
* @return object
*/
_getParameters: function() {
return {};
},
/**
* Initializes list item for uploaded file.
*
* @return jQuery
*/
_initFile: function(file) {
return $('<li>' + file.name + ' (' + file.size + ')<progress max="100" /></li>').appendTo(this._fileListSelector);
},
/**
* Shows the fallback overlay (work in progress)
*/
_showOverlay: function() {
// create iframe
if (this._iframe === null) {
this._iframe = $('<iframe name="__fileUploadIFrame" />').hide().appendTo(document.body);
}
// create overlay
if (!this._overlay) {
this._overlay = $('<div><form enctype="multipart/form-data" method="post" action="' + this._options.url + '" target="__fileUploadIFrame" /></div>').hide().appendTo(document.body);
var $form = this._overlay.find('form');
$('<dl class="wide"><dd><input type="file" id="__fileUpload" name="' + this._name + '" ' + (this._options.multiple ? 'multiple="true" ' : '') + '/></dd></dl>').appendTo($form);
$('<div class="formSubmit"><input type="submit" value="Upload" accesskey="s" /></div></form>').appendTo($form);
$('<input type="hidden" name="isFallback" value="1" />').appendTo($form);
$('<input type="hidden" name="actionName" value="' + this._options.action + '" />').appendTo($form);
$('<input type="hidden" name="className" value="' + this._className + '" />').appendTo($form);
var $additionalParameters = this._getParameters();
for (var $name in $additionalParameters) {
$('<input type="hidden" name="' + $name + '" value="' + $additionalParameters[$name] + '" />').appendTo($form);
}
$form.submit($.proxy(function() {
var $file = {
name: this._getFilename(),
size: ''
};
var $uploadID = this._createUploadMatrix([ $file ]);
var self = this;
this._iframe.data('loading', true).off('load').load(function() { self._evaluateResponse($uploadID); });
this._overlay.wcfDialog('close');
}, this));
}
this._overlay.wcfDialog({
title: WCF.Language.get('wcf.global.button.upload')
});
},
/**
* Evaluates iframe response.
*
* @param integer uploadID
*/
_evaluateResponse: function(uploadID) {
var $returnValues = $.parseJSON(this._iframe.contents().find('pre').html());
this._success(uploadID, $returnValues);
},
/**
* Returns name of selected file.
*
* @return string
*/
_getFilename: function() {
return $('#__fileUpload').val().split('\\').pop();
}
});
/**
* Default implementation for parallel AJAX file uploads.
*
* @deprecated Use WoltLabSuite/Core/Upload
*/
WCF.Upload.Parallel = WCF.Upload.extend({
/**
* @see WCF.Upload.init()
*/
init: function(buttonSelector, fileListSelector, className, options) {
// force multiple uploads
options = $.extend(true, options || { }, {
multiple: true
});
this._super(buttonSelector, fileListSelector, className, options);
},
/**
* @see WCF.Upload._upload()
*/
_upload: function() {
var $files = this._fileUpload.prop('files');
for (var $i = 0, $length = $files.length; $i < $length; $i++) {
var $file = $files[$i];
var $formData = new FormData();
var $internalFileID = this._createUploadMatrix($file);
if (!this._uploadMatrix[$internalFileID].length) {
continue;
}
$formData.append('__files[' + $internalFileID + ']', $file);
$formData.append('actionName', this._options.action);
$formData.append('className', this._className);
var $additionalParameters = this._getParameters();
for (var $name in $additionalParameters) {
$formData.append('parameters[' + $name + ']', $additionalParameters[$name]);
}
this._sendRequest($internalFileID, $formData);
}
},
/**
* Sends an AJAX request to upload a file.
*
* @param integer internalFileID
* @param FormData formData
*/
_sendRequest: function(internalFileID, formData) {
var self = this;
$.ajax({
type: 'POST',
url: this._options.url,
enctype: 'multipart/form-data',
data: formData,
contentType: false,
processData: false,
success: function(data, textStatus, jqXHR) {
self._success(internalFileID, data);
},
error: $.proxy(this._error, this),
xhr: function() {
var $xhr = $.ajaxSettings.xhr();
if ($xhr) {
$xhr.upload.addEventListener('progress', function(event) {
self._progress(internalFileID, event);
}, false);
}
return $xhr;
}
});
},
/**
* Creates upload matrix for provided file and returns its internal file id.
*
* @param object file
* @return integer
*/
_createUploadMatrix: function(file) {
var $li = this._initFile(file);
if (!$li.hasClass('uploadFailed')) {
$li.data('filename', file.name).data('internalFileID', this._internalFileID);
this._uploadMatrix[this._internalFileID++] = $li;
return this._internalFileID - 1;
}
return null;
},
/**
* Callback for success event.
*
* @param integer internalFileID
* @param object data
*/
_success: function(internalFileID, data) { },
/**
* Callback for progress event.
*
* @param integer internalFileID
* @param object event
*/
_progress: function(internalFileID, event) {
var $percentComplete = Math.round(event.loaded * 100 / event.total);
this._uploadMatrix[internalFileID].find('progress').attr('value', $percentComplete);
},
/**
* @see WCF.Upload._showOverlay()
*/
_showOverlay: function() {
// create iframe
if (this._iframe === null) {
this._iframe = $('<iframe name="__fileUploadIFrame" />').hide().appendTo(document.body);
}
// create overlay
if (!this._overlay) {
this._overlay = $('<div><form enctype="multipart/form-data" method="post" action="' + this._options.url + '" target="__fileUploadIFrame" /></div>').hide().appendTo(document.body);
var $form = this._overlay.find('form');
$('<dl class="wide"><dd><input type="file" id="__fileUpload" name="' + this._name + '" ' + (this._options.multiple ? 'multiple="true" ' : '') + '/></dd></dl>').appendTo($form);
$('<div class="formSubmit"><input type="submit" value="Upload" accesskey="s" /></div></form>').appendTo($form);
$('<input type="hidden" name="isFallback" value="1" />').appendTo($form);
$('<input type="hidden" name="actionName" value="' + this._options.action + '" />').appendTo($form);
$('<input type="hidden" name="className" value="' + this._className + '" />').appendTo($form);
var $additionalParameters = this._getParameters();
for (var $name in $additionalParameters) {
$('<input type="hidden" name="' + $name + '" value="' + $additionalParameters[$name] + '" />').appendTo($form);
}
$form.submit($.proxy(function() {
var $file = {
name: this._getFilename(),
size: ''
};
var $internalFileID = this._createUploadMatrix($file);
var self = this;
this._iframe.data('loading', true).off('load').load(function() { self._evaluateResponse($internalFileID); });
this._overlay.wcfDialog('close');
}, this));
}
this._overlay.wcfDialog({
title: WCF.Language.get('wcf.global.button.upload')
});
},
/**
* Evaluates iframe response.
*
* @param integer internalFileID
*/
_evaluateResponse: function(internalFileID) {
var $returnValues = $.parseJSON(this._iframe.contents().find('pre').html());
this._success(internalFileID, $returnValues);
}
});
/**
* Namespace for sortables.
*/
WCF.Sortable = { };
/**
* Sortable implementation for lists.
*
* @param string containerID
* @param string className
* @param integer offset
* @param object options
*/
WCF.Sortable.List = Class.extend({
/**
* additional parameters for AJAX request
* @var object
*/
_additionalParameters: { },
/**
* action class name
* @var string
*/
_className: '',
/**
* container id
* @var string
*/
_containerID: '',
/**
* container object
* @var jQuery
*/
_container: null,
/**
* notification object
* @var WCF.System.Notification
*/
_notification: null,
/**
* show order offset
* @var integer
*/
_offset: 0,
/**
* list of options
* @var object
*/
_options: { },
/**
* proxy object
* @var WCF.Action.Proxy
*/
_proxy: null,
/**
* object structure
* @var object
*/
_structure: { },
/**
* Creates a new sortable list.
*
* @param string containerID
* @param string className
* @param integer offset
* @param object options
* @param boolean isSimpleSorting
* @param object additionalParameters
*/
init: function(containerID, className, offset, options, isSimpleSorting, additionalParameters) {
this._additionalParameters = additionalParameters || { };
this._containerID = $.wcfEscapeID(containerID);
this._container = $('#' + this._containerID);
this._className = className;
this._offset = (offset) ? offset : 0;
this._proxy = new WCF.Action.Proxy({
success: $.proxy(this._success, this)
});
this._structure = { };
// init sortable
this._options = $.extend(true, {
axis: 'y',
connectWith: '#' + this._containerID + ' .sortableList',
disableNesting: 'sortableNoNesting',
doNotClear: true,
errorClass: 'sortableInvalidTarget',
forcePlaceholderSize: true,
helper: 'clone',
items: 'li:not(.sortableNoSorting)',
opacity: .6,
placeholder: 'sortablePlaceholder',
tolerance: 'pointer',
toleranceElement: '> span'
}, options || { });
var sortableList = $('#' + this._containerID + ' .sortableList');
if (sortableList.is('tbody') && this._options.helper === 'clone') {
this._options.helper = this._tableRowHelper.bind(this);
// explicitly set column widths to avoid column resizing during dragging
var thead = sortableList.prev('thead');
if (thead) {
thead.find('th').each(function(index, element) {
element = $(element);
element.width(element.width());
});
}
}
if (isSimpleSorting) {
sortableList.sortable(this._options);
}
else {
sortableList.nestedSortable(this._options);
}
if (this._className) {
var $formSubmit = this._container.find('.formSubmit');
if (!$formSubmit.length) {
$formSubmit = this._container.next('.formSubmit');
if (!$formSubmit.length) {
console.debug("[WCF.Sortable.Simple] Unable to find form submit for saving, aborting.");
return;
}
}
$formSubmit.children('button[data-type="submit"]').click($.proxy(this._submit, this));
}
},
/**
* Fixes the width of the cells of the dragged table row.
*
* @param {Event} event
* @param {jQuery} ui
* @return {jQuery}
*/
_tableRowHelper: function(event, ui) {
ui.children('td').each(function(index, element) {
element = $(element);
element.width(element.width());
});
return ui;
},
/**
* Saves object structure.
*/
_submit: function() {
// reset structure
this._structure = { };
// build structure
this._container.find('.sortableList').each($.proxy(function(index, list) {
var $list = $(list);
var $parentID = $list.data('objectID');
if ($parentID !== undefined) {
$list.children(this._options.items).each($.proxy(function(index, listItem) {
var $objectID = $(listItem).data('objectID');
if (!this._structure[$parentID]) {
this._structure[$parentID] = [ ];
}
this._structure[$parentID].push($objectID);
}, this));
}
}, this));
// send request
var $parameters = $.extend(true, {
data: {
offset: this._offset,
structure: this._structure
}
}, this._additionalParameters);
this._proxy.setOption('data', {
actionName: 'updatePosition',
className: this._className,
interfaceName: 'wcf\\data\\ISortableAction',
parameters: $parameters
});
this._proxy.sendRequest();
},
/**
* Shows notification upon success.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
if (this._notification === null) {
this._notification = new WCF.System.Notification(WCF.Language.get('wcf.global.success.edit'));
}
this._notification.show();
}
});
WCF.Popover = Class.extend({
/**
* currently active element id
* @var string
*/
_activeElementID: '',
_identifier: '',
_popoverObj: null,
/**
* Initializes a new WCF.Popover object.
*
* @param string selector
*/
init: function(selector) {
var mobile = false;
require(['Environment'], function(Environment) {
if (Environment.platform() !== 'desktop') {
mobile = true;
}
}.bind(this));
if (mobile) return;
// assign default values
this._activeElementID = '';
this._identifier = selector;
require(['WoltLabSuite/Core/Controller/Popover'], (function(popover) {
popover.init({
attributeName: 'legacy',
className: selector,
identifier: this._identifier,
legacy: true,
loadCallback: this._legacyLoad.bind(this)
});
}).bind(this));
},
_initContainers: function() {},
_legacyLoad: function(objectId, popover) {
this._activeElementID = objectId;
this._popoverObj = popover;
this._loadContent();
},
_insertContent: function(elementId, template) {
this._popoverObj.setContent(this._identifier, elementId, template);
}
});
/**
* Provides an extensible item list with built-in search.
*
* @param string itemListSelector
* @param string searchInputSelector
*/
WCF.EditableItemList = Class.extend({
/**
* allows custom input not recognized by search to be added
* @var boolean
*/
_allowCustomInput: false,
/**
* action class name
* @var string
*/
_className: '',
/**
* internal data storage
* @var mixed
*/
_data: { },
/**
* form container
* @var jQuery
*/
_form: null,
/**
* item list container
* @var jQuery
*/
_itemList: null,
/**
* current object id
* @var integer
*/
_objectID: 0,
/**
* object type id
* @var integer
*/
_objectTypeID: 0,
/**
* search controller
* @var WCF.Search.Base
*/
_search: null,
/**
* search input element
* @var jQuery
*/
_searchInput: null,
/**
* Creates a new WCF.EditableItemList object.
*
* @param string itemListSelector
* @param string searchInputSelector
*/
init: function(itemListSelector, searchInputSelector) {
this._itemList = $(itemListSelector);
this._searchInput = $(searchInputSelector);
this._data = { };
if (!this._itemList.length || !this._searchInput.length) {
console.debug("[WCF.EditableItemList] Item list and/or search input do not exist, aborting.");
return;
}
this._objectID = this._getObjectID();
this._objectTypeID = this._getObjectTypeID();
// bind item listener
this._itemList.find('.jsEditableItem').click($.proxy(this._click, this));
// create item list
if (!this._itemList.children('ul').length) {
$('<ul />').appendTo(this._itemList);
}
this._itemList = this._itemList.children('ul');
// bind form submit
this._form = this._itemList.parents('form').submit($.proxy(this._submit, this));
if (this._allowCustomInput) {
var self = this;
this._searchInput.keydown($.proxy(this._keyDown, this)).keypress($.proxy(this._keyPress, this)).on('paste', function() {
setTimeout(function() { self._onPaste(); }, 100);
});
}
// block form submit through [ENTER]
this._searchInput.parents('.dropdown').data('preventSubmit', true);
},
/**
* Handles the key down event.
*
* @param object event
*/
_keyDown: function(event) {
if (event === null) {
return this._keyPress(null);
}
return true;
},
/**
* Handles the key press event.
*
* @param object event
*/
_keyPress: function(event) {
// 44 = [,] (charCode != keyCode)
if (event === null || event.charCode === 44 || event.charCode === $.ui.keyCode.ENTER || ($.browser.mozilla && event.keyCode === $.ui.keyCode.ENTER)) {
if (event !== null && event.charCode === $.ui.keyCode.ENTER && this._search) {
if (this._search._itemIndex !== -1) {
return false;
}
}
var $value = $.trim(this._searchInput.val());
// read everything left from caret position
if (event && event.charCode === 44) {
$value = $value.substring(0, this._searchInput.getCaret());
}
if ($value === '') {
return true;
}
this.addItem({
objectID: 0,
label: $value
});
// reset input
if (event && event.charCode === 44) {
this._searchInput.val($.trim(this._searchInput.val().substr(this._searchInput.getCaret())));
}
else {
this._searchInput.val('');
}
if (event !== null) {
event.stopPropagation();
}
return false;
}
return true;
},
/**
* Handle paste event.
*/
_onPaste: function() {
// split content by comma
var $value = $.trim(this._searchInput.val());
$value = $value.split(',');
for (var $i = 0, $length = $value.length; $i < $length; $i++) {
var $label = $.trim($value[$i]);
if ($label === '') {
continue;
}
this.addItem({
objectID: 0,
label: $label
});
}
this._searchInput.val('');
},
/**
* Loads raw data and converts it into internal structure. Override this methods
* in your derived classes.
*
* @param object data
*/
load: function(data) { },
/**
* Removes an item on click.
*
* @param object event
* @return boolean
*/
_click: function(event) {
var $element = $(event.currentTarget);
var $objectID = $element.data('objectID');
var $label = $element.data('label');
if (this._search) {
this._search.removeExcludedSearchValue($label);
}
this._removeItem($objectID, $label);
$element.remove();
event.stopPropagation();
return false;
},
/**
* Returns current object id.
*
* @return integer
*/
_getObjectID: function() {
return 0;
},
/**
* Returns current object type id.
*
* @return integer
*/
_getObjectTypeID: function() {
return 0;
},
/**
* Adds a new item to the list.
*
* @param object data
* @return boolean
*/
addItem: function(data) {
if (this._data[data.objectID]) {
if (!(data.objectID === 0 && this._allowCustomInput)) {
return true;
}
}
var $listItem = $('<li class="badge">' + WCF.String.escapeHTML(data.label) + '</li>').data('objectID', data.objectID).data('label', data.label).appendTo(this._itemList);
$listItem.click($.proxy(this._click, this));
if (this._search) {
this._search.addExcludedSearchValue(data.label);
}
this._addItem(data.objectID, data.label);
return true;
},
/**
* Clears the list of items.
*/
clearList: function() {
this._itemList.children('li').each($.proxy(function(index, element) {
var $element = $(element);
if (this._search) {
this._search.removeExcludedSearchValue($element.data('label'));
}
$element.remove();
this._removeItem($element.data('objectID'), $element.data('label'));
}, this));
},
/**
* Handles form submit, override in your class.
*/
_submit: function() {
this._keyDown(null);
},
/**
* Adds an item to internal storage.
*
* @param integer objectID
* @param string label
*/
_addItem: function(objectID, label) {
this._data[objectID] = label;
},
/**
* Removes an item from internal storage.
*
* @param integer objectID
* @param string label
*/
_removeItem: function(objectID, label) {
delete this._data[objectID];
},
/**
* Returns the search input field.
*
* @return jQuery
*/
getSearchInput: function() {
return this._searchInput;
}
});
/**
* Provides a language chooser.
*
* @param {string} containerId input element conainer id
* @param {string} chooserId input element id
* @param {int} languageId selected language id
* @param {object<int, object<string, string>>} languages data of available languages
* @param {function} callback function called after a language is selected
* @param {boolean} allowEmptyValue true if no language may be selected
*
* @deprecated 3.0 - please use `WoltLabSuite/Core/Language/Chooser` instead
*/
WCF.Language.Chooser = Class.extend({
/**
* Initializes the language chooser.
*
* @param {string} containerId input element conainer id
* @param {string} chooserId input element id
* @param {int} languageId selected language id
* @param {object<int, object<string, string>>} languages data of available languages
* @param {function} callback function called after a language is selected
* @param {boolean} allowEmptyValue true if no language may be selected
*/
init: function(containerId, chooserId, languageId, languages, callback, allowEmptyValue) {
require(['WoltLabSuite/Core/Language/Chooser'], function(LanguageChooser) {
LanguageChooser.init(containerId, chooserId, languageId, languages, callback, allowEmptyValue);
});
}
});
/**
* Namespace for style related classes.
*/
WCF.Style = { };
/**
* Converts static user panel items into interactive dropdowns.
*
* @deprecated 2.1 - Please use WCF.User.Panel.Interactive instead
*
* @param string containerID
*/
WCF.UserPanel = Class.extend({
/**
* target container
* @var jQuery
*/
_container: null,
/**
* initialization state
* @var boolean
*/
_didLoad: false,
/**
* original link element
* @var jQuery
*/
_link: null,
/**
* language variable name for 'no items'
* @var string
*/
_noItems: '',
/**
* reverts to original link if return values are empty
* @var boolean
*/
_revertOnEmpty: true,
/**
* Initialites the WCF.UserPanel class.
*
* @param string containerID
*/
init: function(containerID) {
this._container = $('#' + containerID);
this._didLoad = false;
this._revertOnEmpty = true;
if (this._container.length != 1) {
console.debug("[WCF.UserPanel] Unable to find container identfied by '" + containerID + "', aborting.");
return;
}
this._convert();
},
/**
* Converts link into an interactive dropdown menu.
*/
_convert: function() {
this._container.addClass('dropdown');
this._link = this._container.children('a').remove();
var $button = $('<a href="' + this._link.attr('href') + '" class="dropdownToggle">' + this._link.html() + '</a>').appendTo(this._container).click($.proxy(this._click, this));
var $dropdownMenu = $('<ul class="dropdownMenu" />').appendTo(this._container);
$('<li class="jsDropdownPlaceholder"><span>' + WCF.Language.get('wcf.global.loading') + '</span></li>').appendTo($dropdownMenu);
this._addDefaultItems($dropdownMenu);
this._container.dblclick($.proxy(function() {
window.location = this._link.attr('href');
return false;
}, this));
WCF.Dropdown.initDropdown($button, false);
},
/**
* Adds default items to dropdown menu.
*
* @param jQuery dropdownMenu
*/
_addDefaultItems: function(dropdownMenu) { },
/**
* Adds a dropdown divider.
*
* @param jQuery dropdownMenu
*/
_addDivider: function(dropdownMenu) {
$('<li class="dropdownDivider" />').appendTo(dropdownMenu);
},
/**
* Handles clicks on the dropdown item.
*
* @param object event
*/
_click: function(event) {
event.preventDefault();
if (this._didLoad) {
return;
}
new WCF.Action.Proxy({
autoSend: true,
data: this._getParameters(),
success: $.proxy(this._success, this)
});
this._didLoad = true;
},
/**
* Returns a list of parameters for AJAX request.
*
* @return object
*/
_getParameters: function() {
return { };
},
/**
* Handles successful AJAX requests.
*
* @param object data
* @param string textStatus
* @param jQuery jqXHR
*/
_success: function(data, textStatus, jqXHR) {
var $dropdownMenu = WCF.Dropdown.getDropdownMenu(this._container.wcfIdentify());
$dropdownMenu.children('.jsDropdownPlaceholder').remove();
if (data.returnValues && data.returnValues.template) {
$('' + data.returnValues.template).prependTo($dropdownMenu);
// update badge
this._updateBadge(data.returnValues.totalCount);
this._after($dropdownMenu);
}
else {
$('<li><span>' + WCF.Language.get(this._noItems) + '</span></li>').prependTo($dropdownMenu);
// remove badge
this._updateBadge(0);
}
},
/**
* Updates badge count.
*
* @param integer count
*/
_updateBadge: function(count) {
count = parseInt(count) || 0;
if (count) {
var $badge = this._container.find('.badge');
if (!$badge.length) {
$badge = $('<span class="badge badgeUpdate" />').appendTo(this._container.children('.dropdownToggle'));
$badge.before(' ');
}
$badge.html(count);
}
else {
this._container.find('.badge').remove();
}
},
/**
* Execute actions after the dropdown menu has been populated.
*
* @param object dropdownMenu
*/
_after: function(dropdownMenu) { }
});
jQuery.fn.extend({
// shim for 'ui.wcfDialog'
wcfDialog: function(method) {
var args = arguments;
require(['Dom/Util', 'Ui/Dialog'], (function(DomUtil, UiDialog) {
var id = DomUtil.identify(this[0]);
if (method === 'close') {
UiDialog.close(id);
}
else if (method === 'render') {
UiDialog.rebuild(id);
}
else if (method === 'option') {
if (args.length === 3 && args[1] === 'title' && typeof args[2] === 'string') {
UiDialog.setTitle(id, args[2]);
}
}
else {
if (this[0].parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
// if element is not already part of the DOM, UiDialog.open() will fail
document.body.appendChild(this[0]);
}
UiDialog.openStatic(id, null, (args.length === 1 && typeof args[0] === 'object') ? args[0] : {});
}
}).bind(this));
return this;
}
});
/**
* Provides a slideshow for lists.
*/
$.widget('ui.wcfSlideshow', {
/**
* button list object
* @var jQuery
*/
_buttonList: null,
/**
* number of items
* @var integer
*/
_count: 0,
/**
* item index
* @var integer
*/
_index: 0,
/**
* item list object
* @var jQuery
*/
_itemList: null,
/**
* list of items
* @var jQuery
*/
_items: null,
/**
* timer object
* @var WCF.PeriodicalExecuter
*/
_timer: null,
/**
* list item width
* @var integer
*/
_width: 0,
/**
* list of options
* @var object
*/
options: {
/* enables automatic cycling of items */
cycle: true,
/* cycle interval in seconds */
cycleInterval: 5,
/* gap between items in pixels */
itemGap: 50
},
/**
* Creates a new instance of ui.wcfSlideshow.
*/
_create: function() {
this._itemList = this.element.children('ul');
this._items = this._itemList.children('li');
this._count = this._items.length;
this._index = 0;
if (this._count > 1) {
this._initSlideshow();
}
},
/**
* Initializes the slideshow.
*/
_initSlideshow: function() {
// calculate item dimensions
var $itemHeight = $(this._items.get(0)).outerHeight();
this._items.addClass('slideshowItem');
this._width = this.element.css('height', $itemHeight).innerWidth();
this._itemList.addClass('slideshowItemList').css('left', 0);
this._items.each($.proxy(function(index, item) {
$(item).show().css({
height: $itemHeight,
left: ((this._width + this.options.itemGap) * index),
width: this._width
});
}, this));
this.element.css({
height: $itemHeight,
width: this._width
}).hover($.proxy(this._hoverIn, this), $.proxy(this._hoverOut, this));
// create toggle buttons
this._buttonList = $('<ul class="slideshowButtonList" />').appendTo(this.element);
for (var $i = 0; $i < this._count; $i++) {
var $link = $('<li><a><span class="icon icon16 fa-circle" /></a></li>').data('index', $i).click($.proxy(this._click, this)).appendTo(this._buttonList);
if ($i == 0) {
$link.find('.icon').addClass('active');
}
}
this._resetTimer();
$(window).resize($.proxy(this._resize, this));
},
/**
* Rebuilds slideshow height in case the initial height contained resources affecting the
* element height, but loading has not completed on slideshow init.
*/
rebuildHeight: function() {
var $firstItem = $(this._items.get(0)).css('height', 'auto');
var $itemHeight = $firstItem.outerHeight();
this._items.css('height', $itemHeight + 'px');
this.element.css('height', $itemHeight + 'px');
},
/**
* Handles browser resizing
*/
_resize: function() {
this._width = this.element.css('width', 'auto').innerWidth();
this._items.each($.proxy(function(index, item) {
$(item).css({
left: ((this._width + this.options.itemGap) * index),
width: this._width
});
}, this));
this._index--;
this.moveTo(null);
},
/**
* Disables cycling while hovering.
*/
_hoverIn: function() {
if (this._timer !== null) {
this._timer.stop();
}
},
/**
* Enables cycling after mouse out.
*/
_hoverOut: function() {
this._resetTimer();
},
/**
* Resets cycle timer.
*/
_resetTimer: function() {
if (!this.options.cycle) {
return;
}
if (this._timer !== null) {
this._timer.stop();
}
var self = this;
this._timer = new WCF.PeriodicalExecuter(function() {
self.moveTo(null);
}, this.options.cycleInterval * 1000);
},
/**
* Handles clicks on the select buttons.
*
* @param object event
*/
_click: function(event) {
this.moveTo($(event.currentTarget).data('index'));
this._resetTimer();
},
/**
* Moves to a specified item index, NULL will move to the next item in list.
*
* @param integer index
*/
moveTo: function(index) {
this._index = (index === null) ? this._index + 1 : index;
if (this._index == this._count) {
this._index = 0;
}
$(this._buttonList.find('.icon').removeClass('active').get(this._index)).addClass('active');
this._itemList.css('left', this._index * (this._width + this.options.itemGap) * -1);
this._trigger('moveTo', null, { index: this._index });
},
/**
* Returns item by index or null if index is invalid.
*
* @return jQuery
*/
getItem: function(index) {
if (this._items[index]) {
return this._items[index];
}
return null;
}
});
jQuery.fn.extend({
datepicker: function(method) {
var element = this[0], parameters = Array.prototype.slice.call(arguments, 1);
switch (method) {
case 'destroy':
window.__wcf_bc_datePicker.destroy(element);
break;
case 'getDate':
return window.__wcf_bc_datePicker.getDate(element);
break;
case 'option':
if (parameters[0] === 'onClose') {
return function() {};
}
console.warn("datepicker('option') supports only 'onClose'.");
break;
case 'setDate':
window.__wcf_bc_datePicker.setDate(element, parameters[0]);
break;
case 'setOption':
if (parameters[0] === 'onClose') {
window.__wcf_bc_datePicker.setCloseCallback(element, parameters[1]);
}
else {
console.warn("datepicker('setOption') supports only 'onClose'.");
}
break;
default:
console.debug("Unsupported method '" + method + "' for datepicker()");
break;
}
return this;
}
});
jQuery.fn.extend({
wcfTabs: function(method) {
var element = this[0], parameters = Array.prototype.slice.call(arguments, 1);
require(['Dom/Util', 'WoltLabSuite/Core/Ui/TabMenu'], function(DomUtil, TabMenu) {
var container = TabMenu.getTabMenu(DomUtil.identify(element));
if (container !== null) {
container[method].apply(container, parameters);
}
});
}
});
/**
* jQuery widget implementation of the wcf pagination.
*
* @deprecated 3.0 - use `WoltLabSuite/Core/Ui/Pagination` instead
*/
$.widget('ui.wcfPages', {
_api: null,
SHOW_LINKS: 11,
SHOW_SUB_LINKS: 20,
options: {
// vars
activePage: 1,
maxPage: 1
},
/**
* Creates the pages widget.
*/
_create: function() {
require(['WoltLabSuite/Core/Ui/Pagination'], (function(UiPagination) {
this._api = new UiPagination(this.element[0], {
activePage: this.options.activePage,
maxPage: this.options.maxPage,
callbackShouldSwitch: (function(pageNo) {
var result = this._trigger('shouldSwitch', undefined, {
nextPage: pageNo
});
return (result !== false);
}).bind(this),
callbackSwitch: (function(pageNo) {
this._trigger('switched', undefined, {
activePage: pageNo
});
}).bind(this)
});
}).bind(this));
},
/**
* Destroys the pages widget.
*/
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments);
this._api = null;
this.element[0].innerHTML = '';
},
/**
* Sets the given option to the given value.
* See the jQuery UI widget documentation for more.
*/
_setOption: function(key, value) {
if (key == 'activePage') {
if (value != this.options[key] && value > 0 && value <= this.options.maxPage) {
// you can prevent the page switching by returning false or by event.preventDefault()
// in a shouldSwitch-callback. e.g. if an AJAX request is already running.
var $result = this._trigger('shouldSwitch', undefined, {
nextPage: value
});
if ($result || $result !== undefined) {
this._api.switchPage(value);
}
else {
this._trigger('notSwitched', undefined, {
activePage: value
});
}
}
}
return this;
}
});
/**
* Namespace for category related classes.
*/
WCF.Category = { };
/**
* Handles selection of categories.
*/
WCF.Category.NestedList = Class.extend({
/**
* list of categories
* @var object
*/
_categories: { },
/**
* Initializes the WCF.Category.NestedList object.
*/
init: function() {
var self = this;
$('.jsCategory').each(function(index, category) {
var $category = $(category).data('parentCategoryID', null).change($.proxy(self._updateSelection, self));
self._categories[$category.val()] = $category;
// find child categories
var $childCategoryIDs = [ ];
$category.parents('li').find('.jsChildCategory').each(function(innerIndex, childCategory) {
var $childCategory = $(childCategory).data('parentCategoryID', $category.val()).change($.proxy(self._updateSelection, self));
self._categories[$childCategory.val()] = $childCategory;
$childCategoryIDs.push($childCategory.val());
if ($childCategory.is(':checked')) {
$category.prop('checked', 'checked');
}
});
$category.data('childCategoryIDs', $childCategoryIDs);
});
},
/**
* Updates selection of categories.
*
* @param object event
*/
_updateSelection: function(event) {
var $category = $(event.currentTarget);
var $parentCategoryID = $category.data('parentCategoryID');
if ($category.is(':checked')) {
// child category
if ($parentCategoryID !== null) {
// mark parent category as checked
this._categories[$parentCategoryID].prop('checked', 'checked');
}
}
else {
// top-level category
if ($parentCategoryID === null) {
// unmark all child categories
var $childCategoryIDs = $category.data('childCategoryIDs');
for (var $i = 0, $length = $childCategoryIDs.length; $i < $length; $i++) {
this._categories[$childCategoryIDs[$i]].prop('checked', false);
}
}
}
}
});
/**
* Handles selection of categories.
*/
WCF.Category.FlexibleCategoryList = Class.extend({
/**
* category list container
* @var jQuery
*/
_list: null,
/**
* list of children per category id
* @var object<integer>
*/
_categories: { },
init: function(elementID) {
this._list = $('#' + elementID);
this._buildStructure();
this._list.find('input:checked').each(function() {
$(this).trigger('change');
});
if (this._list.children('li').length < 2) {
this._list.addClass('flexibleCategoryListDisabled');
return;
}
},
_buildStructure: function() {
var self = this;
this._list.find('.jsCategory').each(function(i, category) {
var $category = $(category).change(self._updateSelection.bind(self));
var $categoryID = parseInt($category.val());
var $childCategories = [ ];
$category.parents('li:eq(0)').find('.jsChildCategory').each(function(j, childCategory) {
var $childCategory = $(childCategory);
$childCategory.data('parentCategory', $category).change(self._updateSelection.bind(self));
var $childCategoryID = parseInt($childCategory.val());
$childCategories.push($childCategory);
var $subChildCategories = [ ];
$childCategory.parents('li:eq(0)').find('.jsSubChildCategory').each(function(k, subChildCategory) {
var $subChildCategory = $(subChildCategory);
$subChildCategory.data('parentCategory', $childCategory).change(self._updateSelection.bind(self));
$subChildCategories.push($subChildCategory);
});
self._categories[$childCategoryID] = $subChildCategories;
});
self._categories[$categoryID] = $childCategories;
});
},
_updateSelection: function(event) {
var $category = $(event.currentTarget);
var $categoryID = parseInt($category.val());
var $parentCategory = $category.data('parentCategory');
if ($category.is(':checked')) {
if ($parentCategory) {
$parentCategory.prop('checked', 'checked');
$parentCategory = $parentCategory.data('parentCategory');
if ($parentCategory) {
$parentCategory.prop('checked', 'checked');
}
}
}
else {
// uncheck child categories
if (this._categories[$categoryID]) {
for (var $i = 0, $length = this._categories[$categoryID].length; $i < $length; $i++) {
var $childCategory = this._categories[$categoryID][$i];
$childCategory.prop('checked', false);
var $childCategoryID = parseInt($childCategory.val());
if (this._categories[$childCategoryID]) {
for (var $j = 0, $innerLength = this._categories[$childCategoryID].length; $j < $innerLength; $j++) {
this._categories[$childCategoryID][$j].prop('checked', false);
}
}
}
}
// uncheck direct parent if it has no more checked children
if ($parentCategory) {
var $parentCategoryID = parseInt($parentCategory.val());
for (var $i = 0, $length = this._categories[$parentCategoryID].length; $i < $length; $i++) {
if (this._categories[$parentCategoryID][$i].prop('checked')) {
// at least one child is checked, break
return;
}
}
$parentCategory = $parentCategory.data('parentCategory');
if ($parentCategory) {
$parentCategoryID = parseInt($parentCategory.val());
for (var $i = 0, $length = this._categories[$parentCategoryID].length; $i < $length; $i++) {
if (this._categories[$parentCategoryID][$i].prop('checked')) {
// at least one child is checked, break
return;
}
}
}
}
}
}
});
/**
* Initializes WCF.Condition namespace.
*/
WCF.Condition = { };
/**
* Initialize WCF.Notice namespace.
*/
WCF.Notice = { };
/**
* Encapsulate eval() within an own function to prevent problems
* with optimizing and minifiny JS.
*
* @param mixed expression
* @returns mixed
*/
function wcfEval(expression) {
return eval(expression);
}
| Fixed interactive dropdown collapsing on scroll
| wcfsetup/install/files/js/WCF.js | Fixed interactive dropdown collapsing on scroll | <ide><path>cfsetup/install/files/js/WCF.js
<ide> if (this._dropdownContainer === null) {
<ide> this._dropdownContainer = $('<div class="dropdownMenuContainer" />').appendTo(document.body);
<ide> WCF.CloseOverlayHandler.addCallback('WCF.Dropdown.Interactive.Handler', $.proxy(this.closeAll, this));
<del> window.addEventListener('scroll', this.closeAll.bind(this));
<add>
<add> window.addEventListener('scroll', (function (event) {
<add> if (!document.documentElement.classList.contains('pageOverlayActive')) {
<add> this.closeAll.bind(this)
<add> }
<add> }).bind(this));
<ide> }
<ide>
<ide> var $instance = new WCF.Dropdown.Interactive.Instance(this._dropdownContainer, triggerElement, identifier, options); |
|
Java | apache-2.0 | 2892f6cc4ad88a670ae665a2d82e413162e88156 | 0 | saidmrn/cw-android,atishagrawal/cw-android,HiWong/cw-android,atishagrawal/cw-android,commonsguy/cw-android,HiWong/cw-android,commonsguy/cw-android,saidmrn/cw-android,HiWong/cw-android,saidmrn/cw-android,atishagrawal/cw-android | /***
Copyright (c) 2008-2011 CommonsWare, 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.
*/
package com.commonsware.android.grid;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
public class GridDemo extends Activity
implements AdapterView.OnItemClickListener {
private TextView selection;
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);
GridView g=(GridView) findViewById(R.id.grid);
g.setAdapter(new ArrayAdapter<String>(this,
R.layout.cell,
items));
g.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
selection.setText(items[position]);
}
} | Selection/Grid/src/com/commonsware/android/grid/GridDemo.java | /***
Copyright (c) 2008-2011 CommonsWare, 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.
*/
package com.commonsware.android.grid;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
public class GridDemo extends Activity
implements AdapterView.OnItemSelectedListener {
private TextView selection;
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);
GridView g=(GridView) findViewById(R.id.grid);
g.setAdapter(new ArrayAdapter<String>(this,
R.layout.cell,
items));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
selection.setText(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
} | switched to OnItemClickListener
| Selection/Grid/src/com/commonsware/android/grid/GridDemo.java | switched to OnItemClickListener | <ide><path>election/Grid/src/com/commonsware/android/grid/GridDemo.java
<ide> import android.widget.TextView;
<ide>
<ide> public class GridDemo extends Activity
<del> implements AdapterView.OnItemSelectedListener {
<add> implements AdapterView.OnItemClickListener {
<ide> private TextView selection;
<ide> private static final String[] items={"lorem", "ipsum", "dolor",
<ide> "sit", "amet",
<ide> g.setAdapter(new ArrayAdapter<String>(this,
<ide> R.layout.cell,
<ide> items));
<del> g.setOnItemSelectedListener(this);
<add> g.setOnItemClickListener(this);
<ide> }
<ide>
<del> public void onItemSelected(AdapterView<?> parent, View v,
<add> public void onItemClick(AdapterView<?> parent, View v,
<ide> int position, long id) {
<ide> selection.setText(items[position]);
<ide> }
<del>
<del> public void onNothingSelected(AdapterView<?> parent) {
<del> selection.setText("");
<del> }
<ide> } |
|
Java | apache-2.0 | 1373a9ff23ef7e1c96ea901682f7d3fc7ba41a7f | 0 | shixuan-fan/presto,arhimondr/presto,twitter-forks/presto,mvp/presto,twitter-forks/presto,prestodb/presto,twitter-forks/presto,arhimondr/presto,prestodb/presto,zzhao0/presto,prestodb/presto,zzhao0/presto,facebook/presto,arhimondr/presto,mvp/presto,mvp/presto,ptkool/presto,shixuan-fan/presto,EvilMcJerkface/presto,prestodb/presto,facebook/presto,EvilMcJerkface/presto,arhimondr/presto,twitter-forks/presto,facebook/presto,facebook/presto,ptkool/presto,twitter-forks/presto,prestodb/presto,shixuan-fan/presto,zzhao0/presto,EvilMcJerkface/presto,ptkool/presto,prestodb/presto,facebook/presto,arhimondr/presto,zzhao0/presto,EvilMcJerkface/presto,zzhao0/presto,mvp/presto,mvp/presto,shixuan-fan/presto,ptkool/presto,ptkool/presto,EvilMcJerkface/presto,shixuan-fan/presto | /*
* 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.
*/
package com.facebook.presto.orc.reader;
import com.facebook.presto.memory.context.LocalMemoryContext;
import com.facebook.presto.orc.OrcCorruptionException;
import com.facebook.presto.orc.StreamDescriptor;
import com.facebook.presto.orc.TupleDomainFilter;
import com.facebook.presto.orc.metadata.ColumnEncoding;
import com.facebook.presto.orc.metadata.OrcType;
import com.facebook.presto.orc.stream.BooleanInputStream;
import com.facebook.presto.orc.stream.ByteArrayInputStream;
import com.facebook.presto.orc.stream.InputStreamSource;
import com.facebook.presto.orc.stream.InputStreamSources;
import com.facebook.presto.orc.stream.LongInputStream;
import com.facebook.presto.orc.stream.RowGroupDictionaryLengthInputStream;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockLease;
import com.facebook.presto.spi.block.ClosingBlockLease;
import com.facebook.presto.spi.block.DictionaryBlock;
import com.facebook.presto.spi.block.RunLengthEncodedBlock;
import com.facebook.presto.spi.block.VariableWidthBlock;
import com.facebook.presto.spi.type.Chars;
import com.facebook.presto.spi.type.Type;
import io.airlift.slice.Slice;
import org.openjdk.jol.info.ClassLayout;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static com.facebook.presto.array.Arrays.ensureCapacity;
import static com.facebook.presto.orc.metadata.OrcType.OrcTypeKind.CHAR;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.DATA;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.DICTIONARY_DATA;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.IN_DICTIONARY;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.LENGTH;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.PRESENT;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.ROW_GROUP_DICTIONARY;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.ROW_GROUP_DICTIONARY_LENGTH;
import static com.facebook.presto.orc.reader.SliceSelectiveStreamReader.computeTruncatedLength;
import static com.facebook.presto.orc.stream.MissingInputStreamSource.missingStreamSource;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static io.airlift.slice.SizeOf.sizeOf;
import static io.airlift.slice.Slices.wrappedBuffer;
import static java.lang.Math.toIntExact;
import static java.util.Arrays.fill;
import static java.util.Objects.requireNonNull;
public class SliceDictionarySelectiveReader
implements SelectiveStreamReader
{
private static final int INSTANCE_SIZE = ClassLayout.parseClass(SliceDictionarySelectiveReader.class).instanceSize();
// filter evaluation states, using byte constants instead of enum as its memory efficient
private static final byte FILTER_NOT_EVALUATED = 0;
private static final byte FILTER_PASSED = 1;
private static final byte FILTER_FAILED = 2;
private static final byte[] EMPTY_DICTIONARY_DATA = new byte[0];
// add one extra entry for null after stripe/rowGroup dictionary
private static final int[] EMPTY_DICTIONARY_OFFSETS = new int[2];
private final TupleDomainFilter filter;
private final boolean nonDeterministicFilter;
private final boolean nullsAllowed;
private final Type outputType;
private final boolean outputRequired;
private final StreamDescriptor streamDescriptor;
private final int maxCodePointCount;
private final boolean isCharType;
private byte[] stripeDictionaryData = EMPTY_DICTIONARY_DATA;
private int[] stripeDictionaryOffsetVector = EMPTY_DICTIONARY_OFFSETS;
private byte[] currentDictionaryData = EMPTY_DICTIONARY_DATA;
private int[] stripeDictionaryLength = new int[0];
private int[] rowGroupDictionaryLength = new int[0];
private byte[] evaluationStatus;
private int readOffset;
private VariableWidthBlock dictionary = new VariableWidthBlock(1, wrappedBuffer(EMPTY_DICTIONARY_DATA), EMPTY_DICTIONARY_OFFSETS, Optional.of(new boolean[] {true}));
private InputStreamSource<BooleanInputStream> presentStreamSource = missingStreamSource(BooleanInputStream.class);
private BooleanInputStream presentStream;
private BooleanInputStream inDictionaryStream;
private InputStreamSource<ByteArrayInputStream> stripeDictionaryDataStreamSource = missingStreamSource(ByteArrayInputStream.class);
private InputStreamSource<LongInputStream> stripeDictionaryLengthStreamSource = missingStreamSource(LongInputStream.class);
private boolean stripeDictionaryOpen;
private int stripeDictionarySize;
private InputStreamSource<ByteArrayInputStream> rowGroupDictionaryDataStreamSource = missingStreamSource(ByteArrayInputStream.class);
private InputStreamSource<BooleanInputStream> inDictionaryStreamSource = missingStreamSource(BooleanInputStream.class);
private InputStreamSource<RowGroupDictionaryLengthInputStream> rowGroupDictionaryLengthStreamSource = missingStreamSource(RowGroupDictionaryLengthInputStream.class);
private InputStreamSource<LongInputStream> dataStreamSource = missingStreamSource(LongInputStream.class);
private LongInputStream dataStream;
private boolean rowGroupOpen;
private LocalMemoryContext systemMemoryContext;
private int[] values;
private boolean allNulls;
private int[] outputPositions;
private int outputPositionCount;
private boolean outputPositionsReadOnly;
private boolean valuesInUse;
public SliceDictionarySelectiveReader(StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, Optional<Type> outputType, LocalMemoryContext systemMemoryContext)
{
this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null");
this.filter = requireNonNull(filter, "filter is null").orElse(null);
this.systemMemoryContext = systemMemoryContext;
this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic();
this.nullsAllowed = this.filter == null || nonDeterministicFilter || this.filter.testNull();
this.outputType = requireNonNull(outputType, "outputType is null").orElse(null);
OrcType orcType = streamDescriptor.getOrcType();
this.maxCodePointCount = orcType == null ? 0 : orcType.getLength().orElse(-1);
this.isCharType = orcType.getOrcTypeKind() == CHAR;
this.outputRequired = outputType.isPresent();
checkArgument(filter.isPresent() || outputRequired, "filter must be present if outputRequired is false");
}
@Override
public int read(int offset, int[] positions, int positionCount)
throws IOException
{
if (!rowGroupOpen) {
openRowGroup();
}
checkState(!valuesInUse, "BlockLease hasn't been closed yet");
if (outputRequired) {
values = ensureCapacity(values, positionCount);
}
if (filter != null) {
outputPositions = ensureCapacity(outputPositions, positionCount);
}
else {
outputPositions = positions;
outputPositionsReadOnly = true;
}
systemMemoryContext.setBytes(getRetainedSizeInBytes());
if (readOffset < offset) {
skip(offset - readOffset);
}
outputPositionCount = 0;
int streamPosition;
if (dataStream == null && presentStream != null) {
streamPosition = readAllNulls(positions, positionCount);
}
else if (filter == null) {
streamPosition = readNoFilter(positions, positionCount);
}
else {
streamPosition = readWithFilter(positions, positionCount);
}
readOffset = offset + streamPosition;
return outputPositionCount;
}
private int readNoFilter(int[] positions, int positionCount)
throws IOException
{
int streamPosition = 0;
for (int i = 0; i < positionCount; i++) {
int position = positions[i];
if (position > streamPosition) {
skip(position - streamPosition);
streamPosition = position;
}
if (presentStream != null && !presentStream.nextBit()) {
values[i] = dictionary.getPositionCount() - 1;
}
else {
boolean isInRowDictionary = inDictionaryStream != null && !inDictionaryStream.nextBit();
int index = toIntExact(dataStream.next());
values[i] = isInRowDictionary ? stripeDictionarySize + index : index;
}
streamPosition++;
}
outputPositionCount = positionCount;
return streamPosition;
}
private int readWithFilter(int[] positions, int positionCount)
throws IOException
{
int streamPosition = 0;
for (int i = 0; i < positionCount; i++) {
int position = positions[i];
if (position > streamPosition) {
skip(position - streamPosition);
streamPosition = position;
}
if (presentStream != null && !presentStream.nextBit()) {
if ((nonDeterministicFilter && filter.testNull()) || nullsAllowed) {
if (outputRequired) {
values[outputPositionCount] = dictionary.getPositionCount() - 1;
}
outputPositions[outputPositionCount] = position;
outputPositionCount++;
}
}
else {
boolean inRowDictionary = inDictionaryStream != null && !inDictionaryStream.nextBit();
int rawIndex = toIntExact(dataStream.next());
int index = inRowDictionary ? stripeDictionarySize + rawIndex : rawIndex;
int length;
if (isCharType) {
length = maxCodePointCount;
}
else {
length = inRowDictionary ? rowGroupDictionaryLength[rawIndex] : stripeDictionaryLength[rawIndex];
}
if (nonDeterministicFilter) {
evaluateFilter(position, index, length);
}
else {
switch (evaluationStatus[index]) {
case FILTER_FAILED: {
break;
}
case FILTER_PASSED: {
if (outputRequired) {
values[outputPositionCount] = index;
}
outputPositions[outputPositionCount] = position;
outputPositionCount++;
break;
}
case FILTER_NOT_EVALUATED: {
evaluationStatus[index] = evaluateFilter(position, index, length);
break;
}
default: {
throw new IllegalStateException("invalid evaluation state");
}
}
}
}
streamPosition++;
if (filter != null) {
outputPositionCount -= filter.getPrecedingPositionsToFail();
int succeedingPositionsToFail = filter.getSucceedingPositionsToFail();
if (succeedingPositionsToFail > 0) {
int positionsToSkip = 0;
for (int j = 0; j < succeedingPositionsToFail; j++) {
i++;
int nextPosition = positions[i];
positionsToSkip += 1 + nextPosition - streamPosition;
streamPosition = nextPosition + 1;
}
skip(positionsToSkip);
}
}
}
return streamPosition;
}
private byte evaluateFilter(int position, int index, int length)
{
if (filter.testLength(length)) {
int currentLength = dictionary.getSliceLength(index);
Slice data = dictionary.getSlice(index, 0, currentLength);
if (isCharType && length != currentLength) {
data = Chars.padSpaces(data, maxCodePointCount);
}
if (filter.testBytes(data.getBytes(), 0, length)) {
if (outputRequired) {
values[outputPositionCount] = index;
}
outputPositions[outputPositionCount] = position;
outputPositionCount++;
return FILTER_PASSED;
}
}
return FILTER_FAILED;
}
private int readAllNulls(int[] positions, int positionCount)
throws IOException
{
presentStream.skip(positions[positionCount - 1]);
if (nonDeterministicFilter) {
outputPositionCount = 0;
for (int i = 0; i < positionCount; i++) {
if (filter.testNull()) {
outputPositionCount++;
}
else {
outputPositionCount -= filter.getPrecedingPositionsToFail();
i += filter.getSucceedingPositionsToFail();
}
}
}
else if (nullsAllowed) {
outputPositionCount = positionCount;
if (filter != null) {
outputPositions = positions;
outputPositionsReadOnly = true;
}
}
else {
outputPositionCount = 0;
}
allNulls = true;
return positions[positionCount - 1] + 1;
}
private void skip(int items)
throws IOException
{
if (presentStream != null) {
int dataToSkip = presentStream.countBitsSet(items);
if (inDictionaryStream != null) {
inDictionaryStream.skip(dataToSkip);
}
if (dataStream != null) {
dataStream.skip(dataToSkip);
}
}
else {
if (inDictionaryStream != null) {
inDictionaryStream.skip(items);
}
dataStream.skip(items);
}
}
@Override
public int[] getReadPositions()
{
return outputPositions;
}
@Override
public Block getBlock(int[] positions, int positionCount)
{
checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero");
checkState(outputRequired, "This stream reader doesn't produce output");
checkState(positionCount <= outputPositionCount, "Not enough values");
checkState(!valuesInUse, "BlockLease hasn't been closed yet");
if (allNulls) {
return new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), outputPositionCount);
}
if (positionCount == outputPositionCount) {
DictionaryBlock block = new DictionaryBlock(positionCount, dictionary, values);
values = null;
return block;
}
int[] valuesCopy = new int[positionCount];
int positionIndex = 0;
int nextPosition = positions[positionIndex];
for (int i = 0; i < outputPositionCount; i++) {
if (outputPositions[i] < nextPosition) {
continue;
}
assert outputPositions[i] == nextPosition;
valuesCopy[positionIndex] = this.values[i];
positionIndex++;
if (positionIndex >= positionCount) {
break;
}
nextPosition = positions[positionIndex];
}
return new DictionaryBlock(positionCount, dictionary, valuesCopy);
}
@Override
public BlockLease getBlockView(int[] positions, int positionCount)
{
checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero");
checkState(outputRequired, "This stream reader doesn't produce output");
checkState(positionCount <= outputPositionCount, "Not enough values");
checkState(!valuesInUse, "BlockLease hasn't been closed yet");
if (allNulls) {
return newLease(new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), positionCount));
}
if (positionCount < outputPositionCount) {
compactValues(positions, positionCount);
}
return newLease(new DictionaryBlock(positionCount, dictionary, values));
}
private void compactValues(int[] positions, int positionCount)
{
if (outputPositionsReadOnly) {
outputPositions = Arrays.copyOf(outputPositions, outputPositionCount);
outputPositionsReadOnly = false;
}
int positionIndex = 0;
int nextPosition = positions[positionIndex];
for (int i = 0; i < outputPositionCount; i++) {
if (outputPositions[i] < nextPosition) {
continue;
}
assert outputPositions[i] == nextPosition;
values[positionIndex] = values[i];
outputPositions[positionIndex] = nextPosition;
positionIndex++;
if (positionIndex >= positionCount) {
break;
}
nextPosition = positions[positionIndex];
}
outputPositionCount = positionCount;
}
@Override
public void throwAnyError(int[] positions, int positionCount)
{
}
private void openRowGroup()
throws IOException
{
// read the dictionary
if (!stripeDictionaryOpen) {
if (stripeDictionarySize > 0) {
// resize the dictionary lengths array if necessary
if (stripeDictionaryLength.length < stripeDictionarySize) {
stripeDictionaryLength = new int[stripeDictionarySize];
}
// read the lengths
LongInputStream lengthStream = stripeDictionaryLengthStreamSource.openStream();
if (lengthStream == null) {
throw new OrcCorruptionException(streamDescriptor.getOrcDataSourceId(), "Dictionary is not empty but dictionary length stream is not present");
}
lengthStream.nextIntVector(stripeDictionarySize, stripeDictionaryLength, 0);
long dataLength = 0;
for (int i = 0; i < stripeDictionarySize; i++) {
dataLength += stripeDictionaryLength[i];
}
// we must always create a new dictionary array because the previous dictionary may still be referenced
stripeDictionaryData = new byte[toIntExact(dataLength)];
// add one extra entry for null
stripeDictionaryOffsetVector = new int[stripeDictionarySize + 2];
// read dictionary values
ByteArrayInputStream dictionaryDataStream = stripeDictionaryDataStreamSource.openStream();
readDictionary(dictionaryDataStream, stripeDictionarySize, stripeDictionaryLength, 0, stripeDictionaryData, stripeDictionaryOffsetVector, maxCodePointCount, isCharType);
}
else {
stripeDictionaryData = EMPTY_DICTIONARY_DATA;
stripeDictionaryOffsetVector = EMPTY_DICTIONARY_OFFSETS;
}
}
stripeDictionaryOpen = true;
// read row group dictionary
RowGroupDictionaryLengthInputStream dictionaryLengthStream = rowGroupDictionaryLengthStreamSource.openStream();
if (dictionaryLengthStream != null) {
int rowGroupDictionarySize = dictionaryLengthStream.getEntryCount();
// resize the dictionary lengths array if necessary
if (rowGroupDictionaryLength.length < rowGroupDictionarySize) {
rowGroupDictionaryLength = new int[rowGroupDictionarySize];
}
// read the lengths
dictionaryLengthStream.nextIntVector(rowGroupDictionarySize, rowGroupDictionaryLength, 0);
long dataLength = 0;
for (int i = 0; i < rowGroupDictionarySize; i++) {
dataLength += rowGroupDictionaryLength[i];
}
// We must always create a new dictionary array because the previous dictionary may still be referenced
// The first elements of the dictionary are from the stripe dictionary, then the row group dictionary elements, and then a null
byte[] rowGroupDictionaryData = java.util.Arrays.copyOf(stripeDictionaryData, stripeDictionaryOffsetVector[stripeDictionarySize] + toIntExact(dataLength));
int[] rowGroupDictionaryOffsetVector = Arrays.copyOf(stripeDictionaryOffsetVector, stripeDictionarySize + rowGroupDictionarySize + 2);
// read dictionary values
ByteArrayInputStream dictionaryDataStream = rowGroupDictionaryDataStreamSource.openStream();
readDictionary(dictionaryDataStream, rowGroupDictionarySize, rowGroupDictionaryLength, stripeDictionarySize, rowGroupDictionaryData, rowGroupDictionaryOffsetVector, maxCodePointCount, isCharType);
setDictionaryBlockData(rowGroupDictionaryData, rowGroupDictionaryOffsetVector, stripeDictionarySize + rowGroupDictionarySize + 1);
}
else {
// there is no row group dictionary so use the stripe dictionary
setDictionaryBlockData(stripeDictionaryData, stripeDictionaryOffsetVector, stripeDictionarySize + 1);
}
presentStream = presentStreamSource.openStream();
inDictionaryStream = inDictionaryStreamSource.openStream();
dataStream = dataStreamSource.openStream();
rowGroupOpen = true;
}
// Reads dictionary into data and offsetVector
private static void readDictionary(
@Nullable ByteArrayInputStream dictionaryDataStream,
int dictionarySize,
int[] dictionaryLengthVector,
int offsetVectorOffset,
byte[] data,
int[] offsetVector,
int maxCodePointCount,
boolean isCharType)
throws IOException
{
Slice slice = wrappedBuffer(data);
// initialize the offset if necessary;
// otherwise, use the previous offset
if (offsetVectorOffset == 0) {
offsetVector[0] = 0;
}
// truncate string and update offsets
for (int i = 0; i < dictionarySize; i++) {
int offsetIndex = offsetVectorOffset + i;
int offset = offsetVector[offsetIndex];
int length = dictionaryLengthVector[i];
int truncatedLength;
if (length > 0) {
// read data without truncation
dictionaryDataStream.next(data, offset, offset + length);
// adjust offsets with truncated length
truncatedLength = computeTruncatedLength(slice, offset, length, maxCodePointCount, isCharType);
verify(truncatedLength >= 0);
}
else {
truncatedLength = 0;
}
offsetVector[offsetIndex + 1] = offsetVector[offsetIndex] + truncatedLength;
}
}
@Override
public void startStripe(InputStreamSources dictionaryStreamSources, List<ColumnEncoding> encoding)
{
stripeDictionaryDataStreamSource = dictionaryStreamSources.getInputStreamSource(streamDescriptor, DICTIONARY_DATA, ByteArrayInputStream.class);
stripeDictionaryLengthStreamSource = dictionaryStreamSources.getInputStreamSource(streamDescriptor, LENGTH, LongInputStream.class);
stripeDictionarySize = encoding.get(streamDescriptor.getStreamId())
.getColumnEncoding(streamDescriptor.getSequence())
.getDictionarySize();
stripeDictionaryOpen = false;
presentStreamSource = missingStreamSource(BooleanInputStream.class);
dataStreamSource = missingStreamSource(LongInputStream.class);
inDictionaryStreamSource = missingStreamSource(BooleanInputStream.class);
rowGroupDictionaryLengthStreamSource = missingStreamSource(RowGroupDictionaryLengthInputStream.class);
rowGroupDictionaryDataStreamSource = missingStreamSource(ByteArrayInputStream.class);
readOffset = 0;
presentStream = null;
inDictionaryStream = null;
dataStream = null;
rowGroupOpen = false;
}
@Override
public void startRowGroup(InputStreamSources dataStreamSources)
{
presentStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, PRESENT, BooleanInputStream.class);
dataStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, DATA, LongInputStream.class);
// the "in dictionary" stream signals if the value is in the stripe or row group dictionary
inDictionaryStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, IN_DICTIONARY, BooleanInputStream.class);
rowGroupDictionaryLengthStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, ROW_GROUP_DICTIONARY_LENGTH, RowGroupDictionaryLengthInputStream.class);
rowGroupDictionaryDataStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, ROW_GROUP_DICTIONARY, ByteArrayInputStream.class);
readOffset = 0;
presentStream = null;
inDictionaryStream = null;
dataStream = null;
rowGroupOpen = false;
}
@Override
public void close()
{
systemMemoryContext.close();
}
@Override
public long getRetainedSizeInBytes()
{
return INSTANCE_SIZE + sizeOf(currentDictionaryData) + sizeOf(values) + sizeOf(outputPositions);
}
private void setDictionaryBlockData(byte[] dictionaryData, int[] dictionaryOffsets, int positionCount)
{
verify(positionCount > 0);
// only update the block if the array changed to prevent creation of new Block objects, since
// the engine currently uses identity equality to test if dictionaries are the same
if (currentDictionaryData != dictionaryData) {
boolean[] isNullVector = new boolean[positionCount];
isNullVector[positionCount - 1] = true;
dictionaryOffsets[positionCount] = dictionaryOffsets[positionCount - 1];
dictionary = new VariableWidthBlock(positionCount, wrappedBuffer(dictionaryData), dictionaryOffsets, Optional.of(isNullVector));
currentDictionaryData = dictionaryData;
evaluationStatus = ensureCapacity(evaluationStatus, positionCount - 1);
fill(evaluationStatus, 0, evaluationStatus.length, FILTER_NOT_EVALUATED);
}
}
private BlockLease newLease(Block block)
{
valuesInUse = true;
return ClosingBlockLease.newLease(block, () -> valuesInUse = false);
}
}
| presto-orc/src/main/java/com/facebook/presto/orc/reader/SliceDictionarySelectiveReader.java | /*
* 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.
*/
package com.facebook.presto.orc.reader;
import com.facebook.presto.memory.context.LocalMemoryContext;
import com.facebook.presto.orc.OrcCorruptionException;
import com.facebook.presto.orc.StreamDescriptor;
import com.facebook.presto.orc.TupleDomainFilter;
import com.facebook.presto.orc.metadata.ColumnEncoding;
import com.facebook.presto.orc.metadata.OrcType;
import com.facebook.presto.orc.stream.BooleanInputStream;
import com.facebook.presto.orc.stream.ByteArrayInputStream;
import com.facebook.presto.orc.stream.InputStreamSource;
import com.facebook.presto.orc.stream.InputStreamSources;
import com.facebook.presto.orc.stream.LongInputStream;
import com.facebook.presto.orc.stream.RowGroupDictionaryLengthInputStream;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockLease;
import com.facebook.presto.spi.block.ClosingBlockLease;
import com.facebook.presto.spi.block.DictionaryBlock;
import com.facebook.presto.spi.block.RunLengthEncodedBlock;
import com.facebook.presto.spi.block.VariableWidthBlock;
import com.facebook.presto.spi.type.Chars;
import com.facebook.presto.spi.type.Type;
import io.airlift.slice.Slice;
import org.openjdk.jol.info.ClassLayout;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static com.facebook.presto.array.Arrays.ensureCapacity;
import static com.facebook.presto.orc.metadata.OrcType.OrcTypeKind.CHAR;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.DATA;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.DICTIONARY_DATA;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.IN_DICTIONARY;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.LENGTH;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.PRESENT;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.ROW_GROUP_DICTIONARY;
import static com.facebook.presto.orc.metadata.Stream.StreamKind.ROW_GROUP_DICTIONARY_LENGTH;
import static com.facebook.presto.orc.reader.SliceSelectiveStreamReader.computeTruncatedLength;
import static com.facebook.presto.orc.stream.MissingInputStreamSource.missingStreamSource;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static io.airlift.slice.SizeOf.sizeOf;
import static io.airlift.slice.Slices.wrappedBuffer;
import static java.lang.Math.toIntExact;
import static java.util.Arrays.fill;
import static java.util.Objects.requireNonNull;
public class SliceDictionarySelectiveReader
implements SelectiveStreamReader
{
private static final int INSTANCE_SIZE = ClassLayout.parseClass(SliceDictionarySelectiveReader.class).instanceSize();
// filter evaluation states, using byte constants instead of enum as its memory efficient
private static final byte FILTER_NOT_EVALUATED = 0;
private static final byte FILTER_PASSED = 1;
private static final byte FILTER_FAILED = 2;
private static final byte[] EMPTY_DICTIONARY_DATA = new byte[0];
// add one extra entry for null after stripe/rowGroup dictionary
private static final int[] EMPTY_DICTIONARY_OFFSETS = new int[2];
private final TupleDomainFilter filter;
private final boolean nonDeterministicFilter;
private final boolean nullsAllowed;
private final Type outputType;
private final boolean outputRequired;
private final StreamDescriptor streamDescriptor;
private final int maxCodePointCount;
private final boolean isCharType;
private byte[] stripeDictionaryData = EMPTY_DICTIONARY_DATA;
private int[] stripeDictionaryOffsetVector = EMPTY_DICTIONARY_OFFSETS;
private byte[] currentDictionaryData = EMPTY_DICTIONARY_DATA;
private int[] stripeDictionaryLength = new int[0];
private int[] rowGroupDictionaryLength = new int[0];
private byte[] evaluationStatus;
private int readOffset;
private VariableWidthBlock dictionary = new VariableWidthBlock(1, wrappedBuffer(EMPTY_DICTIONARY_DATA), EMPTY_DICTIONARY_OFFSETS, Optional.of(new boolean[] {true}));
private InputStreamSource<BooleanInputStream> presentStreamSource = missingStreamSource(BooleanInputStream.class);
private BooleanInputStream presentStream;
private BooleanInputStream inDictionaryStream;
private InputStreamSource<ByteArrayInputStream> stripeDictionaryDataStreamSource = missingStreamSource(ByteArrayInputStream.class);
private InputStreamSource<LongInputStream> stripeDictionaryLengthStreamSource = missingStreamSource(LongInputStream.class);
private boolean stripeDictionaryOpen;
private int stripeDictionarySize;
private InputStreamSource<ByteArrayInputStream> rowGroupDictionaryDataStreamSource = missingStreamSource(ByteArrayInputStream.class);
private InputStreamSource<BooleanInputStream> inDictionaryStreamSource = missingStreamSource(BooleanInputStream.class);
private InputStreamSource<RowGroupDictionaryLengthInputStream> rowGroupDictionaryLengthStreamSource = missingStreamSource(RowGroupDictionaryLengthInputStream.class);
private InputStreamSource<LongInputStream> dataStreamSource = missingStreamSource(LongInputStream.class);
private LongInputStream dataStream;
private boolean rowGroupOpen;
private LocalMemoryContext systemMemoryContext;
private int[] values;
private boolean allNulls;
private int[] outputPositions;
private int outputPositionCount;
private boolean outputPositionsReadOnly;
private boolean valuesInUse;
public SliceDictionarySelectiveReader(StreamDescriptor streamDescriptor, Optional<TupleDomainFilter> filter, Optional<Type> outputType, LocalMemoryContext systemMemoryContext)
{
this.streamDescriptor = requireNonNull(streamDescriptor, "streamDescriptor is null");
this.filter = requireNonNull(filter, "filter is null").orElse(null);
this.systemMemoryContext = systemMemoryContext;
this.nonDeterministicFilter = this.filter != null && !this.filter.isDeterministic();
this.nullsAllowed = this.filter == null || nonDeterministicFilter || this.filter.testNull();
this.outputType = requireNonNull(outputType, "outputType is null").orElse(null);
OrcType orcType = streamDescriptor.getOrcType();
this.maxCodePointCount = orcType == null ? 0 : orcType.getLength().orElse(-1);
this.isCharType = orcType.getOrcTypeKind() == CHAR;
this.outputRequired = outputType.isPresent();
checkArgument(filter.isPresent() || outputRequired, "filter must be present if outputRequired is false");
}
@Override
public int read(int offset, int[] positions, int positionCount)
throws IOException
{
if (!rowGroupOpen) {
openRowGroup();
}
checkState(!valuesInUse, "BlockLease hasn't been closed yet");
if (outputRequired) {
values = ensureCapacity(values, positionCount);
}
if (filter != null) {
outputPositions = ensureCapacity(outputPositions, positionCount);
}
else {
outputPositions = positions;
outputPositionsReadOnly = true;
}
systemMemoryContext.setBytes(getRetainedSizeInBytes());
if (readOffset < offset) {
skip(offset - readOffset);
}
outputPositionCount = 0;
int streamPosition;
if (dataStream == null && presentStream != null) {
streamPosition = readAllNulls(positions, positionCount);
}
else if (filter == null) {
streamPosition = readNoFilter(positions, positionCount);
}
else {
streamPosition = readWithFilter(positions, positionCount);
}
readOffset = offset + streamPosition;
return outputPositionCount;
}
private int readNoFilter(int[] positions, int positionCount)
throws IOException
{
int streamPosition = 0;
for (int i = 0; i < positionCount; i++) {
int position = positions[i];
if (position > streamPosition) {
skip(position - streamPosition);
streamPosition = position;
}
if (presentStream != null && !presentStream.nextBit()) {
values[i] = dictionary.getPositionCount() - 1;
}
else {
boolean isInRowDictionary = inDictionaryStream != null && !inDictionaryStream.nextBit();
int index = toIntExact(dataStream.next());
values[i] = isInRowDictionary ? stripeDictionarySize + index : index;
}
streamPosition++;
}
outputPositionCount = positionCount;
return streamPosition;
}
private int readWithFilter(int[] positions, int positionCount)
throws IOException
{
int streamPosition = 0;
for (int i = 0; i < positionCount; i++) {
int position = positions[i];
if (position > streamPosition) {
skip(position - streamPosition);
streamPosition = position;
}
if (presentStream != null && !presentStream.nextBit()) {
if ((nonDeterministicFilter && filter.testNull()) || nullsAllowed) {
if (outputRequired) {
values[outputPositionCount] = dictionary.getPositionCount() - 1;
}
outputPositions[outputPositionCount] = position;
outputPositionCount++;
}
}
else {
boolean inRowDictionary = inDictionaryStream != null && !inDictionaryStream.nextBit();
int rawIndex = toIntExact(dataStream.next());
int index = inRowDictionary ? stripeDictionarySize + rawIndex : rawIndex;
int length;
if (isCharType) {
length = maxCodePointCount;
}
else {
length = inRowDictionary ? rowGroupDictionaryLength[rawIndex] : stripeDictionaryLength[rawIndex];
}
if (nonDeterministicFilter) {
evaluateFilter(position, index, length);
}
else {
switch (evaluationStatus[index]) {
case FILTER_FAILED: {
break;
}
case FILTER_PASSED: {
if (outputRequired) {
values[outputPositionCount] = index;
}
outputPositions[outputPositionCount] = position;
outputPositionCount++;
break;
}
case FILTER_NOT_EVALUATED: {
evaluationStatus[index] = evaluateFilter(position, index, length);
break;
}
default: {
throw new IllegalStateException("invalid evaluation state");
}
}
}
}
streamPosition++;
if (filter != null) {
outputPositionCount -= filter.getPrecedingPositionsToFail();
int succeedingPositionsToFail = filter.getSucceedingPositionsToFail();
if (succeedingPositionsToFail > 0) {
int positionsToSkip = 0;
for (int j = 0; j < succeedingPositionsToFail; j++) {
i++;
int nextPosition = positions[i];
positionsToSkip += 1 + nextPosition - streamPosition;
streamPosition = nextPosition + 1;
}
skip(positionsToSkip);
}
}
}
return streamPosition;
}
private byte evaluateFilter(int position, int index, int length)
{
if (filter.testLength(length)) {
int currentLength = dictionary.getSliceLength(index);
Slice data = dictionary.getSlice(index, 0, currentLength);
if (isCharType && length != currentLength) {
data = Chars.padSpaces(data, maxCodePointCount);
}
if (filter.testBytes(data.getBytes(), 0, length)) {
if (outputRequired) {
values[outputPositionCount] = index;
}
outputPositions[outputPositionCount] = position;
outputPositionCount++;
return FILTER_PASSED;
}
}
return FILTER_FAILED;
}
private int readAllNulls(int[] positions, int positionCount)
throws IOException
{
presentStream.skip(positions[positionCount - 1]);
if (nonDeterministicFilter) {
outputPositionCount = 0;
for (int i = 0; i < positionCount; i++) {
if (filter.testNull()) {
outputPositionCount++;
}
else {
outputPositionCount -= filter.getPrecedingPositionsToFail();
i += filter.getSucceedingPositionsToFail();
}
}
}
else if (nullsAllowed) {
outputPositionCount = positionCount;
if (filter != null) {
outputPositions = positions;
outputPositionsReadOnly = true;
}
}
else {
outputPositionCount = 0;
}
allNulls = true;
return positions[positionCount - 1] + 1;
}
private void skip(int items)
throws IOException
{
if (presentStream != null) {
int dataToSkip = presentStream.countBitsSet(items);
if (inDictionaryStream != null) {
inDictionaryStream.skip(dataToSkip);
}
if (dataStream != null) {
dataStream.skip(dataToSkip);
}
}
else {
if (inDictionaryStream != null) {
inDictionaryStream.skip(items);
}
dataStream.skip(items);
}
}
@Override
public int[] getReadPositions()
{
return outputPositions;
}
@Override
public Block getBlock(int[] positions, int positionCount)
{
checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero");
checkState(outputRequired, "This stream reader doesn't produce output");
checkState(positionCount <= outputPositionCount, "Not enough values");
checkState(!valuesInUse, "BlockLease hasn't been closed yet");
if (allNulls) {
return new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), outputPositionCount);
}
if (positionCount == outputPositionCount) {
DictionaryBlock block = new DictionaryBlock(positionCount, dictionary, values);
values = null;
return block;
}
int[] valuesCopy = new int[positionCount];
int positionIndex = 0;
int nextPosition = positions[positionIndex];
for (int i = 0; i < outputPositionCount; i++) {
if (outputPositions[i] < nextPosition) {
continue;
}
assert outputPositions[i] == nextPosition;
valuesCopy[positionIndex] = this.values[i];
positionIndex++;
if (positionIndex >= positionCount) {
break;
}
nextPosition = positions[positionIndex];
}
return new DictionaryBlock(positionCount, dictionary, valuesCopy);
}
@Override
public BlockLease getBlockView(int[] positions, int positionCount)
{
checkArgument(outputPositionCount > 0, "outputPositionCount must be greater than zero");
checkState(outputRequired, "This stream reader doesn't produce output");
checkState(positionCount <= outputPositionCount, "Not enough values");
checkState(!valuesInUse, "BlockLease hasn't been closed yet");
if (positionCount < outputPositionCount) {
compactValues(positions, positionCount);
}
return newLease(new DictionaryBlock(positionCount, dictionary, values));
}
private void compactValues(int[] positions, int positionCount)
{
if (outputPositionsReadOnly) {
outputPositions = Arrays.copyOf(outputPositions, outputPositionCount);
outputPositionsReadOnly = false;
}
int positionIndex = 0;
int nextPosition = positions[positionIndex];
for (int i = 0; i < outputPositionCount; i++) {
if (outputPositions[i] < nextPosition) {
continue;
}
assert outputPositions[i] == nextPosition;
values[positionIndex] = values[i];
outputPositions[positionIndex] = nextPosition;
positionIndex++;
if (positionIndex >= positionCount) {
break;
}
nextPosition = positions[positionIndex];
}
outputPositionCount = positionCount;
}
@Override
public void throwAnyError(int[] positions, int positionCount)
{
}
private void openRowGroup()
throws IOException
{
// read the dictionary
if (!stripeDictionaryOpen) {
if (stripeDictionarySize > 0) {
// resize the dictionary lengths array if necessary
if (stripeDictionaryLength.length < stripeDictionarySize) {
stripeDictionaryLength = new int[stripeDictionarySize];
}
// read the lengths
LongInputStream lengthStream = stripeDictionaryLengthStreamSource.openStream();
if (lengthStream == null) {
throw new OrcCorruptionException(streamDescriptor.getOrcDataSourceId(), "Dictionary is not empty but dictionary length stream is not present");
}
lengthStream.nextIntVector(stripeDictionarySize, stripeDictionaryLength, 0);
long dataLength = 0;
for (int i = 0; i < stripeDictionarySize; i++) {
dataLength += stripeDictionaryLength[i];
}
// we must always create a new dictionary array because the previous dictionary may still be referenced
stripeDictionaryData = new byte[toIntExact(dataLength)];
// add one extra entry for null
stripeDictionaryOffsetVector = new int[stripeDictionarySize + 2];
// read dictionary values
ByteArrayInputStream dictionaryDataStream = stripeDictionaryDataStreamSource.openStream();
readDictionary(dictionaryDataStream, stripeDictionarySize, stripeDictionaryLength, 0, stripeDictionaryData, stripeDictionaryOffsetVector, maxCodePointCount, isCharType);
}
else {
stripeDictionaryData = EMPTY_DICTIONARY_DATA;
stripeDictionaryOffsetVector = EMPTY_DICTIONARY_OFFSETS;
}
}
stripeDictionaryOpen = true;
// read row group dictionary
RowGroupDictionaryLengthInputStream dictionaryLengthStream = rowGroupDictionaryLengthStreamSource.openStream();
if (dictionaryLengthStream != null) {
int rowGroupDictionarySize = dictionaryLengthStream.getEntryCount();
// resize the dictionary lengths array if necessary
if (rowGroupDictionaryLength.length < rowGroupDictionarySize) {
rowGroupDictionaryLength = new int[rowGroupDictionarySize];
}
// read the lengths
dictionaryLengthStream.nextIntVector(rowGroupDictionarySize, rowGroupDictionaryLength, 0);
long dataLength = 0;
for (int i = 0; i < rowGroupDictionarySize; i++) {
dataLength += rowGroupDictionaryLength[i];
}
// We must always create a new dictionary array because the previous dictionary may still be referenced
// The first elements of the dictionary are from the stripe dictionary, then the row group dictionary elements, and then a null
byte[] rowGroupDictionaryData = java.util.Arrays.copyOf(stripeDictionaryData, stripeDictionaryOffsetVector[stripeDictionarySize] + toIntExact(dataLength));
int[] rowGroupDictionaryOffsetVector = Arrays.copyOf(stripeDictionaryOffsetVector, stripeDictionarySize + rowGroupDictionarySize + 2);
// read dictionary values
ByteArrayInputStream dictionaryDataStream = rowGroupDictionaryDataStreamSource.openStream();
readDictionary(dictionaryDataStream, rowGroupDictionarySize, rowGroupDictionaryLength, stripeDictionarySize, rowGroupDictionaryData, rowGroupDictionaryOffsetVector, maxCodePointCount, isCharType);
setDictionaryBlockData(rowGroupDictionaryData, rowGroupDictionaryOffsetVector, stripeDictionarySize + rowGroupDictionarySize + 1);
}
else {
// there is no row group dictionary so use the stripe dictionary
setDictionaryBlockData(stripeDictionaryData, stripeDictionaryOffsetVector, stripeDictionarySize + 1);
}
presentStream = presentStreamSource.openStream();
inDictionaryStream = inDictionaryStreamSource.openStream();
dataStream = dataStreamSource.openStream();
rowGroupOpen = true;
}
// Reads dictionary into data and offsetVector
private static void readDictionary(
@Nullable ByteArrayInputStream dictionaryDataStream,
int dictionarySize,
int[] dictionaryLengthVector,
int offsetVectorOffset,
byte[] data,
int[] offsetVector,
int maxCodePointCount,
boolean isCharType)
throws IOException
{
Slice slice = wrappedBuffer(data);
// initialize the offset if necessary;
// otherwise, use the previous offset
if (offsetVectorOffset == 0) {
offsetVector[0] = 0;
}
// truncate string and update offsets
for (int i = 0; i < dictionarySize; i++) {
int offsetIndex = offsetVectorOffset + i;
int offset = offsetVector[offsetIndex];
int length = dictionaryLengthVector[i];
int truncatedLength;
if (length > 0) {
// read data without truncation
dictionaryDataStream.next(data, offset, offset + length);
// adjust offsets with truncated length
truncatedLength = computeTruncatedLength(slice, offset, length, maxCodePointCount, isCharType);
verify(truncatedLength >= 0);
}
else {
truncatedLength = 0;
}
offsetVector[offsetIndex + 1] = offsetVector[offsetIndex] + truncatedLength;
}
}
@Override
public void startStripe(InputStreamSources dictionaryStreamSources, List<ColumnEncoding> encoding)
{
stripeDictionaryDataStreamSource = dictionaryStreamSources.getInputStreamSource(streamDescriptor, DICTIONARY_DATA, ByteArrayInputStream.class);
stripeDictionaryLengthStreamSource = dictionaryStreamSources.getInputStreamSource(streamDescriptor, LENGTH, LongInputStream.class);
stripeDictionarySize = encoding.get(streamDescriptor.getStreamId())
.getColumnEncoding(streamDescriptor.getSequence())
.getDictionarySize();
stripeDictionaryOpen = false;
presentStreamSource = missingStreamSource(BooleanInputStream.class);
dataStreamSource = missingStreamSource(LongInputStream.class);
inDictionaryStreamSource = missingStreamSource(BooleanInputStream.class);
rowGroupDictionaryLengthStreamSource = missingStreamSource(RowGroupDictionaryLengthInputStream.class);
rowGroupDictionaryDataStreamSource = missingStreamSource(ByteArrayInputStream.class);
readOffset = 0;
presentStream = null;
inDictionaryStream = null;
dataStream = null;
rowGroupOpen = false;
}
@Override
public void startRowGroup(InputStreamSources dataStreamSources)
{
presentStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, PRESENT, BooleanInputStream.class);
dataStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, DATA, LongInputStream.class);
// the "in dictionary" stream signals if the value is in the stripe or row group dictionary
inDictionaryStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, IN_DICTIONARY, BooleanInputStream.class);
rowGroupDictionaryLengthStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, ROW_GROUP_DICTIONARY_LENGTH, RowGroupDictionaryLengthInputStream.class);
rowGroupDictionaryDataStreamSource = dataStreamSources.getInputStreamSource(streamDescriptor, ROW_GROUP_DICTIONARY, ByteArrayInputStream.class);
readOffset = 0;
presentStream = null;
inDictionaryStream = null;
dataStream = null;
rowGroupOpen = false;
}
@Override
public void close()
{
systemMemoryContext.close();
}
@Override
public long getRetainedSizeInBytes()
{
return INSTANCE_SIZE + sizeOf(currentDictionaryData) + sizeOf(values) + sizeOf(outputPositions);
}
private void setDictionaryBlockData(byte[] dictionaryData, int[] dictionaryOffsets, int positionCount)
{
verify(positionCount > 0);
// only update the block if the array changed to prevent creation of new Block objects, since
// the engine currently uses identity equality to test if dictionaries are the same
if (currentDictionaryData != dictionaryData) {
boolean[] isNullVector = new boolean[positionCount];
isNullVector[positionCount - 1] = true;
dictionaryOffsets[positionCount] = dictionaryOffsets[positionCount - 1];
dictionary = new VariableWidthBlock(positionCount, wrappedBuffer(dictionaryData), dictionaryOffsets, Optional.of(isNullVector));
currentDictionaryData = dictionaryData;
evaluationStatus = ensureCapacity(evaluationStatus, positionCount - 1);
fill(evaluationStatus, 0, evaluationStatus.length, FILTER_NOT_EVALUATED);
}
}
private BlockLease newLease(Block block)
{
valuesInUse = true;
return ClosingBlockLease.newLease(block, () -> valuesInUse = false);
}
}
| Fix getBlockView for all-null SliceDictionarySelectiveReader
| presto-orc/src/main/java/com/facebook/presto/orc/reader/SliceDictionarySelectiveReader.java | Fix getBlockView for all-null SliceDictionarySelectiveReader | <ide><path>resto-orc/src/main/java/com/facebook/presto/orc/reader/SliceDictionarySelectiveReader.java
<ide> checkState(positionCount <= outputPositionCount, "Not enough values");
<ide> checkState(!valuesInUse, "BlockLease hasn't been closed yet");
<ide>
<add> if (allNulls) {
<add> return newLease(new RunLengthEncodedBlock(outputType.createBlockBuilder(null, 1).appendNull().build(), positionCount));
<add> }
<ide> if (positionCount < outputPositionCount) {
<ide> compactValues(positions, positionCount);
<ide> } |
|
Java | mit | f420860da0c5ff59008875cef2e85a70a899f541 | 0 | tmc-cli/tmc-cli,testmycode/tmc-cli,tmc-cli/tmc-cli,testmycode/tmc-cli | package fi.helsinki.cs.tmc.cli.io;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class TerminalIoTest {
Io io = new TerminalIo();
OutputStream os;
@Before
public void setUp() {
os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
System.setOut(ps);
}
@Test
public void printWord() {
io.print("foo");
assertTrue(os.toString().equals("foo"));
}
@Test
public void printLineWithNewLine() {
io.println("foo");
assertTrue(os.toString().equals("foo\n"));
}
@Test
public void printNull() {
io.print(null);
assertTrue(os.toString().equals("null"));
}
@Test
public void printInteger() {
io.print(5);
assertTrue(os.toString().equals("5"));
}
}
| src/test/java/fi/helsinki/cs/tmc/cli/io/TerminalIoTest.java | package fi.helsinki.cs.tmc.cli.io;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
public class TerminalIoTest {
Io io = new TerminalIo();
OutputStream os;
@Before
public void setUp() {
os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
System.setOut(ps);
}
@Test
public void printlnWorksRight() {
io.println("foo");
assertTrue(os.toString().equals("foo\n"));
}
}
| Add more terminal io tests.
| src/test/java/fi/helsinki/cs/tmc/cli/io/TerminalIoTest.java | Add more terminal io tests. | <ide><path>rc/test/java/fi/helsinki/cs/tmc/cli/io/TerminalIoTest.java
<ide> }
<ide>
<ide> @Test
<del> public void printlnWorksRight() {
<add> public void printWord() {
<add> io.print("foo");
<add> assertTrue(os.toString().equals("foo"));
<add> }
<add>
<add> @Test
<add> public void printLineWithNewLine() {
<ide> io.println("foo");
<ide> assertTrue(os.toString().equals("foo\n"));
<ide> }
<add>
<add> @Test
<add> public void printNull() {
<add> io.print(null);
<add> assertTrue(os.toString().equals("null"));
<add> }
<add>
<add> @Test
<add> public void printInteger() {
<add> io.print(5);
<add> assertTrue(os.toString().equals("5"));
<add> }
<ide> } |
|
Java | apache-2.0 | 3d54efb661c556edf6e0042ee28b11a9b9611421 | 0 | First-Peoples-Cultural-Council/fv-web-ui,First-Peoples-Cultural-Council/fv-web-ui,First-Peoples-Cultural-Council/fv-web-ui,First-Peoples-Cultural-Council/fv-web-ui,First-Peoples-Cultural-Council/fv-web-ui | package ca.firstvoices.rest.services;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.Body;
import com.amazonaws.services.simpleemail.model.Content;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.Message;
import com.amazonaws.services.simpleemail.model.SendEmailRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class AmazonSESSimpleMailServiceImpl implements SimpleMailService {
private static final Log log = LogFactory.getLog(AmazonSESSimpleMailServiceImpl.class);
private final String from;
public AmazonSESSimpleMailServiceImpl(final String from) {
this.from = from;
log.info(this.toString() + " is ready!");
}
@Override
public void sendMessage(String destination, String subject, String body) {
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard().withRegion(
Regions.CA_CENTRAL_1).build();
SendEmailRequest messageRequest =
new SendEmailRequest()
.withSource(this.from)
.withMessage(new Message()
.withBody(new Body().withText(new Content().withCharset("UTF-8").withData(body)))
.withSubject(new Content().withCharset("UTF-8").withData(subject)))
.withDestination(new Destination().withToAddresses(destination));
try {
client.sendEmail(messageRequest);
} catch (Exception e) {
log.error(e);
}
}
@Override
public String toString() {
return "AmazonSESSimpleMailServiceImpl{" + "from='" + from + '\'' + '}';
}
}
| modules/api/firstvoices-rest-page-providers/src/main/java/ca/firstvoices/rest/services/AmazonSESSimpleMailServiceImpl.java | package ca.firstvoices.rest.services;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.Body;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.SendEmailRequest;
import com.amazonaws.services.simpleemail.model.Message;
import com.amazonaws.services.simpleemail.model.Content;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class AmazonSESSimpleMailServiceImpl implements SimpleMailService {
private static final Log log = LogFactory.getLog(AmazonSESSimpleMailServiceImpl.class);
private final String from;
public AmazonSESSimpleMailServiceImpl(final String from) {
this.from = from;
log.info(this.toString() + " is ready!");
}
@Override
public void sendMessage(String destination, String subject, String body) {
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard().withRegion(
Regions.CA_CENTRAL_1).build();
SendEmailRequest messageRequest =
new SendEmailRequest()
.withSource(this.from)
.withMessage(new Message()
.withBody(new Body().withText(new Content().withCharset("UTF-8").withData(body)))
.withSubject(new Content().withCharset("UTF-8").withData(subject)))
.withDestination(new Destination().withToAddresses(destination));
try {
client.sendEmail(messageRequest);
} catch (Exception e) {
log.error(e);
}
}
@Override
public String toString() {
return "AmazonSESSimpleMailServiceImpl{" + "from='" + from + '\'' + '}';
}
}
| checkstyle appeasement
| modules/api/firstvoices-rest-page-providers/src/main/java/ca/firstvoices/rest/services/AmazonSESSimpleMailServiceImpl.java | checkstyle appeasement | <ide><path>odules/api/firstvoices-rest-page-providers/src/main/java/ca/firstvoices/rest/services/AmazonSESSimpleMailServiceImpl.java
<ide> import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
<ide> import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
<ide> import com.amazonaws.services.simpleemail.model.Body;
<add>import com.amazonaws.services.simpleemail.model.Content;
<ide> import com.amazonaws.services.simpleemail.model.Destination;
<add>import com.amazonaws.services.simpleemail.model.Message;
<ide> import com.amazonaws.services.simpleemail.model.SendEmailRequest;
<del>import com.amazonaws.services.simpleemail.model.Message;
<del>import com.amazonaws.services.simpleemail.model.Content;
<ide> import org.apache.commons.logging.Log;
<del>
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> public class AmazonSESSimpleMailServiceImpl implements SimpleMailService { |
|
Java | mit | 96d15bb91bf128f4bbe9a327356048cd4372d41d | 0 | ShaneMcC/DMDirc-Client,greboid/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,greboid/DMDirc,DMDirc/DMDirc,csmith/DMDirc,DMDirc/DMDirc,csmith/DMDirc,csmith/DMDirc,csmith/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,greboid/DMDirc,DMDirc/DMDirc | /*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.
*/
package com.dmdirc.addons.logging;
import com.dmdirc.Config;
import com.dmdirc.FrameContainer;
import com.dmdirc.IconManager;
import com.dmdirc.Main;
import com.dmdirc.Server;
import com.dmdirc.ui.interfaces.Window;
import java.util.Stack;
/**
* Displays an extended history of a window.
*
* @author Chris
*/
public class HistoryWindow extends FrameContainer {
/** The title of our window. */
private final String title;
/** The server we're associated with. */
private final Server server;
/** The window we're using. */
private final Window myWindow;
/**
* Creates a new HistoryWindow.
*
* @param title The title of the window
* @param reader The reader to use to get the history
* @param server The server we're associated with
*/
public HistoryWindow(final String title, final ReverseFileReader reader, final Server server) {
super();
this.title = title;
this.server = server;
icon = IconManager.getIconManager().getIcon("raw");
myWindow = Main.getUI().getWindow(this);
myWindow.setTitle(title);
myWindow.setFrameIcon(icon);
myWindow.setVisible(true);
Main.getUI().getFrameManager().addCustom(server, this);
final Stack<String> lines = reader.getLines(Config.getOptionInt("plugin-Logging", "history.lines", 50000));
while (lines.size() > 0) {
myWindow.addLine(lines.pop(), false);
}
}
/** {@inheritDoc} */
public Window getFrame() {
return myWindow;
}
/** {@inheritDoc} */
public String toString() {
return title;
}
/** {@inheritDoc} */
public void close() {
myWindow.setVisible(false);
Main.getUI().getMainWindow().delChild(myWindow);
Main.getUI().getFrameManager().delCustom(server, this);
}
/** {@inheritDoc} */
public Server getServer() {
return server;
}
}
| src/com/dmdirc/addons/logging/HistoryWindow.java | /*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.
*/
package com.dmdirc.addons.logging;
import com.dmdirc.Config;
import com.dmdirc.FrameContainer;
import com.dmdirc.IconManager;
import com.dmdirc.Main;
import com.dmdirc.Server;
import com.dmdirc.ui.interfaces.Window;
import java.util.Stack;
/**
* Displays an extended history of a window.
*
* @author Chris
*/
public class HistoryWindow extends FrameContainer {
/** The title of our window. */
private final String title;
/** The server we're associated with. */
private final Server server;
/** The window we're using. */
private final Window myWindow;
/**
* Creates a new HistoryWindow.
*
* @param title The title of the window
* @param reader The reader to use to get the history
* @param server The server we're associated with
*/
public HistoryWindow(final String title, final ReverseFileReader reader, final Server server) {
super();
this.title = title;
this.server = server;
icon = IconManager.getIconManager().getIcon("raw");
myWindow = Main.getUI().getWindow(this);
myWindow.setTitle(title);
myWindow.setFrameIcon(icon);
myWindow.setVisible(true);
Main.getUI().getFrameManager().addCustom(server, this);
final Stack<String> lines = reader.getLines(Config.getOptionInt("plugin-Logging", "history.lines", 50000));
while (lines.size() > 0) {
myWindow.addLine(lines.pop(), false);
}
}
/** {@inheritDoc} */
public Window getFrame() {
return myWindow;
}
/** {@inheritDoc} */
public String toString() {
return title;
}
/** {@inheritDoc} */
public void close() {
myWindow.setVisible(false);
Main.getUI().getMainWindow().delChild(myWindow);
}
/** {@inheritDoc} */
public Server getServer() {
return server;
}
}
| Fix logging plugin history window not being removed from the frame manager
git-svn-id: 50f83ef66c13f323b544ac924010c921a9f4a0f7@1853 00569f92-eb28-0410-84fd-f71c24880f43
| src/com/dmdirc/addons/logging/HistoryWindow.java | Fix logging plugin history window not being removed from the frame manager | <ide><path>rc/com/dmdirc/addons/logging/HistoryWindow.java
<ide> public void close() {
<ide> myWindow.setVisible(false);
<ide> Main.getUI().getMainWindow().delChild(myWindow);
<add> Main.getUI().getFrameManager().delCustom(server, this);
<ide> }
<ide>
<ide> /** {@inheritDoc} */ |
|
Java | mit | error: pathspec 'wysi/core/src/game_objects/interactions/IScared.java' did not match any file(s) known to git
| 3cc27fab786ae32ff3baa5f2c3a57d40d4803886 | 1 | mtvarkovsky/old_48 | package game_objects.interactions;
public interface IScared {
void getScared();
}
| wysi/core/src/game_objects/interactions/IScared.java | IScared interface added
| wysi/core/src/game_objects/interactions/IScared.java | IScared interface added | <ide><path>ysi/core/src/game_objects/interactions/IScared.java
<add>package game_objects.interactions;
<add>
<add>public interface IScared {
<add> void getScared();
<add>} |
|
JavaScript | mit | afd17551202242587f0615bb062681fd1b06d83f | 0 | chromecide/flux-data-mysql | var mysql = require('mysql');
var MySQLStore = function(params, callbacks){
var self = this;
this.params = params;
if(this.params.models){
for(var key in this.params.models){
this.params.models[key].store = this;
}
}
this.connect = function(params, cbs){
if(!this.connection){
this.connection = mysql.createConnection(this.params);
}
this.connection.connect(function(err) {
if (err) {
if(cbs.error){
cbs.error(err.stack, self);
}
return;
}else{
if(cbs.success){
cbs.success(self);
}
}
});
};
this.disconnect = function(cbs){
this.connection.end();
if(cbs.success){
cbs.success();
}
};
this.save = function(records, cbs){
saveRecords(this, records, [], cbs);
};
this.read = function(model, params, cbs){
var query = objectToQuery(this, model, params);
this.connection.query(query.sql, query.values, function(err, res){
if(err){
console.log(err);
if(cbs.error){
cbs.error(err, res);
}
}else{
if(cbs.success){
cbs.success(res);
}
}
});
};
this.destroy = function(records, cbs){
removeRecords(this, records, [], cbs);
};
this.loadModelConfig = function(cbs){
var self = this;
var tableSQL = 'SHOW TABLES;';
this.connection.query({sql: tableSQL, raw: true}, function(err, res){
var modelNames = [];
for(var i=0;i<res.length;i++){
modelNames.push(res[i][Object.keys(res[i])[0]]);
}
loadAllTableData(self, modelNames, {}, {
success: function(data){
console.log(data);
//turn the data into model configurations
var modelConfigs = {};
for(var tableName in data){
modelConfigs[tableName] = {
name: tableName,
collection: tableName,
fields: {}
};
var fields = data[tableName];
for(var l=0;l<fields.length;l++){
var field = fields[l];
modelConfigs[tableName].fields[field.Field] = {};
switch(field.Type){
case 'timestamp':
case 'datetime':
modelConfigs[tableName].fields[field.Field].type='DATETIME';
break;
default:
if(field.Type.substr(0,3)=='int'){
modelConfigs[tableName].fields[field.Field].type='NUMBER';
}else{
if(field.Type.substr(0, 7)=='tinyint'){
modelConfigs[tableName].fields[field.Field].type='BOOLEAN';
}else{
console.log(field.Type);
modelConfigs[tableName].fields[field.Field].type='STRING';
}
}
break;
}
}
}
if(cbs && cbs.success){
cbs.success(modelConfigs);
}
},
error: function(err){
if(cbs && cbs.error){
cbs.error(err);
}
}
});
});
};
if(this.params.autoconnect){
this.connect(this.params, {
success: function(){
if(callbacks.success){
callbacks.success(self);
}
},
error: function(e){
if(callbacks.error){
callbacks.error(e, self);
}
}
});
}else{
if(callbacks.success){
callbacks.success(this);
}
}
};
function loadAllTableData(self, tableNames, loadedTables, cbs){
if(tableNames.length===0){
if(cbs && cbs.success){
cbs.success(loadedTables);
}
return;
}
var tableName = tableNames.shift();
loadTableData(self, tableName, {
success: function(data){
loadedTables[tableName] = data;
loadAllTableData(self, tableNames, loadedTables, cbs);
},
error: function(err){
if(cbs && cbs.error){
cbs.error(err);
}
}
});
}
function loadTableData(self, tableName, cbs){
var tableQuery = 'DESCRIBE '+tableName;
self.connection.query(tableQuery, function(err, res){
if(!err){
if(cbs && cbs.success){
cbs.success(res);
}
}else{
if(cbs && cbs.error){
cbs.error(err);
}
}
});
}
function padLeft(str, cha, len){
str = str.toString();
for(var i=0; i<len-str.length;i++){
str = cha+str;
}
return str;
}
function escapeValue(field, value){
var returnValue = '';
switch(field.type){
case 'TIMESTAMP':
returnValue = '"'+value.getUTCFullYear()+'-'+padLeft(value.getUTCMonth(), '0', 2)+'-'+padLeft(value.getUTCDate(), '0', 2)+' '+padLeft(value.getUTCHours(),'0',2)+':'+padLeft(value.getUTCMinutes(), '0', 2)+':'+value.getUTCSeconds()+'"';
break;
case 'NUMBER':
returnValue = value;
break;
case 'STRING':
returnValue = '"'+value+'"';
break;
case 'BOOLEAN':
returnValue = value?1:0;
break;
}
return returnValue;
}
function saveRecords(self, records, processedRecords, cbs){
var errors = [];
if(records.length===processedRecords.length){
if(errors.length>0){
if(cbs.error){
cbs.error(errors, records, processedRecords);
}
}else{
if(cbs.success){
cbs.success(records);
}
}
return;
}
var recordItem = records[processedRecords.length];
saveRecord(self, recordItem, {
success: function(ri){
processedRecords.push(ri);
saveRecords(self, records, processedRecords, cbs);
},
error: function(err, ri){
errors.push(err);
ri.lastError = err;
processedRecords.push(ri);
saveRecords(self, records, processedRecords, cbs);
}
});
}
function saveRecord(self, recordItem, cbs){
var saveSQL = '';
var dataValues = recordItem.dataValues;
var model = recordItem.model;
var fields = model.config.fields;
var setFields = [];
var pkField = model.config.pk_field||'id';
if(dataValues.id){ //update
saveSQL = 'UPDATE '+model.config.collection+' SET ';
for(var key in fields){
if(key!=pkField){
if(recordItem.get(key)){
console.log(key);
console.log(recordItem.get(key));
saveSQL += key+'=?,';
setFields.push(recordItem.get(key));
}
}
}
saveSQL=saveSQL.substr(0, saveSQL.length-1);//remove the last comma
saveSQL+=' WHERE '+pkField+'=?;';
setFields.push(recordItem.get(pkField));
}else{ //insert
recordItem.set('created_at', new Date());
recordItem.set('modified_at', new Date());
saveSQL = 'INSERT INTO '+model.config.collection+' (';
valueSQL = '';
for(var key in fields){
console.log(recordItem.get(key));
if(recordItem.get(key)){
saveSQL += key+',';
setFields.push(recordItem.get(key));
valueSQL+= '?,';
}
}
saveSQL = saveSQL.substr(0, saveSQL.length-1)+') VALUES ('+valueSQL.substr(0, valueSQL.length-1)+')';
}
self.connection.query(saveSQL, setFields, function(err, res){
if(err){
console.log(err);
if(cbs.error){
cbs.error(err, recordItem);
}
}else{
recordItem.set(pkField, recordItem.get(pkField) || res.insertId);
if(cbs.success){
cbs.success(recordItem);
}
}
});
}
function removeRecords(self, records, processedRecords, cbs){
console.log('REMOVING');
console.log(records);
var errors = [];
if(records.length===processedRecords.length){
if(errors.length>0){
if(cbs.error){
cbs.error(errors, records, processedRecords);
}
}else{
if(cbs.success){
cbs.success(records);
}
}
return;
}
var recordItem = records[processedRecords.length];
removeRecord(self, recordItem, {
success: function(ri){
processedRecords.push(ri);
removeRecords(self, records, processedRecords, cbs);
},
error: function(err, ri){
errors.push(err);
ri.lastError = err;
processedRecords.push(ri);
removeRecords(self, records, processedRecords, cbs);
}
});
}
function removeRecord(self, recordItem, cbs){
var model = recordItem.model;
var fields = model.config.fields;
var pkField = model.config.pk_field||'id';
var removeSQL = 'UPDATE '+model.config.collection+' SET deleted_at=?, deleted_by=? WHERE '+pkField+' = ?;';
var setFields = [new Date(), recordItem.get('deleted_by'), recordItem.get(pkField)];
self.connection.query(removeSQL, setFields, function(err, res){
if(err){
if(cbs.error){
cbs.error(err, recordItem);
}
}else{
//recordItem.set('id', res.insertId);
if(cbs.success){
cbs.success(recordItem);
}
}
});
}
function objectToQuery(self, model, queryData, cbs){
var querySQL = 'SELECT ';
var valueArray = [];
if(queryData.fields){
for(var i=0;i<queryData.fields.length;i++){
querySQL+='`'+queryData.fields[i]+'`,';
}
querySQL=querySQL.substr(0, querySQL.length-1);
}else{
querySQL+='* ';
}
querySQL+=' FROM '+model.config.collection;
if(queryData.where){
querySQL+=' WHERE ';
for(var fieldName in queryData.where){
var fieldCrit = queryData.where[fieldName];
if(fieldCrit && (typeof fieldCrit)=='object'){
for(var fieldOp in fieldCrit){
switch(fieldOp){
case 'eq':
if(fieldCrit[fieldOp].length>1){
querySQL+=fieldName+' IN (?) AND ';
valueArray.push(fieldCrit[fieldOp]);
}else{
querySQL+=fieldName+'=? AND ';
valueArray.push(fieldCrit[fieldOp][0]);
}
break;
case 'gt':
if(fieldCrit[fieldOp].length>1){
querySQL+=fieldName+' IN (?) AND ';
}else{
querySQL+=fieldName+'>? AND ';
valueArray.push(fieldCrit[fieldOp][0]);
}
break;
case 'lt':
if(fieldCrit[fieldOp].length>1){
querySQL+=fieldName+' IN (?) AND ';
}else{
querySQL+=fieldName+'<? AND ';
valueArray.push(fieldCrit[fieldOp][0]);
}
break;
}
}
}else{
if(fieldCrit===null){
querySQL+=fieldName+' IS ? AND ';
}else{
if(fieldCrit.length>1){
querySQL+=fieldName+' IN (?) AND ';
}else{
querySQL+=fieldName+'=? AND ';
}
}
valueArray.push(fieldCrit);
}
}
if(querySQL.substr(querySQL.length-5, 5)==' AND '){
querySQL = querySQL.substr(0, querySQL.length-5);
}
}
return {sql: querySQL, values: valueArray};
}
module.exports = MySQLStore; | index.js | var mysql = require('mysql');
var MySQLStore = function(params, callbacks){
var self = this;
this.params = params;
if(this.params.models){
for(var key in this.params.models){
this.params.models[key].store = this;
}
}
this.connect = function(params, cbs){
if(!this.connection){
this.connection = mysql.createConnection(this.params);
}
this.connection.connect(function(err) {
if (err) {
if(cbs.error){
cbs.error(err.stack, self);
}
return;
}else{
if(cbs.success){
cbs.success(self);
}
}
});
};
this.disconnect = function(cbs){
this.connection.end();
if(cbs.success){
cbs.success();
}
};
this.save = function(records, cbs){
saveRecords(this, records, [], cbs);
};
this.read = function(model, params, cbs){
var query = objectToQuery(this, model, params);
this.connection.query(query.sql, query.values, function(err, res){
if(err){
console.log(err);
if(cbs.error){
cbs.error(err, res);
}
}else{
if(cbs.success){
cbs.success(res);
}
}
});
};
this.destroy = function(records, cbs){
removeRecords(this, records, [], cbs);
};
this.loadModelConfig = function(cbs){
var self = this;
var tableSQL = 'SHOW TABLES;';
this.connection.query({sql: tableSQL, raw: true}, function(err, res){
var modelNames = [];
for(var i=0;i<res.length;i++){
modelNames.push(res[i][Object.keys(res[i])[0]]);
}
loadAllTableData(self, modelNames, {}, {
success: function(data){
console.log(data);
//turn the data into model configurations
var modelConfigs = {};
for(var tableName in data){
modelConfigs[tableName] = {
name: tableName,
collection: tableName,
fields: {}
};
var fields = data[tableName];
for(var l=0;l<fields.length;l++){
var field = fields[l];
modelConfigs[tableName].fields[field.Field] = {};
switch(field.Type){
case 'timestamp':
case 'datetime':
modelConfigs[tableName].fields[field.Field].type='DATETIME';
break;
default:
if(field.Type.substr(0,3)=='int'){
modelConfigs[tableName].fields[field.Field].type='NUMBER';
}else{
if(field.Type.substr(0, 7)=='tinyint'){
modelConfigs[tableName].fields[field.Field].type='BOOLEAN';
}else{
console.log(field.Type);
modelConfigs[tableName].fields[field.Field].type='STRING';
}
}
break;
}
}
}
if(cbs && cbs.success){
cbs.success(modelConfigs);
}
},
error: function(err){
if(cbs && cbs.error){
cbs.error(err);
}
}
});
});
};
if(this.params.autoconnect){
this.connect(this.params, {
success: function(){
if(callbacks.success){
callbacks.success(self);
}
},
error: function(e){
if(callbacks.error){
callbacks.error(e, self);
}
}
});
}else{
if(callbacks.success){
callbacks.success(this);
}
}
};
function loadAllTableData(self, tableNames, loadedTables, cbs){
if(tableNames.length===0){
if(cbs && cbs.success){
cbs.success(loadedTables);
}
return;
}
var tableName = tableNames.shift();
loadTableData(self, tableName, {
success: function(data){
loadedTables[tableName] = data;
loadAllTableData(self, tableNames, loadedTables, cbs);
},
error: function(err){
if(cbs && cbs.error){
cbs.error(err);
}
}
});
}
function loadTableData(self, tableName, cbs){
var tableQuery = 'DESCRIBE '+tableName;
self.connection.query(tableQuery, function(err, res){
if(!err){
if(cbs && cbs.success){
cbs.success(res);
}
}else{
if(cbs && cbs.error){
cbs.error(err);
}
}
});
}
function padLeft(str, cha, len){
str = str.toString();
for(var i=0; i<len-str.length;i++){
str = cha+str;
}
return str;
}
function escapeValue(field, value){
var returnValue = '';
switch(field.type){
case 'TIMESTAMP':
returnValue = '"'+value.getUTCFullYear()+'-'+padLeft(value.getUTCMonth(), '0', 2)+'-'+padLeft(value.getUTCDate(), '0', 2)+' '+padLeft(value.getUTCHours(),'0',2)+':'+padLeft(value.getUTCMinutes(), '0', 2)+':'+value.getUTCSeconds()+'"';
break;
case 'NUMBER':
returnValue = value;
break;
case 'STRING':
returnValue = '"'+value+'"';
break;
case 'BOOLEAN':
returnValue = value?1:0;
break;
}
return returnValue;
}
function saveRecords(self, records, processedRecords, cbs){
var errors = [];
if(records.length===processedRecords.length){
if(errors.length>0){
if(cbs.error){
cbs.error(errors, records, processedRecords);
}
}else{
if(cbs.success){
cbs.success(records);
}
}
return;
}
var recordItem = records[processedRecords.length];
saveRecord(self, recordItem, {
success: function(ri){
processedRecords.push(ri);
saveRecords(self, records, processedRecords, cbs);
},
error: function(err, ri){
errors.push(err);
ri.lastError = err;
processedRecords.push(ri);
saveRecords(self, records, processedRecords, cbs);
}
});
}
function saveRecord(self, recordItem, cbs){
var saveSQL = '';
var dataValues = recordItem.dataValues;
var model = recordItem.model;
var fields = model.config.fields;
var setFields = [];
var pkField = model.config.pk_field||'id';
if(dataValues.id){ //update
saveSQL = 'UPDATE '+model.config.collection+' SET ';
for(var key in fields){
if(key!=pkField){
if(recordItem.get(key)){
console.log(key);
console.log(recordItem.get(key));
saveSQL += key+'=?,';
setFields.push(recordItem.get(key));
}
}
}
saveSQL=saveSQL.substr(0, saveSQL.length-1);//remove the last comma
saveSQL+=' WHERE '+pkField+'=?;';
setFields.push(recordItem.get(pkField));
}else{ //insert
recordItem.set('created_at', new Date());
recordItem.set('modified_at', new Date());
saveSQL = 'INSERT INTO '+model.config.collection+' (';
valueSQL = '';
for(var key in fields){
console.log(recordItem.get(key));
if(recordItem.get(key)){
saveSQL += key+',';
setFields.push(recordItem.get(key));
valueSQL+= '?,';
}
}
saveSQL = saveSQL.substr(0, saveSQL.length-1)+') VALUES ('+valueSQL.substr(0, valueSQL.length-1)+')';
}
self.connection.query(saveSQL, setFields, function(err, res){
if(err){
console.log(err);
if(cbs.error){
cbs.error(err, recordItem);
}
}else{
recordItem.set(pkField, recordItem.get(pkField) || res.insertId);
if(cbs.success){
cbs.success(recordItem);
}
}
});
}
function removeRecords(self, records, processedRecords, cbs){
console.log('REMOVING');
console.log(records);
var errors = [];
if(records.length===processedRecords.length){
if(errors.length>0){
if(cbs.error){
cbs.error(errors, records, processedRecords);
}
}else{
if(cbs.success){
cbs.success(records);
}
}
return;
}
var recordItem = records[processedRecords.length];
removeRecord(self, recordItem, {
success: function(ri){
processedRecords.push(ri);
removeRecords(self, records, processedRecords, cbs);
},
error: function(err, ri){
errors.push(err);
ri.lastError = err;
processedRecords.push(ri);
removeRecords(self, records, processedRecords, cbs);
}
});
}
function removeRecord(self, recordItem, cbs){
var model = recordItem.model;
var fields = model.config.fields;
var pkField = model.config.pk_field||'id';
var removeSQL = 'UPDATE '+model.config.collection+' SET deleted_at=?, deleted_by=? WHERE '+pkField+' = ?;';
var setFields = [new Date(), recordItem.get('deleted_by'), recordItem.get(pkField)];
self.connection.query(removeSQL, setFields, function(err, res){
if(err){
if(cbs.error){
cbs.error(err, recordItem);
}
}else{
//recordItem.set('id', res.insertId);
if(cbs.success){
cbs.success(recordItem);
}
}
});
}
function objectToQuery(self, model, queryData, cbs){
var querySQL = 'SELECT ';
var valueArray = [];
if(queryData.fields){
for(var i=0;i<queryData.fields.length;i++){
querySQL+='`'+queryData.fields[i]+'`,';
}
querySQL=querySQL.substr(0, querySQL.length-1);
}else{
querySQL+='* ';
}
querySQL+=' FROM '+model.config.collection;
console.log(queryData);
if(queryData.where){
querySQL+=' WHERE ';
for(var fieldName in queryData.where){
var fieldCrit = queryData.where[fieldName];
if(fieldCrit && (typeof fieldCrit)=='object'){
for(var fieldOp in fieldCrit){
switch(fieldOp){
case 'eq':
if(fieldCrit[fieldOp].length>1){
querySQL+=fieldName+' IN (?) AND ';
valueArray.push(fieldCrit[fieldOp]);
}else{
querySQL+=fieldName+'=? AND ';
valueArray.push(fieldCrit[fieldOp][0]);
}
break;
case 'gt':
if(fieldCrit[fieldOp].length>1){
querySQL+=fieldName+' IN (?) AND ';
}else{
querySQL+=fieldName+'>? AND ';
valueArray.push(fieldCrit[fieldOp][0]);
}
break;
case 'lt':
if(fieldCrit[fieldOp].length>1){
querySQL+=fieldName+' IN (?) AND ';
}else{
querySQL+=fieldName+'<? AND ';
valueArray.push(fieldCrit[fieldOp][0]);
}
break;
}
}
}else{
if(fieldCrit===null){
querySQL+=fieldName+' IS ? AND ';
}else{
if(fieldCrit.length>1){
querySQL+=fieldName+' IN (?) AND ';
}else{
querySQL+=fieldName+'=? AND ';
}
}
valueArray.push(fieldCrit);
}
}
if(querySQL.substr(querySQL.length-5, 5)==' AND '){
querySQL = querySQL.substr(0, querySQL.length-5);
}
}
return {sql: querySQL, values: valueArray};
}
module.exports = MySQLStore; | removed debug code
| index.js | removed debug code | <ide><path>ndex.js
<ide> function objectToQuery(self, model, queryData, cbs){
<ide> var querySQL = 'SELECT ';
<ide> var valueArray = [];
<add>
<ide> if(queryData.fields){
<ide> for(var i=0;i<queryData.fields.length;i++){
<ide> querySQL+='`'+queryData.fields[i]+'`,';
<ide> }
<ide>
<ide> querySQL+=' FROM '+model.config.collection;
<del> console.log(queryData);
<add>
<ide> if(queryData.where){
<ide> querySQL+=' WHERE ';
<ide> |
|
Java | lgpl-2.1 | d7f5bae7bf6170f3620fa88b50f786b84f3ef854 | 0 | tomck/intermine,drhee/toxoMine,elsiklab/intermine,elsiklab/intermine,joshkh/intermine,tomck/intermine,joshkh/intermine,kimrutherford/intermine,justincc/intermine,joshkh/intermine,justincc/intermine,zebrafishmine/intermine,justincc/intermine,justincc/intermine,zebrafishmine/intermine,JoeCarlson/intermine,kimrutherford/intermine,tomck/intermine,drhee/toxoMine,justincc/intermine,elsiklab/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,zebrafishmine/intermine,julie-sullivan/phytomine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,JoeCarlson/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,julie-sullivan/phytomine,julie-sullivan/phytomine,elsiklab/intermine,JoeCarlson/intermine,justincc/intermine,drhee/toxoMine,kimrutherford/intermine,kimrutherford/intermine,JoeCarlson/intermine,drhee/toxoMine,kimrutherford/intermine,elsiklab/intermine,tomck/intermine,kimrutherford/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,joshkh/intermine,tomck/intermine,tomck/intermine,joshkh/intermine,justincc/intermine,julie-sullivan/phytomine,julie-sullivan/phytomine,Arabidopsis-Information-Portal/intermine,julie-sullivan/phytomine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,elsiklab/intermine,elsiklab/intermine,elsiklab/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,zebrafishmine/intermine,drhee/toxoMine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,zebrafishmine/intermine,justincc/intermine,tomck/intermine,joshkh/intermine,JoeCarlson/intermine,zebrafishmine/intermine,julie-sullivan/phytomine,zebrafishmine/intermine,kimrutherford/intermine,JoeCarlson/intermine | intermine/src/java/org/intermine/web/QueryController.java | package org.flymine.web;
/*
* Copyright (C) 2002-2003 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.tiles.actions.TilesAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* Perform initialisation steps for query editing tile prior to calling
* query.jsp.
*
* @author Mark Woodbridge
* @author Richard Smith
*/
public class QueryController extends TilesAction
{
/**
* @see TilesAction#execute
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
return null;
}
}
| Remove redundant controller
| intermine/src/java/org/intermine/web/QueryController.java | Remove redundant controller | <ide><path>ntermine/src/java/org/intermine/web/QueryController.java
<del>package org.flymine.web;
<del>
<del>/*
<del> * Copyright (C) 2002-2003 FlyMine
<del> *
<del> * This code may be freely distributed and modified under the
<del> * terms of the GNU Lesser General Public Licence. This should
<del> * be distributed with the code. See the LICENSE file for more
<del> * information or http://www.gnu.org/copyleft/lesser.html.
<del> *
<del> */
<del>
<del>import javax.servlet.http.HttpServletRequest;
<del>import javax.servlet.http.HttpServletResponse;
<del>
<del>import org.apache.struts.tiles.actions.TilesAction;
<del>import org.apache.struts.action.ActionForm;
<del>import org.apache.struts.action.ActionForward;
<del>import org.apache.struts.action.ActionMapping;
<del>
<del>/**
<del> * Perform initialisation steps for query editing tile prior to calling
<del> * query.jsp.
<del> *
<del> * @author Mark Woodbridge
<del> * @author Richard Smith
<del> */
<del>public class QueryController extends TilesAction
<del>{
<del> /**
<del> * @see TilesAction#execute
<del> */
<del> public ActionForward execute(ActionMapping mapping,
<del> ActionForm form,
<del> HttpServletRequest request,
<del> HttpServletResponse response)
<del> throws Exception {
<del> return null;
<del> }
<del>} |
||
Java | apache-2.0 | 9f72e11600cd1d7946de12d78625f3ae40bef188 | 0 | GEBIT/bnd,psoreide/bnd,lostiniceland/bnd,magnet/bnd,lostiniceland/bnd,lostiniceland/bnd,mcculls/bnd,xtracoder/bnd,joansmith/bnd,joansmith/bnd,GEBIT/bnd,psoreide/bnd,magnet/bnd,xtracoder/bnd,mcculls/bnd,magnet/bnd,psoreide/bnd,mcculls/bnd | package aQute.lib.tag;
import java.io.*;
import java.text.*;
import java.util.*;
/**
* The Tag class represents a minimal XML tree. It consist of a named element
* with a hashtable of named attributes. Methods are provided to walk the tree
* and get its constituents. The content of a Tag is a list that contains String
* objects or other Tag objects.
*/
public class Tag {
Tag parent; // Parent
String name; // Name
final Map<String,String> attributes = new LinkedHashMap<String,String>();
final List<Object> content = new ArrayList<Object>(); // Content
final static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
boolean cdata;
/**
* Construct a new Tag with a name.
*/
public Tag(String name, Object... contents) {
this.name = name;
for (Object c : contents)
content.add(c);
}
public Tag(Tag parent, String name, Object... contents) {
this(name, contents);
parent.addContent(this);
}
/**
* Construct a new Tag with a name.
*/
public Tag(String name, Map<String,String> attributes, Object... contents) {
this(name, contents);
this.attributes.putAll(attributes);
}
public Tag(String name, Map<String,String> attributes) {
this(name, attributes, new Object[0]);
}
/**
* Construct a new Tag with a name and a set of attributes. The attributes
* are given as ( name, value ) ...
*/
public Tag(String name, String[] attributes, Object... contents) {
this(name, contents);
for (int i = 0; i < attributes.length; i += 2)
addAttribute(attributes[i], attributes[i + 1]);
}
public Tag(String name, String[] attributes) {
this(name, attributes, new Object[0]);
}
/**
* Add a new attribute.
*/
public Tag addAttribute(String key, String value) {
if (value != null)
attributes.put(key, value);
return this;
}
/**
* Add a new attribute.
*/
public Tag addAttribute(String key, Object value) {
if (value == null)
return this;
attributes.put(key, value.toString());
return this;
}
/**
* Add a new attribute.
*/
public Tag addAttribute(String key, int value) {
attributes.put(key, Integer.toString(value));
return this;
}
/**
* Add a new date attribute. The date is formatted as the SimpleDateFormat
* describes at the top of this class.
*/
public Tag addAttribute(String key, Date value) {
if (value != null) {
synchronized (format) {
attributes.put(key, format.format(value));
}
}
return this;
}
/**
* Add a new content string.
*/
public Tag addContent(String string) {
if (string != null)
content.add(string);
return this;
}
/**
* Add a new content tag.
*/
public Tag addContent(Tag tag) {
content.add(tag);
tag.parent = this;
return this;
}
/**
* Return the name of the tag.
*/
public String getName() {
return name;
}
/**
* Return the attribute value.
*/
public String getAttribute(String key) {
return attributes.get(key);
}
/**
* Return the attribute value or a default if not defined.
*/
public String getAttribute(String key, String deflt) {
String answer = getAttribute(key);
return answer == null ? deflt : answer;
}
/**
* Answer the attributes as a Dictionary object.
*/
public Map<String,String> getAttributes() {
return attributes;
}
/**
* Return the contents.
*/
public List<Object> getContents() {
return content;
}
/**
* Return a string representation of this Tag and all its children
* recursively.
*/
@Override
public String toString() {
StringWriter sw = new StringWriter();
print(0, new PrintWriter(sw));
return sw.toString();
}
/**
* Return only the tags of the first level of descendants that match the
* name.
*/
public List<Object> getContents(String tag) {
List<Object> out = new ArrayList<Object>();
for (Object o : out) {
if (o instanceof Tag && ((Tag) o).getName().equals(tag))
out.add(o);
}
return out;
}
/**
* Return the whole contents as a String (no tag info and attributes).
*/
public String getContentsAsString() {
StringBuilder sb = new StringBuilder();
getContentsAsString(sb);
return sb.toString();
}
/**
* convenient method to get the contents in a StringBuilder.
*/
public void getContentsAsString(StringBuilder sb) {
for (Object o : content) {
if (o instanceof Tag)
((Tag) o).getContentsAsString(sb);
else
sb.append(o.toString());
}
}
/**
* Print the tag formatted to a PrintWriter.
*/
public Tag print(int indent, PrintWriter pw) {
if (indent >= 0) {
pw.println();
spaces(pw, indent);
}
pw.print('<');
pw.print(name);
for (String key : attributes.keySet()) {
String value = escape(attributes.get(key));
pw.print(' ');
pw.print(key);
pw.print("=\"");
pw.print(value);
pw.print("\"");
}
if (content.size() == 0)
pw.print('/');
else {
pw.print('>');
for (Object c : content) {
if (c instanceof String) {
if (cdata) {
pw.print("<![CDATA[");
String s = (String) c;
s = s.replaceAll("]]>", "] ]>");
pw.print(s);
pw.print("]]>");
} else
formatted(pw, indent + 2, 60, escape((String) c));
} else if (c instanceof Tag) {
Tag tag = (Tag) c;
tag.print(indent + 2, pw);
}
}
if (indent >= 0) {
pw.println();
spaces(pw, indent);
}
pw.print("</");
pw.print(name);
}
pw.print('>');
return this;
}
/**
* Convenience method to print a string nicely and does character conversion
* to entities.
*/
void formatted(PrintWriter pw, int left, int width, String s) {
int pos = width + 1;
s = s.trim();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (i == 0 || (Character.isWhitespace(c) && pos > width - 3)) {
if (left >= 0 && width > 0) {
pw.println();
spaces(pw, left);
}
pos = 0;
}
switch (c) {
case '<' :
pw.print("<");
pos += 4;
break;
case '>' :
pw.print(">");
pos += 4;
break;
case '&' :
pw.print("&");
pos += 5;
break;
default :
pw.print(c);
pos++;
break;
}
}
}
/**
* Escape a string, do entity conversion.
*/
public static String escape(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '<' :
sb.append("<");
break;
case '>' :
sb.append(">");
break;
case '\"' :
sb.append(""");
break;
case '&' :
sb.append("&");
break;
default :
sb.append(c);
break;
}
}
return sb.toString();
}
/**
* Make spaces.
*/
void spaces(PrintWriter pw, int n) {
while (n-- > 0)
pw.print(' ');
}
/**
* root/preferences/native/os
*/
public Collection<Tag> select(String path) {
return select(path, (Tag) null);
}
public Collection<Tag> select(String path, Tag mapping) {
List<Tag> v = new ArrayList<Tag>();
select(path, v, mapping);
return v;
}
void select(String path, List<Tag> results, Tag mapping) {
if (path.startsWith("//")) {
int i = path.indexOf('/', 2);
String name = path.substring(2, i < 0 ? path.length() : i);
for (Object o : content) {
if (o instanceof Tag) {
Tag child = (Tag) o;
if (match(name, child, mapping))
results.add(child);
child.select(path, results, mapping);
}
}
return;
}
if (path.length() == 0) {
results.add(this);
return;
}
int i = path.indexOf("/");
String elementName = path;
String remainder = "";
if (i > 0) {
elementName = path.substring(0, i);
remainder = path.substring(i + 1);
}
for (Object o : content) {
if (o instanceof Tag) {
Tag child = (Tag) o;
if (child.getName().equals(elementName) || elementName.equals("*"))
child.select(remainder, results, mapping);
}
}
}
public boolean match(String search, Tag child, Tag mapping) {
String target = child.getName();
String sn = null;
String tn = null;
if (search.equals("*"))
return true;
int s = search.indexOf(':');
if (s > 0) {
sn = search.substring(0, s);
search = search.substring(s + 1);
}
int t = target.indexOf(':');
if (t > 0) {
tn = target.substring(0, t);
target = target.substring(t + 1);
}
if (!search.equals(target)) // different tag names
return false;
if (mapping == null) {
return tn == sn || (sn != null && sn.equals(tn));
}
String suri = sn == null ? mapping.getAttribute("xmlns") : mapping.getAttribute("xmlns:" + sn);
String turi = tn == null ? child.findRecursiveAttribute("xmlns") : child.findRecursiveAttribute("xmlns:" + tn);
return ((turi == null) && (suri == null)) || ((turi != null) && turi.equals(suri));
}
public String getString(String path) {
String attribute = null;
int index = path.indexOf("@");
if (index >= 0) {
// attribute
attribute = path.substring(index + 1);
if (index > 0) {
// prefix path
path = path.substring(index - 1); // skip -1
} else
path = "";
}
Collection<Tag> tags = select(path);
StringBuilder sb = new StringBuilder();
for (Tag tag : tags) {
if (attribute == null)
tag.getContentsAsString(sb);
else
sb.append(tag.getAttribute(attribute));
}
return sb.toString();
}
public String getStringContent() {
StringBuilder sb = new StringBuilder();
for (Object c : content) {
if (!(c instanceof Tag))
sb.append(c);
}
return sb.toString();
}
public String getNameSpace() {
return getNameSpace(name);
}
public String getNameSpace(String name) {
int index = name.indexOf(':');
if (index > 0) {
String ns = name.substring(0, index);
return findRecursiveAttribute("xmlns:" + ns);
}
return findRecursiveAttribute("xmlns");
}
public String findRecursiveAttribute(String name) {
String value = getAttribute(name);
if (value != null)
return value;
if (parent != null)
return parent.findRecursiveAttribute(name);
return null;
}
public String getLocalName() {
int index = name.indexOf(':');
if (index <= 0)
return name;
return name.substring(index + 1);
}
public void rename(String string) {
name = string;
}
public void setCDATA() {
cdata = true;
}
public String compact() {
StringWriter sw = new StringWriter();
print(Integer.MIN_VALUE, new PrintWriter(sw));
return sw.toString();
}
}
| aQute.libg/src/aQute/lib/tag/Tag.java | package aQute.lib.tag;
import java.io.*;
import java.text.*;
import java.util.*;
/**
* The Tag class represents a minimal XML tree. It consist of a named element
* with a hashtable of named attributes. Methods are provided to walk the tree
* and get its constituents. The content of a Tag is a list that contains String
* objects or other Tag objects.
*/
public class Tag {
Tag parent; // Parent
String name; // Name
final Map<String,String> attributes = new LinkedHashMap<String,String>();
final List<Object> content = new ArrayList<Object>(); // Content
final static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss.SSS");
boolean cdata;
/**
* Construct a new Tag with a name.
*/
public Tag(String name, Object... contents) {
this.name = name;
for (Object c : contents)
content.add(c);
}
public Tag(Tag parent, String name, Object... contents) {
this(name, contents);
parent.addContent(this);
}
/**
* Construct a new Tag with a name.
*/
public Tag(String name, Map<String,String> attributes, Object... contents) {
this(name, contents);
this.attributes.putAll(attributes);
}
public Tag(String name, Map<String,String> attributes) {
this(name, attributes, new Object[0]);
}
/**
* Construct a new Tag with a name and a set of attributes. The attributes
* are given as ( name, value ) ...
*/
public Tag(String name, String[] attributes, Object... contents) {
this(name, contents);
for (int i = 0; i < attributes.length; i += 2)
addAttribute(attributes[i], attributes[i + 1]);
}
public Tag(String name, String[] attributes) {
this(name, attributes, new Object[0]);
}
/**
* Add a new attribute.
*/
public Tag addAttribute(String key, String value) {
if (value != null)
attributes.put(key, value);
return this;
}
/**
* Add a new attribute.
*/
public Tag addAttribute(String key, Object value) {
if (value == null)
return this;
attributes.put(key, value.toString());
return this;
}
/**
* Add a new attribute.
*/
public Tag addAttribute(String key, int value) {
attributes.put(key, Integer.toString(value));
return this;
}
/**
* Add a new date attribute. The date is formatted as the SimpleDateFormat
* describes at the top of this class.
*/
public Tag addAttribute(String key, Date value) {
if (value != null) {
synchronized (format) {
attributes.put(key, format.format(value));
}
}
return this;
}
/**
* Add a new content string.
*/
public Tag addContent(String string) {
if (string != null)
content.add(string);
return this;
}
/**
* Add a new content tag.
*/
public Tag addContent(Tag tag) {
content.add(tag);
tag.parent = this;
return this;
}
/**
* Return the name of the tag.
*/
public String getName() {
return name;
}
/**
* Return the attribute value.
*/
public String getAttribute(String key) {
return attributes.get(key);
}
/**
* Return the attribute value or a default if not defined.
*/
public String getAttribute(String key, String deflt) {
String answer = getAttribute(key);
return answer == null ? deflt : answer;
}
/**
* Answer the attributes as a Dictionary object.
*/
public Map<String,String> getAttributes() {
return attributes;
}
/**
* Return the contents.
*/
public List<Object> getContents() {
return content;
}
/**
* Return a string representation of this Tag and all its children
* recursively.
*/
@Override
public String toString() {
StringWriter sw = new StringWriter();
print(0, new PrintWriter(sw));
return sw.toString();
}
/**
* Return only the tags of the first level of descendants that match the
* name.
*/
public List<Object> getContents(String tag) {
List<Object> out = new ArrayList<Object>();
for (Object o : out) {
if (o instanceof Tag && ((Tag) o).getName().equals(tag))
out.add(o);
}
return out;
}
/**
* Return the whole contents as a String (no tag info and attributes).
*/
public String getContentsAsString() {
StringBuilder sb = new StringBuilder();
getContentsAsString(sb);
return sb.toString();
}
/**
* convenient method to get the contents in a StringBuilder.
*/
public void getContentsAsString(StringBuilder sb) {
for (Object o : content) {
if (o instanceof Tag)
((Tag) o).getContentsAsString(sb);
else
sb.append(o.toString());
}
}
/**
* Print the tag formatted to a PrintWriter.
*/
public Tag print(int indent, PrintWriter pw) {
if (indent >= 0) {
pw.print("\n");
spaces(pw, indent);
}
pw.print('<');
pw.print(name);
for (String key : attributes.keySet()) {
String value = escape(attributes.get(key));
pw.print(' ');
pw.print(key);
pw.print("=\"");
pw.print(value);
pw.print("\"");
}
if (content.size() == 0)
pw.print('/');
else {
pw.print('>');
for (Object c : content) {
if (c instanceof String) {
if (cdata) {
pw.print("<![CDATA[");
String s = (String) c;
s = s.replaceAll("]]>", "] ]>");
pw.print(s);
pw.print("]]>");
} else
formatted(pw, indent + 2, 60, escape((String) c));
} else if (c instanceof Tag) {
Tag tag = (Tag) c;
tag.print(indent + 2, pw);
}
}
if (indent >= 0) {
pw.print("\n");
spaces(pw, indent);
}
pw.print("</");
pw.print(name);
}
pw.print('>');
return this;
}
/**
* Convenience method to print a string nicely and does character conversion
* to entities.
*/
void formatted(PrintWriter pw, int left, int width, String s) {
int pos = width + 1;
s = s.trim();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (i == 0 || (Character.isWhitespace(c) && pos > width - 3)) {
if (left >= 0 && width > 0) {
pw.print("\n");
spaces(pw, left);
}
pos = 0;
}
switch (c) {
case '<' :
pw.print("<");
pos += 4;
break;
case '>' :
pw.print(">");
pos += 4;
break;
case '&' :
pw.print("&");
pos += 5;
break;
default :
pw.print(c);
pos++;
break;
}
}
}
/**
* Escape a string, do entity conversion.
*/
public static String escape(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '<' :
sb.append("<");
break;
case '>' :
sb.append(">");
break;
case '\"' :
sb.append(""");
break;
case '&' :
sb.append("&");
break;
default :
sb.append(c);
break;
}
}
return sb.toString();
}
/**
* Make spaces.
*/
void spaces(PrintWriter pw, int n) {
while (n-- > 0)
pw.print(' ');
}
/**
* root/preferences/native/os
*/
public Collection<Tag> select(String path) {
return select(path, (Tag) null);
}
public Collection<Tag> select(String path, Tag mapping) {
List<Tag> v = new ArrayList<Tag>();
select(path, v, mapping);
return v;
}
void select(String path, List<Tag> results, Tag mapping) {
if (path.startsWith("//")) {
int i = path.indexOf('/', 2);
String name = path.substring(2, i < 0 ? path.length() : i);
for (Object o : content) {
if (o instanceof Tag) {
Tag child = (Tag) o;
if (match(name, child, mapping))
results.add(child);
child.select(path, results, mapping);
}
}
return;
}
if (path.length() == 0) {
results.add(this);
return;
}
int i = path.indexOf("/");
String elementName = path;
String remainder = "";
if (i > 0) {
elementName = path.substring(0, i);
remainder = path.substring(i + 1);
}
for (Object o : content) {
if (o instanceof Tag) {
Tag child = (Tag) o;
if (child.getName().equals(elementName) || elementName.equals("*"))
child.select(remainder, results, mapping);
}
}
}
public boolean match(String search, Tag child, Tag mapping) {
String target = child.getName();
String sn = null;
String tn = null;
if (search.equals("*"))
return true;
int s = search.indexOf(':');
if (s > 0) {
sn = search.substring(0, s);
search = search.substring(s + 1);
}
int t = target.indexOf(':');
if (t > 0) {
tn = target.substring(0, t);
target = target.substring(t + 1);
}
if (!search.equals(target)) // different tag names
return false;
if (mapping == null) {
return tn == sn || (sn != null && sn.equals(tn));
}
String suri = sn == null ? mapping.getAttribute("xmlns") : mapping.getAttribute("xmlns:" + sn);
String turi = tn == null ? child.findRecursiveAttribute("xmlns") : child.findRecursiveAttribute("xmlns:" + tn);
return ((turi == null) && (suri == null)) || ((turi != null) && turi.equals(suri));
}
public String getString(String path) {
String attribute = null;
int index = path.indexOf("@");
if (index >= 0) {
// attribute
attribute = path.substring(index + 1);
if (index > 0) {
// prefix path
path = path.substring(index - 1); // skip -1
} else
path = "";
}
Collection<Tag> tags = select(path);
StringBuilder sb = new StringBuilder();
for (Tag tag : tags) {
if (attribute == null)
tag.getContentsAsString(sb);
else
sb.append(tag.getAttribute(attribute));
}
return sb.toString();
}
public String getStringContent() {
StringBuilder sb = new StringBuilder();
for (Object c : content) {
if (!(c instanceof Tag))
sb.append(c);
}
return sb.toString();
}
public String getNameSpace() {
return getNameSpace(name);
}
public String getNameSpace(String name) {
int index = name.indexOf(':');
if (index > 0) {
String ns = name.substring(0, index);
return findRecursiveAttribute("xmlns:" + ns);
}
return findRecursiveAttribute("xmlns");
}
public String findRecursiveAttribute(String name) {
String value = getAttribute(name);
if (value != null)
return value;
if (parent != null)
return parent.findRecursiveAttribute(name);
return null;
}
public String getLocalName() {
int index = name.indexOf(':');
if (index <= 0)
return name;
return name.substring(index + 1);
}
public void rename(String string) {
name = string;
}
public void setCDATA() {
cdata = true;
}
public String compact() {
StringWriter sw = new StringWriter();
print(Integer.MIN_VALUE, new PrintWriter(sw));
return sw.toString();
}
}
| Use consistent EOLs when creating DS & Metatype resources
MetaTypeReader and TagResource both use PrintWriter.println() to output the XML declaration and then delegate to Tag.print() to generate the XML document. Tag.print() uses PrintWriter.print("\n") to generate newlines in the XML document.
PrintWriter.println() on Windows will use \r\n, so we end up with inconsistent whitespace in the file. This patch changes Tag.print() to invoke PrintWriter.println() instead of hard coding the EOL character. This is only a presentation issue, but it also "resolves" this bndtools issue (assuming you are looking at a JAR created on your platform):
https://github.com/bndtools/bndtools/issues/864
An alternate approach would be to change MetaTypeReader and TagResource to explicitly use a \n when rendering the XML declaration rather than using PrintWriter.println().
Signed-off-by: Sean Bright <[email protected]>
| aQute.libg/src/aQute/lib/tag/Tag.java | Use consistent EOLs when creating DS & Metatype resources | <ide><path>Qute.libg/src/aQute/lib/tag/Tag.java
<ide> */
<ide> public Tag print(int indent, PrintWriter pw) {
<ide> if (indent >= 0) {
<del> pw.print("\n");
<add> pw.println();
<ide> spaces(pw, indent);
<ide> }
<ide> pw.print('<');
<ide> }
<ide> }
<ide> if (indent >= 0) {
<del> pw.print("\n");
<add> pw.println();
<ide> spaces(pw, indent);
<ide> }
<ide> pw.print("</");
<ide> char c = s.charAt(i);
<ide> if (i == 0 || (Character.isWhitespace(c) && pos > width - 3)) {
<ide> if (left >= 0 && width > 0) {
<del> pw.print("\n");
<add> pw.println();
<ide> spaces(pw, left);
<ide> }
<ide> pos = 0; |
|
Java | apache-2.0 | f205a3ee8905332f230c299b85365492ceca9194 | 0 | mikaelhg/urlbuilder,mikesprague/urlbuilder | package gumi.builders;
import org.testng.annotations.Test;
import java.net.*;
import java.util.Arrays;
import static org.testng.Assert.*;
/**
* A few simple, handwritten, non-datadriven tests to get started.
*/
public class SimpleUrlTest {
@Test
public void userInfoTest() throws Exception {
final String userInfo = "username:password";
final String model = "http://" + userInfo + "@server/path?a=b#fragment";
final UrlBuilder ub1 = UrlBuilder.fromString(model);
assertEquals(ub1.userInfo, userInfo);
assertEquals(ub1.toString(), model);
final URL url1 = ub1.toUrl();
assertEquals(url1.getUserInfo(), userInfo);
assertEquals(url1.toString(), model);
final UrlBuilder ub2 = UrlBuilder.fromUrl(new URL(model));
assertEquals(ub2.userInfo, userInfo);
}
@Test
public void incompleteUserInfoTest() throws Exception {
final String userInfo = "username:password";
final UrlBuilder ub1 = UrlBuilder.empty().withScheme("http").withUserInfo(userInfo);
assertEquals(ub1.userInfo, userInfo);
assertEquals(ub1.toString(), "http:");
final URL url1 = ub1.toUrl();
assertEquals(url1.toString(), "http:");
assertNull(url1.getUserInfo());
final UrlBuilder ub2 = UrlBuilder.fromString("http://username:password@");
assertEquals(ub2.userInfo, userInfo);
assertEquals(ub2.hostName, "");
final UrlBuilder ub3 = UrlBuilder.fromString("http://username:password@/");
assertEquals(ub3.userInfo, userInfo);
assertEquals(ub3.hostName, "");
}
@Test(expectedExceptions = NumberFormatException.class)
public void brokenUrlEncodingTest() throws Exception {
UrlBuilder.fromString("http://localhost/%ax");
}
@Test
public void utf8Test() throws Exception {
assertEquals(UrlBuilder
.fromString("http://foo/h%F6pl%E4", "ISO-8859-1")
.encodeAs("UTF-8").toString(),
"http://foo/h%C3%B6pl%C3%A4");
}
@Test
public void parameterTest() {
final UrlBuilder ub1 = UrlBuilder.fromString("?a=b&a=c&b=c");
assertTrue(ub1.queryParameters.containsKey("a"));
assertTrue(ub1.queryParameters.containsKey("b"));
assertEquals(ub1.queryParameters.get("a"), Arrays.asList("b", "c"));
}
@Test
public void brokenparameterTest() {
final UrlBuilder ub1 = UrlBuilder.fromString("?=b");
assertEquals(ub1.queryParameters.get("").get(0), "b");
final UrlBuilder ub2 = UrlBuilder.fromString("?==b");
assertEquals(ub2.queryParameters.get("").get(0), "=b");
assertEquals(ub2.toString(), "?=%3Db");
}
@Test
public void simpleTest() throws Exception {
final UrlBuilder ub1 = UrlBuilder.empty()
.withScheme("http")
.withHost("www.example.com")
.withPath("/")
.addParameter("foo", "bar");
final String urlString1 = ub1.toString();
final UrlBuilder ub2 = UrlBuilder.fromString("http://www.example.com/?foo=bar");
final String urlString2 = ub2.toString();
assertEquals(urlString1, "http://www.example.com/?foo=bar");
assertEquals(urlString2, "http://www.example.com/?foo=bar");
final String portUrl = "http://www.example.com:1234/?foo=bar";
assertEquals(portUrl, UrlBuilder.fromString(portUrl).toString());
}
@Test
public void percentEndOfLineTest() throws Exception {
final UrlBuilder ub1 = UrlBuilder.fromString("http://www.example.com/?q=Science%2");
final UrlBuilder ub2 = UrlBuilder.fromString("http://www.example.com/?q=Science%25");
final UrlBuilder ub3 = UrlBuilder.fromString("http://www.example.com/?q=Science%");
final UrlBuilder ub4 = UrlBuilder.fromString("http://www.example.com/?q=Science%255");
assertEquals(ub1.toString(), "http://www.example.com/?q=Science%252");
assertEquals(ub2.toString(), "http://www.example.com/?q=Science%25");
assertEquals(ub3.toString(), "http://www.example.com/?q=Science%25");
assertEquals(ub4.toString(), "http://www.example.com/?q=Science%255");
}
@Test
public void urlExceptionTest() throws Exception {
UrlBuilder.fromString("https://www:1234/").toUriWithException();
final String charset = "ISO-8859-1";
final String foo = URLEncoder.encode("ööäöäöäö", charset);
final String bar = URLDecoder.decode(foo, charset);
final String url1 = "https://www:1234/foo?foo=" + foo;
assertEquals(UrlBuilder.empty().encodeAs("ISO-8859-1")
.withHost("test").withPath("/foo")
.addParameter("foo", "öäöäöä")
.toString(),
"//test/foo?foo=%F6%E4%F6%E4%F6%E4");
assertEquals(UrlBuilder.fromString(url1, charset).encodeAs(charset).toString(), url1);
assertEquals(UrlBuilder.fromString("?foo=%E4%F6%E4%F6%E4%F6%E4%F6%E4%F6", "ISO-8859-1").toString(),
"?foo=%C3%A4%C3%B6%C3%A4%C3%B6%C3%A4%C3%B6%C3%A4%C3%B6%C3%A4%C3%B6");
assertEquals(UrlBuilder.fromString("?foo=%E4%F6%E4%F6%E4%F6%E4%F6%E4%F6", "ISO-8859-1").encodeAs("ISO-8859-1").toString(),
"?foo=%E4%F6%E4%F6%E4%F6%E4%F6%E4%F6");
assertEquals(UrlBuilder.fromString("http://foo/h%E4pl%F6", "ISO-8859-1").encodeAs("UTF-8").toString(),
"http://foo/h%C3%A4pl%C3%B6");
}
@Test
public void testEmptyParameterNameAfterAmpersand() {
assertEquals("foo", UrlBuilder.fromString("http://www.google.com/?q=foo&").queryParameters.get("q").get(0));
}
@Test
public void testArrayParameterOrderStability() {
final String qp1 = "?a=1&b=2&a=3&b=4";
assertEquals(qp1, UrlBuilder.fromString(qp1).toString());
}
@Test
public void testNonArrayParameterOrderStability() {
final String qp1 = "?a=1&b=2&c=3&d=4";
assertEquals(UrlBuilder.fromString(qp1).toString(), qp1);
final String qp2 = "?d=1&c=2&b=3&a=4";
assertEquals(UrlBuilder.fromString(qp2).toString(), qp2);
}
@Test
public void testPortParsing() {
assertUrlBuilderEquals(null, "localhost", 8080, "/thing", UrlBuilder.fromString("http://localhost:8080/thing"));
assertUrlBuilderEquals(null, "localhost", null, "/thing", UrlBuilder.fromString("http://localhost/thing"));
assertUrlBuilderEquals("arabung", "localhost", null, "/thing", UrlBuilder.fromString("http://arabung@localhost/thing"));
assertUrlBuilderEquals("arabung", "localhost", 808, "/thing", UrlBuilder.fromString("http://arabung@localhost:808/thing"));
assertUrlBuilderEquals(null, "github.com", null, "", UrlBuilder.fromString("https://github.com"));
assertUrlBuilderEquals(null, "github.com", 443, "", UrlBuilder.fromString("https://github.com:443.com"));
}
private static void assertUrlBuilderEquals(String expectedUserInfo, String expectedHostName, Integer expectedPort, String expectedPath, UrlBuilder b) {
assertEquals(b.userInfo, expectedUserInfo);
assertEquals(b.hostName, expectedHostName);
assertEquals(b.port, expectedPort);
assertEquals(b.path, expectedPath);
}
@Test
public void parsePortAndHostname() {
UrlBuilder b = UrlBuilder.fromString("http://foo:8080/foo");
assertEquals(b.port, new Integer(8080));
assertEquals(b.hostName, "foo");
}
@Test
public void encodedPathFromURI() throws URISyntaxException {
assertEquals(UrlBuilder.fromUri(new URI("http://foo/a%20b")).toString(), "http://foo/a%20b");
assertEquals(UrlBuilder.fromUri(new URI("http://foo/a%7Bb")).toString(), "http://foo/a%7Bb");
}
@Test
public void testRemoveParameter() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1");
assertFalse(b.removeParameters("parameter1").queryParameters.containsKey("parameter1"));
assertEquals(b.removeParameter("parameter1", "value1").toString(), "http://somehost.com/page");
}
@Test
public void testRemoveOneParameterByKey() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1");
assertFalse(b.removeParameters("parameter1").queryParameters.containsKey("parameter1"));
assertEquals(b.removeParameters("parameter1").toString(), "http://somehost.com/page");
}
@Test
public void testRemoveTwoParametersByKey() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1¶meter1=value2");
assertFalse(b.removeParameters("parameter1").queryParameters.containsKey("parameter1"));
assertEquals(b.removeParameters("parameter1").toString(), "http://somehost.com/page");
}
@Test
public void testRemoveThreeParametersByKey() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1¶meter1=value2¶meter1=value3");
assertFalse(b.removeParameters("parameter1").queryParameters.containsKey("parameter1"));
assertEquals(b.removeParameters("parameter1").toString(), "http://somehost.com/page");
}
@Test
public void containsParameter() {
final UrlBuilder b = UrlBuilder.fromString("/?a=1");
assertTrue(b.queryParameters.containsKey("a"), "builder contains parameter");
assertFalse(b.queryParameters.containsKey("b"), "builder doesn't contain parameter");
}
@Test
public void testSetParameterShouldReplaceExistingParameter() {
UrlBuilder builder = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1");
assertEquals(builder.setParameter("parameter1", "value2").toString(), "http://somehost.com/page?parameter1=value2");
}
@Test
public void testAddParameterShouldAppendOneNewParameter() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1");
assertEquals(b.addParameter("parameter1", "value2").toString(),
"http://somehost.com/page?parameter1=value1¶meter1=value2");
}
@Test
public void testWithFragmentShouldAppendAnchor() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page");
assertEquals(b.withFragment("anchor").toString(), "http://somehost.com/page#anchor");
}
}
| src/test/java/gumi/builders/SimpleUrlTest.java | package gumi.builders;
import org.testng.annotations.Test;
import java.net.*;
import java.util.Arrays;
import static org.testng.Assert.*;
/**
* A few simple, handwritten, non-datadriven tests to get started.
*/
public class SimpleUrlTest {
@Test
public void userInfoTest() throws Exception {
final String userInfo = "username:password";
final String model = "http://" + userInfo + "@server/path?a=b#fragment";
final UrlBuilder ub1 = UrlBuilder.fromString(model);
assertEquals(ub1.userInfo, userInfo);
assertEquals(ub1.toString(), model);
final URL url1 = ub1.toUrl();
assertEquals(url1.getUserInfo(), userInfo);
assertEquals(url1.toString(), model);
final UrlBuilder ub2 = UrlBuilder.fromUrl(new URL(model));
assertEquals(ub2.userInfo, userInfo);
}
@Test
public void incompleteUserInfoTest() throws Exception {
final String userInfo = "username:password";
final UrlBuilder ub1 = UrlBuilder.empty().withScheme("http").withUserInfo(userInfo);
assertEquals(ub1.userInfo, userInfo);
assertEquals(ub1.toString(), "http:");
final URL url1 = ub1.toUrl();
assertEquals(url1.toString(), "http:");
assertNull(url1.getUserInfo());
final UrlBuilder ub2 = UrlBuilder.fromString("http://username:password@");
assertEquals(ub2.userInfo, userInfo);
assertEquals(ub2.hostName, "");
final UrlBuilder ub3 = UrlBuilder.fromString("http://username:password@/");
assertEquals(ub3.userInfo, userInfo);
assertEquals(ub3.hostName, "");
}
@Test(expectedExceptions = NumberFormatException.class)
public void brokenUrlEncodingTest() throws Exception {
UrlBuilder.fromString("http://localhost/%ax");
}
@Test
public void utf8Test() throws Exception {
assertEquals(UrlBuilder
.fromString("http://foo/h%F6pl%E4", "ISO-8859-1")
.encodeAs("UTF-8").toString(),
"http://foo/h%C3%B6pl%C3%A4");
}
@Test
public void parameterTest() {
final UrlBuilder ub1 = UrlBuilder.fromString("?a=b&a=c&b=c");
assertTrue(ub1.queryParameters.containsKey("a"));
assertTrue(ub1.queryParameters.containsKey("b"));
assertEquals(ub1.queryParameters.get("a"), Arrays.asList("b", "c"));
}
@Test
public void brokenparameterTest() {
final UrlBuilder ub1 = UrlBuilder.fromString("?=b");
assertEquals(ub1.queryParameters.get("").get(0), "b");
final UrlBuilder ub2 = UrlBuilder.fromString("?==b");
assertEquals(ub2.queryParameters.get("").get(0), "=b");
assertEquals(ub2.toString(), "?=%3Db");
}
@Test
public void simpleTest() throws Exception {
final UrlBuilder ub1 = UrlBuilder.empty()
.withScheme("http")
.withHost("www.example.com")
.withPath("/")
.addParameter("foo", "bar");
final String urlString1 = ub1.toString();
final UrlBuilder ub2 = UrlBuilder.fromString("http://www.example.com/?foo=bar");
final String urlString2 = ub2.toString();
assertEquals(urlString1, "http://www.example.com/?foo=bar");
assertEquals(urlString2, "http://www.example.com/?foo=bar");
final String portUrl = "http://www.example.com:1234/?foo=bar";
assertEquals(portUrl, UrlBuilder.fromString(portUrl).toString());
}
@Test
public void urlExceptionTest() throws Exception {
UrlBuilder.fromString("https://www:1234/").toUriWithException();
final String charset = "ISO-8859-1";
final String foo = URLEncoder.encode("ööäöäöäö", charset);
final String bar = URLDecoder.decode(foo, charset);
final String url1 = "https://www:1234/foo?foo=" + foo;
assertEquals(UrlBuilder.empty().encodeAs("ISO-8859-1")
.withHost("test").withPath("/foo")
.addParameter("foo", "öäöäöä")
.toString(),
"//test/foo?foo=%F6%E4%F6%E4%F6%E4");
assertEquals(UrlBuilder.fromString(url1, charset).encodeAs(charset).toString(), url1);
assertEquals(UrlBuilder.fromString("?foo=%E4%F6%E4%F6%E4%F6%E4%F6%E4%F6", "ISO-8859-1").toString(),
"?foo=%C3%A4%C3%B6%C3%A4%C3%B6%C3%A4%C3%B6%C3%A4%C3%B6%C3%A4%C3%B6");
assertEquals(UrlBuilder.fromString("?foo=%E4%F6%E4%F6%E4%F6%E4%F6%E4%F6", "ISO-8859-1").encodeAs("ISO-8859-1").toString(),
"?foo=%E4%F6%E4%F6%E4%F6%E4%F6%E4%F6");
assertEquals(UrlBuilder.fromString("http://foo/h%E4pl%F6", "ISO-8859-1").encodeAs("UTF-8").toString(),
"http://foo/h%C3%A4pl%C3%B6");
}
@Test
public void testEmptyParameterNameAfterAmpersand() {
assertEquals("foo", UrlBuilder.fromString("http://www.google.com/?q=foo&").queryParameters.get("q").get(0));
}
@Test
public void testArrayParameterOrderStability() {
final String qp1 = "?a=1&b=2&a=3&b=4";
assertEquals(qp1, UrlBuilder.fromString(qp1).toString());
}
@Test
public void testNonArrayParameterOrderStability() {
final String qp1 = "?a=1&b=2&c=3&d=4";
assertEquals(UrlBuilder.fromString(qp1).toString(), qp1);
final String qp2 = "?d=1&c=2&b=3&a=4";
assertEquals(UrlBuilder.fromString(qp2).toString(), qp2);
}
@Test
public void testPortParsing() {
assertUrlBuilderEquals(null, "localhost", 8080, "/thing", UrlBuilder.fromString("http://localhost:8080/thing"));
assertUrlBuilderEquals(null, "localhost", null, "/thing", UrlBuilder.fromString("http://localhost/thing"));
assertUrlBuilderEquals("arabung", "localhost", null, "/thing", UrlBuilder.fromString("http://arabung@localhost/thing"));
assertUrlBuilderEquals("arabung", "localhost", 808, "/thing", UrlBuilder.fromString("http://arabung@localhost:808/thing"));
assertUrlBuilderEquals(null, "github.com", null, "", UrlBuilder.fromString("https://github.com"));
assertUrlBuilderEquals(null, "github.com", 443, "", UrlBuilder.fromString("https://github.com:443.com"));
}
private static void assertUrlBuilderEquals(String expectedUserInfo, String expectedHostName, Integer expectedPort, String expectedPath, UrlBuilder b) {
assertEquals(b.userInfo, expectedUserInfo);
assertEquals(b.hostName, expectedHostName);
assertEquals(b.port, expectedPort);
assertEquals(b.path, expectedPath);
}
@Test
public void parsePortAndHostname() {
UrlBuilder b = UrlBuilder.fromString("http://foo:8080/foo");
assertEquals(b.port, new Integer(8080));
assertEquals(b.hostName, "foo");
}
@Test
public void encodedPathFromURI() throws URISyntaxException {
assertEquals(UrlBuilder.fromUri(new URI("http://foo/a%20b")).toString(), "http://foo/a%20b");
assertEquals(UrlBuilder.fromUri(new URI("http://foo/a%7Bb")).toString(), "http://foo/a%7Bb");
}
@Test
public void testRemoveParameter() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1");
assertFalse(b.removeParameters("parameter1").queryParameters.containsKey("parameter1"));
assertEquals(b.removeParameter("parameter1", "value1").toString(), "http://somehost.com/page");
}
@Test
public void testRemoveOneParameterByKey() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1");
assertFalse(b.removeParameters("parameter1").queryParameters.containsKey("parameter1"));
assertEquals(b.removeParameters("parameter1").toString(), "http://somehost.com/page");
}
@Test
public void testRemoveTwoParametersByKey() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1¶meter1=value2");
assertFalse(b.removeParameters("parameter1").queryParameters.containsKey("parameter1"));
assertEquals(b.removeParameters("parameter1").toString(), "http://somehost.com/page");
}
@Test
public void testRemoveThreeParametersByKey() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1¶meter1=value2¶meter1=value3");
assertFalse(b.removeParameters("parameter1").queryParameters.containsKey("parameter1"));
assertEquals(b.removeParameters("parameter1").toString(), "http://somehost.com/page");
}
@Test
public void containsParameter() {
final UrlBuilder b = UrlBuilder.fromString("/?a=1");
assertTrue(b.queryParameters.containsKey("a"), "builder contains parameter");
assertFalse(b.queryParameters.containsKey("b"), "builder doesn't contain parameter");
}
@Test
public void testSetParameterShouldReplaceExistingParameter() {
UrlBuilder builder = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1");
assertEquals(builder.setParameter("parameter1", "value2").toString(), "http://somehost.com/page?parameter1=value2");
}
@Test
public void testAddParameterShouldAppendOneNewParameter() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page?parameter1=value1");
assertEquals(b.addParameter("parameter1", "value2").toString(),
"http://somehost.com/page?parameter1=value1¶meter1=value2");
}
@Test
public void testWithFragmentShouldAppendAnchor() {
UrlBuilder b = UrlBuilder.fromString("http://somehost.com/page");
assertEquals(b.withFragment("anchor").toString(), "http://somehost.com/page#anchor");
}
}
| A test for various URLs that end in with a broken percent encoding. Some of these will throw an exception.
| src/test/java/gumi/builders/SimpleUrlTest.java | A test for various URLs that end in with a broken percent encoding. Some of these will throw an exception. | <ide><path>rc/test/java/gumi/builders/SimpleUrlTest.java
<ide> assertEquals(portUrl, UrlBuilder.fromString(portUrl).toString());
<ide> }
<ide>
<add> @Test
<add> public void percentEndOfLineTest() throws Exception {
<add> final UrlBuilder ub1 = UrlBuilder.fromString("http://www.example.com/?q=Science%2");
<add> final UrlBuilder ub2 = UrlBuilder.fromString("http://www.example.com/?q=Science%25");
<add> final UrlBuilder ub3 = UrlBuilder.fromString("http://www.example.com/?q=Science%");
<add> final UrlBuilder ub4 = UrlBuilder.fromString("http://www.example.com/?q=Science%255");
<add>
<add> assertEquals(ub1.toString(), "http://www.example.com/?q=Science%252");
<add> assertEquals(ub2.toString(), "http://www.example.com/?q=Science%25");
<add> assertEquals(ub3.toString(), "http://www.example.com/?q=Science%25");
<add> assertEquals(ub4.toString(), "http://www.example.com/?q=Science%255");
<add> }
<add>
<ide> @Test
<ide> public void urlExceptionTest() throws Exception {
<ide> UrlBuilder.fromString("https://www:1234/").toUriWithException(); |
|
JavaScript | mit | 4d16488baf44b18c86cd70ae73244697e9452402 | 0 | rkrauskopf/ez-spawn | "use strict";
const chai = require("chai");
const expect = chai.expect;
const syntaxModes = require("../fixtures/syntax-modes");
for (let spawn of syntaxModes) {
describe(`error handling (${spawn.name})`, () => {
it("should throw an error if no args are passed", () => {
return spawn()
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.equal("The command to execute is missing.");
expect(error.toString()).to.equal("Error: The command to execute is missing.");
// Check the process info
expect(error.command).to.equal("");
expect(error.args).to.deep.equal([]);
expect(error.status).to.equal(null);
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.equal("");
});
});
it("should throw an error if the command is empty", () => {
return spawn("")
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.equal("The command to execute is missing.");
expect(error.toString()).to.equal("Error: The command to execute is missing.");
// Check the process info
expect(error.command).to.equal("");
expect(error.args).to.deep.equal([]);
expect(error.status).to.equal(null);
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.equal("");
});
});
it("should throw and error if the command is not a string", () => {
return spawn({}, "--foo", "--bar")
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.equal("The command to execute should be a string, not an Object.");
expect(error.toString()).to.equal("Error: The command to execute should be a string, not an Object.");
// Check the process info
expect(error.command).to.equal("[object Object]");
expect(error.args).to.deep.equal(["--foo", "--bar"]);
expect(error.status).to.equal(null);
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.equal("");
});
});
it("should throw an error if the command args are not strings or arrays", () => {
return spawn("test/fixtures/bin/echo-args", ["--foo", {}])
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.equal("The command arguments should be strings, but argument #2 is an Object.");
expect(error.toString()).to.equal("Error: The command arguments should be strings, but argument #2 is an Object.");
// Check the process info
expect(error.command).to.equal("test/fixtures/bin/echo-args");
expect(error.args).to.deep.equal(["--foo", "[object Object]"]);
expect(error.status).to.equal(null);
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.equal("");
});
});
describe("error while spawning the process", () => {
it("should throw an error when a command is not found", () => {
return spawn("test/fixtures/bin/wrong-command --foo --bar")
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.contain("test/fixtures/bin/wrong-command ENOENT");
expect(error.toString()).to.contain("test/fixtures/bin/wrong-command ENOENT");
// Check the process info
expect(error.command).to.equal("test/fixtures/bin/wrong-command");
expect(error.args).to.deep.equal(["--foo", "--bar"]);
if (spawn.name === "syncSyntax" && process.platform === "win32") {
// On Windows, cross-spawn tries to run the command via "cmd", so it has an exit code
expect(error.status).to.equal(1);
}
else {
expect(error.status).to.equal(null);
}
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.contain("wrong-command");
});
});
it("should return an error on a non-executable file", () => {
return spawn("test/fixtures/bin/text-file --foo --bar")
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.contain("test/fixtures/bin/text-file ENOENT");
expect(error.toString()).to.contain("test/fixtures/bin/text-file ENOENT");
// Check the process info
expect(error.command).to.equal("test/fixtures/bin/text-file");
expect(error.args).to.deep.equal(["--foo", "--bar"]);
if (spawn.name === "syncSyntax" && process.platform === "win32") {
// On Windows, cross-spawn tries to run the command via "cmd", so it has an exit code
expect(error.status).to.equal(1);
}
else {
expect(error.status).to.equal(null);
}
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.contain("text-file");
});
});
});
});
}
| test/specs/error.spec.js | "use strict";
const chai = require("chai");
const expect = chai.expect;
const syntaxModes = require("../fixtures/syntax-modes");
for (let spawn of syntaxModes) {
describe(`error handling (${spawn.name})`, () => {
it("should throw an error if no args are passed", () => {
return spawn()
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.equal("The command to execute is missing.");
expect(error.toString()).to.equal("Error: The command to execute is missing.");
// Check the process info
expect(error.command).to.equal("");
expect(error.args).to.deep.equal([]);
expect(error.status).to.equal(null);
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.equal("");
});
});
it("should throw an error if the command is empty", () => {
return spawn("")
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.equal("The command to execute is missing.");
expect(error.toString()).to.equal("Error: The command to execute is missing.");
// Check the process info
expect(error.command).to.equal("");
expect(error.args).to.deep.equal([]);
expect(error.status).to.equal(null);
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.equal("");
});
});
it("should throw and error if the command is not a string", () => {
return spawn({}, "--foo", "--bar")
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.equal("The command to execute should be a string, not an Object.");
expect(error.toString()).to.equal("Error: The command to execute should be a string, not an Object.");
// Check the process info
expect(error.command).to.equal("[object Object]");
expect(error.args).to.deep.equal(["--foo", "--bar"]);
expect(error.status).to.equal(null);
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.equal("");
});
});
it("should throw an error if the command args are not strings or arrays", () => {
return spawn("test/fixtures/bin/echo-args", ["--foo", {}])
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.equal("The command arguments should be strings, but argument #2 is an Object.");
expect(error.toString()).to.equal("Error: The command arguments should be strings, but argument #2 is an Object.");
// Check the process info
expect(error.command).to.equal("test/fixtures/bin/echo-args");
expect(error.args).to.deep.equal(["--foo", "[object Object]"]);
expect(error.status).to.equal(null);
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.equal("");
});
});
describe("error while spawning the process", () => {
it("should throw an error when a command is not found", () => {
return spawn("test/fixtures/bin/wrong-command --foo --bar")
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.contain("test/fixtures/bin/wrong-command ENOENT");
expect(error.toString()).to.contain("test/fixtures/bin/wrong-command ENOENT");
// Check the process info
expect(error.command).to.equal("test/fixtures/bin/wrong-command");
expect(error.args).to.deep.equal(["--foo", "--bar"]);
if (spawn.name === "syncSyntax") {
// TODO: Find out why the status code is 1 for spawnSync, but not for spawn
// TODO: I suspect that this may be a bug in cross-spawn
expect(error.status).to.equal(1);
}
else {
expect(error.status).to.equal(null);
}
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.contain("wrong-command");
});
});
it("should return an error on a non-executable file", () => {
return spawn("test/fixtures/bin/text-file --foo --bar")
.then(() => {
chai.assert(false, "no error was thrown");
})
.catch(error => {
// Verify the error
expect(error).to.be.an.instanceOf(Error);
expect(error.message).to.contain("test/fixtures/bin/text-file ENOENT");
expect(error.toString()).to.contain("test/fixtures/bin/text-file ENOENT");
// Check the process info
expect(error.command).to.equal("test/fixtures/bin/text-file");
expect(error.args).to.deep.equal(["--foo", "--bar"]);
if (spawn.name === "syncSyntax") {
// TODO: Find out why the status code is 1 for spawnSync, but not for spawn
// TODO: I suspect that this may be a bug in cross-spawn
expect(error.status).to.equal(1);
}
else {
expect(error.status).to.equal(null);
}
expect(error.signal).to.equal(null);
expect(error.stdout).to.equal("");
expect(error.stderr).to.contain("text-file");
});
});
});
});
}
| Fixed a test that was failing on non-Windows systems
| test/specs/error.spec.js | Fixed a test that was failing on non-Windows systems | <ide><path>est/specs/error.spec.js
<ide> expect(error.command).to.equal("test/fixtures/bin/wrong-command");
<ide> expect(error.args).to.deep.equal(["--foo", "--bar"]);
<ide>
<del> if (spawn.name === "syncSyntax") {
<del> // TODO: Find out why the status code is 1 for spawnSync, but not for spawn
<del> // TODO: I suspect that this may be a bug in cross-spawn
<add> if (spawn.name === "syncSyntax" && process.platform === "win32") {
<add> // On Windows, cross-spawn tries to run the command via "cmd", so it has an exit code
<ide> expect(error.status).to.equal(1);
<ide> }
<ide> else {
<ide> expect(error.command).to.equal("test/fixtures/bin/text-file");
<ide> expect(error.args).to.deep.equal(["--foo", "--bar"]);
<ide>
<del> if (spawn.name === "syncSyntax") {
<del> // TODO: Find out why the status code is 1 for spawnSync, but not for spawn
<del> // TODO: I suspect that this may be a bug in cross-spawn
<add> if (spawn.name === "syncSyntax" && process.platform === "win32") {
<add> // On Windows, cross-spawn tries to run the command via "cmd", so it has an exit code
<ide> expect(error.status).to.equal(1);
<ide> }
<ide> else { |
|
Java | apache-2.0 | 14ceb1fd9c99282c7044c2d5bd586e7a64a402aa | 0 | mikosik/smooth-build,mikosik/smooth-build | package org.smoothbuild.lang.base.type;
import static java.util.stream.Collectors.toList;
import static org.smoothbuild.lang.base.type.TestedType.A;
import static org.smoothbuild.lang.base.type.TestedType.A_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.A_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.B;
import static org.smoothbuild.lang.base.type.TestedType.BLOB;
import static org.smoothbuild.lang.base.type.TestedType.BLOB_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.BLOB_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.BOOL;
import static org.smoothbuild.lang.base.type.TestedType.BOOL_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.BOOL_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.B_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.B_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.NOTHING;
import static org.smoothbuild.lang.base.type.TestedType.NOTHING_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.NOTHING_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.STRING;
import static org.smoothbuild.lang.base.type.TestedType.STRING_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.STRING_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_BOOL;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_BOOL_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_BOOL_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_STRING;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_STRING_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_STRING_ARRAY2;
import java.util.ArrayList;
import java.util.List;
public class TestedAssignmentSpec extends TestedAssignment {
public final boolean allowed;
public TestedAssignmentSpec(TestedAssignment assignment, boolean allowed) {
super(assignment.target, assignment.source);
this.allowed = allowed;
}
TestedAssignmentSpec(TestedType target, TestedType source, boolean allowed) {
super(target, source);
this.allowed = allowed;
}
public static TestedAssignmentSpec illegalAssignment(TestedType target, TestedType source) {
return new TestedAssignmentSpec(target, source, false);
}
public static TestedAssignmentSpec allowedAssignment(TestedType target, TestedType source) {
return new TestedAssignmentSpec(target, source, true);
}
public static List<TestedAssignmentSpec> assignment_test_specs() {
return List.of(
// A
illegalAssignment(A, BLOB),
illegalAssignment(A, BOOL),
allowedAssignment(A, NOTHING),
illegalAssignment(A, STRING),
illegalAssignment(A, STRUCT_WITH_STRING),
allowedAssignment(A, A),
illegalAssignment(A, B),
illegalAssignment(A, BLOB_ARRAY),
illegalAssignment(A, BOOL_ARRAY),
illegalAssignment(A, NOTHING_ARRAY),
illegalAssignment(A, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(A, STRING_ARRAY),
illegalAssignment(A, A_ARRAY),
illegalAssignment(A, B_ARRAY),
illegalAssignment(A, BLOB_ARRAY2),
illegalAssignment(A, BOOL_ARRAY2),
illegalAssignment(A, NOTHING_ARRAY2),
illegalAssignment(A, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(A, STRING_ARRAY2),
illegalAssignment(A, A_ARRAY2),
illegalAssignment(A, B_ARRAY2),
// Blob
allowedAssignment(BLOB, BLOB),
illegalAssignment(BLOB, BOOL),
allowedAssignment(BLOB, NOTHING),
illegalAssignment(BLOB, STRING),
illegalAssignment(BLOB, STRUCT_WITH_STRING),
illegalAssignment(BLOB, A),
illegalAssignment(BLOB, BLOB_ARRAY),
illegalAssignment(BLOB, BOOL_ARRAY),
illegalAssignment(BLOB, NOTHING_ARRAY),
illegalAssignment(BLOB, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BLOB, STRING_ARRAY),
illegalAssignment(BLOB, A_ARRAY),
illegalAssignment(BLOB, BLOB_ARRAY2),
illegalAssignment(BLOB, BOOL_ARRAY2),
illegalAssignment(BLOB, NOTHING_ARRAY2),
illegalAssignment(BLOB, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BLOB, STRING_ARRAY2),
illegalAssignment(BLOB, A_ARRAY2),
// Bool
illegalAssignment(BOOL, BLOB),
allowedAssignment(BOOL, BOOL),
allowedAssignment(BOOL, NOTHING),
illegalAssignment(BOOL, STRING),
illegalAssignment(BOOL, STRUCT_WITH_STRING),
illegalAssignment(BOOL, A),
illegalAssignment(BOOL, BLOB_ARRAY),
illegalAssignment(BOOL, BOOL_ARRAY),
illegalAssignment(BOOL, NOTHING_ARRAY),
illegalAssignment(BOOL, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BOOL, STRING_ARRAY),
illegalAssignment(BOOL, A_ARRAY),
illegalAssignment(BOOL, BLOB_ARRAY2),
illegalAssignment(BOOL, BOOL_ARRAY2),
illegalAssignment(BOOL, NOTHING_ARRAY2),
illegalAssignment(BOOL, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BOOL, STRING_ARRAY2),
illegalAssignment(BOOL, A_ARRAY2),
// Nothing
illegalAssignment(NOTHING, BLOB),
illegalAssignment(NOTHING, BOOL),
allowedAssignment(NOTHING, NOTHING),
illegalAssignment(NOTHING, STRING),
illegalAssignment(NOTHING, STRUCT_WITH_STRING),
illegalAssignment(NOTHING, A),
illegalAssignment(NOTHING, BLOB_ARRAY),
illegalAssignment(NOTHING, BOOL_ARRAY),
illegalAssignment(NOTHING, NOTHING_ARRAY),
illegalAssignment(NOTHING, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(NOTHING, STRING_ARRAY),
illegalAssignment(NOTHING, A_ARRAY),
illegalAssignment(NOTHING, BLOB_ARRAY2),
illegalAssignment(NOTHING, BOOL_ARRAY2),
illegalAssignment(NOTHING, NOTHING_ARRAY2),
illegalAssignment(NOTHING, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(NOTHING, STRING_ARRAY2),
illegalAssignment(NOTHING, A_ARRAY2),
// String
illegalAssignment(STRING, BLOB),
illegalAssignment(STRING, BOOL),
allowedAssignment(STRING, NOTHING),
allowedAssignment(STRING, STRING),
allowedAssignment(STRING, STRUCT_WITH_STRING),
illegalAssignment(STRING, A),
illegalAssignment(STRING, BLOB_ARRAY),
illegalAssignment(STRING, BOOL_ARRAY),
illegalAssignment(STRING, NOTHING_ARRAY),
illegalAssignment(STRING, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRING, STRING_ARRAY),
illegalAssignment(STRING, A_ARRAY),
illegalAssignment(STRING, BLOB_ARRAY2),
illegalAssignment(STRING, BOOL_ARRAY2),
illegalAssignment(STRING, NOTHING_ARRAY2),
illegalAssignment(STRING, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRING, STRING_ARRAY2),
illegalAssignment(STRING, A_ARRAY2),
// Struct
illegalAssignment(STRUCT_WITH_STRING, BLOB),
illegalAssignment(STRUCT_WITH_STRING, BOOL),
allowedAssignment(STRUCT_WITH_STRING, NOTHING),
illegalAssignment(STRUCT_WITH_STRING, STRING),
allowedAssignment(STRUCT_WITH_STRING, STRUCT_WITH_STRING),
illegalAssignment(STRUCT_WITH_STRING, A),
illegalAssignment(STRUCT_WITH_STRING, BLOB_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, BOOL_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, NOTHING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, A_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, BLOB_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, BOOL_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, NOTHING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, A_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_BOOL),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_BOOL_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_BOOL_ARRAY2),
// [A]
illegalAssignment(A_ARRAY, BLOB),
illegalAssignment(A_ARRAY, BOOL),
allowedAssignment(A_ARRAY, NOTHING),
illegalAssignment(A_ARRAY, STRING),
illegalAssignment(A_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(A_ARRAY, A),
illegalAssignment(A_ARRAY, B),
illegalAssignment(A_ARRAY, BLOB_ARRAY),
illegalAssignment(A_ARRAY, BOOL_ARRAY),
allowedAssignment(A_ARRAY, NOTHING_ARRAY),
illegalAssignment(A_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(A_ARRAY, STRING_ARRAY),
allowedAssignment(A_ARRAY, A_ARRAY),
illegalAssignment(A_ARRAY, B_ARRAY),
illegalAssignment(A_ARRAY, BLOB_ARRAY2),
illegalAssignment(A_ARRAY, BOOL_ARRAY2),
illegalAssignment(A_ARRAY, NOTHING_ARRAY2),
illegalAssignment(A_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(A_ARRAY, STRING_ARRAY2),
illegalAssignment(A_ARRAY, A_ARRAY2),
illegalAssignment(A_ARRAY, B_ARRAY2),
// [Blob]
illegalAssignment(BLOB_ARRAY, BLOB),
illegalAssignment(BLOB_ARRAY, BOOL),
allowedAssignment(BLOB_ARRAY, NOTHING),
illegalAssignment(BLOB_ARRAY, STRING),
illegalAssignment(BLOB_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(BLOB_ARRAY, A),
allowedAssignment(BLOB_ARRAY, BLOB_ARRAY),
illegalAssignment(BLOB_ARRAY, BOOL_ARRAY),
allowedAssignment(BLOB_ARRAY, NOTHING_ARRAY),
illegalAssignment(BLOB_ARRAY, STRING_ARRAY),
illegalAssignment(BLOB_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BLOB_ARRAY, A_ARRAY),
illegalAssignment(BLOB_ARRAY, BLOB_ARRAY2),
illegalAssignment(BLOB_ARRAY, BOOL_ARRAY2),
illegalAssignment(BLOB_ARRAY, NOTHING_ARRAY2),
illegalAssignment(BLOB_ARRAY, STRING_ARRAY2),
illegalAssignment(BLOB_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BLOB_ARRAY, A_ARRAY2),
// [Bool]
illegalAssignment(BOOL_ARRAY, BLOB),
illegalAssignment(BOOL_ARRAY, BOOL),
allowedAssignment(BOOL_ARRAY, NOTHING),
illegalAssignment(BOOL_ARRAY, STRING),
illegalAssignment(BOOL_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(BOOL_ARRAY, A),
illegalAssignment(BOOL_ARRAY, BLOB_ARRAY),
allowedAssignment(BOOL_ARRAY, BOOL_ARRAY),
allowedAssignment(BOOL_ARRAY, NOTHING_ARRAY),
illegalAssignment(BOOL_ARRAY, STRING_ARRAY),
illegalAssignment(BOOL_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BOOL_ARRAY, A_ARRAY),
illegalAssignment(BOOL_ARRAY, BLOB_ARRAY2),
illegalAssignment(BOOL_ARRAY, BOOL_ARRAY2),
illegalAssignment(BOOL_ARRAY, NOTHING_ARRAY2),
illegalAssignment(BOOL_ARRAY, STRING_ARRAY2),
illegalAssignment(BOOL_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BOOL_ARRAY, A_ARRAY2),
// [Nothing]
illegalAssignment(NOTHING_ARRAY, BLOB),
illegalAssignment(NOTHING_ARRAY, BOOL),
allowedAssignment(NOTHING_ARRAY, NOTHING),
illegalAssignment(NOTHING_ARRAY, STRING),
illegalAssignment(NOTHING_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(NOTHING_ARRAY, A),
illegalAssignment(NOTHING_ARRAY, BLOB_ARRAY),
illegalAssignment(NOTHING_ARRAY, BOOL_ARRAY),
allowedAssignment(NOTHING_ARRAY, NOTHING_ARRAY),
illegalAssignment(NOTHING_ARRAY, STRING_ARRAY),
illegalAssignment(NOTHING_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(NOTHING_ARRAY, A_ARRAY),
illegalAssignment(NOTHING_ARRAY, BLOB_ARRAY2),
illegalAssignment(NOTHING_ARRAY, BOOL_ARRAY2),
illegalAssignment(NOTHING_ARRAY, NOTHING_ARRAY2),
illegalAssignment(NOTHING_ARRAY, STRING_ARRAY2),
illegalAssignment(NOTHING_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(NOTHING_ARRAY, A_ARRAY2),
// [String]
illegalAssignment(STRING_ARRAY, BLOB),
illegalAssignment(STRING_ARRAY, BOOL),
allowedAssignment(STRING_ARRAY, NOTHING),
illegalAssignment(STRING_ARRAY, STRING),
illegalAssignment(STRING_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(STRING_ARRAY, A),
illegalAssignment(STRING_ARRAY, BLOB_ARRAY),
illegalAssignment(STRING_ARRAY, BOOL_ARRAY),
allowedAssignment(STRING_ARRAY, NOTHING_ARRAY),
allowedAssignment(STRING_ARRAY, STRING_ARRAY),
allowedAssignment(STRING_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRING_ARRAY, A_ARRAY),
illegalAssignment(STRING_ARRAY, BLOB_ARRAY2),
illegalAssignment(STRING_ARRAY, BOOL_ARRAY2),
illegalAssignment(STRING_ARRAY, NOTHING_ARRAY2),
illegalAssignment(STRING_ARRAY, STRING_ARRAY2),
illegalAssignment(STRING_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRING_ARRAY, A_ARRAY2),
// [Struct]
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BLOB),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BOOL),
allowedAssignment(STRUCT_WITH_STRING_ARRAY, NOTHING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, A),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BLOB_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BOOL_ARRAY),
allowedAssignment(STRUCT_WITH_STRING_ARRAY, NOTHING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRING_ARRAY),
allowedAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, A_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BLOB_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BOOL_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, NOTHING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, A_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_BOOL),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_BOOL_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_BOOL_ARRAY2),
// [[A]]
illegalAssignment(A_ARRAY2, BLOB),
illegalAssignment(A_ARRAY2, BOOL),
allowedAssignment(A_ARRAY2, NOTHING),
illegalAssignment(A_ARRAY2, STRING),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(A_ARRAY2, A),
illegalAssignment(A_ARRAY2, B),
illegalAssignment(A_ARRAY2, BLOB_ARRAY),
illegalAssignment(A_ARRAY2, BOOL_ARRAY),
allowedAssignment(A_ARRAY2, NOTHING_ARRAY),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(A_ARRAY2, STRING_ARRAY),
illegalAssignment(A_ARRAY2, A_ARRAY),
illegalAssignment(A_ARRAY2, B_ARRAY),
illegalAssignment(A_ARRAY2, BLOB_ARRAY2),
illegalAssignment(A_ARRAY2, BOOL_ARRAY2),
allowedAssignment(A_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(A_ARRAY2, STRING_ARRAY2),
allowedAssignment(A_ARRAY2, A_ARRAY2),
illegalAssignment(A_ARRAY2, B_ARRAY2),
// [[Blob]]
illegalAssignment(BLOB_ARRAY2, BLOB),
illegalAssignment(BLOB_ARRAY2, BOOL),
allowedAssignment(BLOB_ARRAY2, NOTHING),
illegalAssignment(BLOB_ARRAY2, STRING),
illegalAssignment(BLOB_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(BLOB_ARRAY2, A),
illegalAssignment(BLOB_ARRAY2, BLOB_ARRAY),
illegalAssignment(BLOB_ARRAY2, BOOL_ARRAY),
allowedAssignment(BLOB_ARRAY2, NOTHING_ARRAY),
illegalAssignment(BLOB_ARRAY2, STRING_ARRAY),
illegalAssignment(BLOB_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BLOB_ARRAY2, A_ARRAY),
allowedAssignment(BLOB_ARRAY2, BLOB_ARRAY2),
illegalAssignment(BLOB_ARRAY2, BOOL_ARRAY2),
allowedAssignment(BLOB_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(BLOB_ARRAY2, STRING_ARRAY2),
illegalAssignment(BLOB_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BLOB_ARRAY2, A_ARRAY2),
// [[Bool]]
illegalAssignment(BOOL_ARRAY2, BLOB),
illegalAssignment(BOOL_ARRAY2, BOOL),
allowedAssignment(BOOL_ARRAY2, NOTHING),
illegalAssignment(BOOL_ARRAY2, STRING),
illegalAssignment(BOOL_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(BOOL_ARRAY2, A),
illegalAssignment(BOOL_ARRAY2, BLOB_ARRAY),
illegalAssignment(BOOL_ARRAY2, BOOL_ARRAY),
allowedAssignment(BOOL_ARRAY2, NOTHING_ARRAY),
illegalAssignment(BOOL_ARRAY2, STRING_ARRAY),
illegalAssignment(BOOL_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BOOL_ARRAY2, A_ARRAY),
illegalAssignment(BOOL_ARRAY2, BLOB_ARRAY2),
allowedAssignment(BOOL_ARRAY2, BOOL_ARRAY2),
allowedAssignment(BOOL_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(BOOL_ARRAY2, STRING_ARRAY2),
illegalAssignment(BOOL_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BOOL_ARRAY2, A_ARRAY2),
// [[Nothing]]
illegalAssignment(NOTHING_ARRAY2, BLOB),
illegalAssignment(NOTHING_ARRAY2, BOOL),
allowedAssignment(NOTHING_ARRAY2, NOTHING),
illegalAssignment(NOTHING_ARRAY2, STRING),
illegalAssignment(NOTHING_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(NOTHING_ARRAY2, A),
illegalAssignment(NOTHING_ARRAY2, BLOB_ARRAY),
illegalAssignment(NOTHING_ARRAY2, BOOL_ARRAY),
allowedAssignment(NOTHING_ARRAY2, NOTHING_ARRAY),
illegalAssignment(NOTHING_ARRAY2, STRING_ARRAY),
illegalAssignment(NOTHING_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(NOTHING_ARRAY2, A_ARRAY),
illegalAssignment(NOTHING_ARRAY2, BLOB_ARRAY2),
illegalAssignment(NOTHING_ARRAY2, BOOL_ARRAY2),
allowedAssignment(NOTHING_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(NOTHING_ARRAY2, STRING_ARRAY2),
illegalAssignment(NOTHING_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(NOTHING_ARRAY2, A_ARRAY2),
// [[String]]
illegalAssignment(STRING_ARRAY2, BLOB),
illegalAssignment(STRING_ARRAY2, BOOL),
allowedAssignment(STRING_ARRAY2, NOTHING),
illegalAssignment(STRING_ARRAY2, STRING),
illegalAssignment(STRING_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(STRING_ARRAY2, A),
illegalAssignment(STRING_ARRAY2, BLOB_ARRAY),
illegalAssignment(STRING_ARRAY2, BOOL_ARRAY),
allowedAssignment(STRING_ARRAY2, NOTHING_ARRAY),
illegalAssignment(STRING_ARRAY2, STRING_ARRAY),
illegalAssignment(STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRING_ARRAY2, A_ARRAY),
illegalAssignment(STRING_ARRAY2, BLOB_ARRAY2),
illegalAssignment(STRING_ARRAY2, BOOL_ARRAY2),
allowedAssignment(STRING_ARRAY2, NOTHING_ARRAY2),
allowedAssignment(STRING_ARRAY2, STRING_ARRAY2),
allowedAssignment(STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRING_ARRAY2, A_ARRAY2),
// [[Struct]]
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BLOB),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BOOL),
allowedAssignment(STRUCT_WITH_STRING_ARRAY2, NOTHING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, A),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BLOB_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BOOL_ARRAY),
allowedAssignment(STRUCT_WITH_STRING_ARRAY2, NOTHING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, A_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BLOB_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BOOL_ARRAY2),
allowedAssignment(STRUCT_WITH_STRING_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRING_ARRAY2),
allowedAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, A_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_BOOL),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_BOOL_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_BOOL_ARRAY2)
);
}
public static List<TestedAssignmentSpec> parameter_assignment_test_specs() {
ArrayList<TestedAssignmentSpec> result = new ArrayList<>();
result.addAll(assignment_without_generics_test_specs());
result.addAll(parameter_assignment_generic_test_specs());
return result;
}
public static List<TestedAssignmentSpec> assignment_without_generics_test_specs() {
return assignment_test_specs()
.stream()
.filter(a -> !(a.target.type().isGeneric() || a.source.type().isGeneric()))
.collect(toList());
}
private static List<TestedAssignmentSpec> parameter_assignment_generic_test_specs() {
return List.of(
allowedAssignment(A, STRING),
allowedAssignment(A, STRUCT_WITH_STRING),
allowedAssignment(A, NOTHING),
allowedAssignment(A, A),
allowedAssignment(A, B),
allowedAssignment(A, STRING_ARRAY),
allowedAssignment(A, STRUCT_WITH_STRING_ARRAY),
allowedAssignment(A, NOTHING_ARRAY),
allowedAssignment(A, A_ARRAY),
allowedAssignment(A, B_ARRAY),
allowedAssignment(A, STRING_ARRAY2),
allowedAssignment(A, STRUCT_WITH_STRING_ARRAY2),
allowedAssignment(A, NOTHING_ARRAY2),
allowedAssignment(A, A_ARRAY2),
allowedAssignment(A, B_ARRAY2),
illegalAssignment(A_ARRAY, STRING),
illegalAssignment(A_ARRAY, STRUCT_WITH_STRING),
allowedAssignment(A_ARRAY, NOTHING),
illegalAssignment(A_ARRAY, A),
illegalAssignment(A_ARRAY, B),
allowedAssignment(A_ARRAY, STRING_ARRAY),
allowedAssignment(A_ARRAY, STRUCT_WITH_STRING_ARRAY),
allowedAssignment(A_ARRAY, NOTHING_ARRAY),
allowedAssignment(A_ARRAY, A_ARRAY),
allowedAssignment(A_ARRAY, B_ARRAY),
allowedAssignment(A_ARRAY, STRING_ARRAY2),
allowedAssignment(A_ARRAY, STRUCT_WITH_STRING_ARRAY2),
allowedAssignment(A_ARRAY, NOTHING_ARRAY2),
allowedAssignment(A_ARRAY, A_ARRAY2),
allowedAssignment(A_ARRAY, B_ARRAY2),
illegalAssignment(A_ARRAY2, STRING),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING),
allowedAssignment(A_ARRAY2, NOTHING),
illegalAssignment(A_ARRAY2, A),
illegalAssignment(A_ARRAY2, B),
illegalAssignment(A_ARRAY2, STRING_ARRAY),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING_ARRAY),
allowedAssignment(A_ARRAY2, NOTHING_ARRAY),
illegalAssignment(A_ARRAY2, A_ARRAY),
illegalAssignment(A_ARRAY2, B_ARRAY),
allowedAssignment(A_ARRAY2, STRING_ARRAY2),
allowedAssignment(A_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
allowedAssignment(A_ARRAY2, NOTHING_ARRAY2),
allowedAssignment(A_ARRAY2, A_ARRAY2),
allowedAssignment(A_ARRAY2, B_ARRAY2));
}
}
| src/testing/java/org/smoothbuild/lang/base/type/TestedAssignmentSpec.java | package org.smoothbuild.lang.base.type;
import static java.util.stream.Collectors.toList;
import static org.smoothbuild.lang.base.type.TestedType.A;
import static org.smoothbuild.lang.base.type.TestedType.A_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.A_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.B;
import static org.smoothbuild.lang.base.type.TestedType.BLOB;
import static org.smoothbuild.lang.base.type.TestedType.BLOB_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.BLOB_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.BOOL;
import static org.smoothbuild.lang.base.type.TestedType.BOOL_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.BOOL_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.B_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.B_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.NOTHING;
import static org.smoothbuild.lang.base.type.TestedType.NOTHING_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.NOTHING_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.STRING;
import static org.smoothbuild.lang.base.type.TestedType.STRING_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.STRING_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_BOOL;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_BOOL_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_BOOL_ARRAY2;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_STRING;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_STRING_ARRAY;
import static org.smoothbuild.lang.base.type.TestedType.STRUCT_WITH_STRING_ARRAY2;
import java.util.ArrayList;
import java.util.List;
public class TestedAssignmentSpec extends TestedAssignment {
public final boolean allowed;
public TestedAssignmentSpec(TestedAssignment assignment, boolean allowed) {
super(assignment.target, assignment.source);
this.allowed = allowed;
}
TestedAssignmentSpec(TestedType target, TestedType source, boolean allowed) {
super(target, source);
this.allowed = allowed;
}
public static TestedAssignmentSpec illegalAssignment(TestedType target, TestedType source) {
return new TestedAssignmentSpec(target, source, false);
}
public static TestedAssignmentSpec allowedAssignment(TestedType target, TestedType source) {
return new TestedAssignmentSpec(target, source, true);
}
public static List<TestedAssignmentSpec> assignment_without_generics_test_specs() {
return assignment_test_specs()
.stream()
.filter(a -> !(a.target.type().isGeneric() || a.source.type().isGeneric()))
.collect(toList());
}
public static List<TestedAssignmentSpec> assignment_test_specs() {
return List.of(
// A
illegalAssignment(A, BLOB),
illegalAssignment(A, BOOL),
allowedAssignment(A, NOTHING),
illegalAssignment(A, STRING),
illegalAssignment(A, STRUCT_WITH_STRING),
allowedAssignment(A, A),
illegalAssignment(A, B),
illegalAssignment(A, BLOB_ARRAY),
illegalAssignment(A, BOOL_ARRAY),
illegalAssignment(A, NOTHING_ARRAY),
illegalAssignment(A, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(A, STRING_ARRAY),
illegalAssignment(A, A_ARRAY),
illegalAssignment(A, B_ARRAY),
illegalAssignment(A, BLOB_ARRAY2),
illegalAssignment(A, BOOL_ARRAY2),
illegalAssignment(A, NOTHING_ARRAY2),
illegalAssignment(A, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(A, STRING_ARRAY2),
illegalAssignment(A, A_ARRAY2),
illegalAssignment(A, B_ARRAY2),
// Blob
allowedAssignment(BLOB, BLOB),
illegalAssignment(BLOB, BOOL),
allowedAssignment(BLOB, NOTHING),
illegalAssignment(BLOB, STRING),
illegalAssignment(BLOB, STRUCT_WITH_STRING),
illegalAssignment(BLOB, A),
illegalAssignment(BLOB, BLOB_ARRAY),
illegalAssignment(BLOB, BOOL_ARRAY),
illegalAssignment(BLOB, NOTHING_ARRAY),
illegalAssignment(BLOB, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BLOB, STRING_ARRAY),
illegalAssignment(BLOB, A_ARRAY),
illegalAssignment(BLOB, BLOB_ARRAY2),
illegalAssignment(BLOB, BOOL_ARRAY2),
illegalAssignment(BLOB, NOTHING_ARRAY2),
illegalAssignment(BLOB, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BLOB, STRING_ARRAY2),
illegalAssignment(BLOB, A_ARRAY2),
// Bool
illegalAssignment(BOOL, BLOB),
allowedAssignment(BOOL, BOOL),
allowedAssignment(BOOL, NOTHING),
illegalAssignment(BOOL, STRING),
illegalAssignment(BOOL, STRUCT_WITH_STRING),
illegalAssignment(BOOL, A),
illegalAssignment(BOOL, BLOB_ARRAY),
illegalAssignment(BOOL, BOOL_ARRAY),
illegalAssignment(BOOL, NOTHING_ARRAY),
illegalAssignment(BOOL, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BOOL, STRING_ARRAY),
illegalAssignment(BOOL, A_ARRAY),
illegalAssignment(BOOL, BLOB_ARRAY2),
illegalAssignment(BOOL, BOOL_ARRAY2),
illegalAssignment(BOOL, NOTHING_ARRAY2),
illegalAssignment(BOOL, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BOOL, STRING_ARRAY2),
illegalAssignment(BOOL, A_ARRAY2),
// Nothing
illegalAssignment(NOTHING, BLOB),
illegalAssignment(NOTHING, BOOL),
allowedAssignment(NOTHING, NOTHING),
illegalAssignment(NOTHING, STRING),
illegalAssignment(NOTHING, STRUCT_WITH_STRING),
illegalAssignment(NOTHING, A),
illegalAssignment(NOTHING, BLOB_ARRAY),
illegalAssignment(NOTHING, BOOL_ARRAY),
illegalAssignment(NOTHING, NOTHING_ARRAY),
illegalAssignment(NOTHING, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(NOTHING, STRING_ARRAY),
illegalAssignment(NOTHING, A_ARRAY),
illegalAssignment(NOTHING, BLOB_ARRAY2),
illegalAssignment(NOTHING, BOOL_ARRAY2),
illegalAssignment(NOTHING, NOTHING_ARRAY2),
illegalAssignment(NOTHING, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(NOTHING, STRING_ARRAY2),
illegalAssignment(NOTHING, A_ARRAY2),
// String
illegalAssignment(STRING, BLOB),
illegalAssignment(STRING, BOOL),
allowedAssignment(STRING, NOTHING),
allowedAssignment(STRING, STRING),
allowedAssignment(STRING, STRUCT_WITH_STRING),
illegalAssignment(STRING, A),
illegalAssignment(STRING, BLOB_ARRAY),
illegalAssignment(STRING, BOOL_ARRAY),
illegalAssignment(STRING, NOTHING_ARRAY),
illegalAssignment(STRING, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRING, STRING_ARRAY),
illegalAssignment(STRING, A_ARRAY),
illegalAssignment(STRING, BLOB_ARRAY2),
illegalAssignment(STRING, BOOL_ARRAY2),
illegalAssignment(STRING, NOTHING_ARRAY2),
illegalAssignment(STRING, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRING, STRING_ARRAY2),
illegalAssignment(STRING, A_ARRAY2),
// Struct
illegalAssignment(STRUCT_WITH_STRING, BLOB),
illegalAssignment(STRUCT_WITH_STRING, BOOL),
allowedAssignment(STRUCT_WITH_STRING, NOTHING),
illegalAssignment(STRUCT_WITH_STRING, STRING),
allowedAssignment(STRUCT_WITH_STRING, STRUCT_WITH_STRING),
illegalAssignment(STRUCT_WITH_STRING, A),
illegalAssignment(STRUCT_WITH_STRING, BLOB_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, BOOL_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, NOTHING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, A_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, BLOB_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, BOOL_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, NOTHING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, A_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_BOOL),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_BOOL_ARRAY),
illegalAssignment(STRUCT_WITH_STRING, STRUCT_WITH_BOOL_ARRAY2),
// [A]
illegalAssignment(A_ARRAY, BLOB),
illegalAssignment(A_ARRAY, BOOL),
allowedAssignment(A_ARRAY, NOTHING),
illegalAssignment(A_ARRAY, STRING),
illegalAssignment(A_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(A_ARRAY, A),
illegalAssignment(A_ARRAY, B),
illegalAssignment(A_ARRAY, BLOB_ARRAY),
illegalAssignment(A_ARRAY, BOOL_ARRAY),
allowedAssignment(A_ARRAY, NOTHING_ARRAY),
illegalAssignment(A_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(A_ARRAY, STRING_ARRAY),
allowedAssignment(A_ARRAY, A_ARRAY),
illegalAssignment(A_ARRAY, B_ARRAY),
illegalAssignment(A_ARRAY, BLOB_ARRAY2),
illegalAssignment(A_ARRAY, BOOL_ARRAY2),
illegalAssignment(A_ARRAY, NOTHING_ARRAY2),
illegalAssignment(A_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(A_ARRAY, STRING_ARRAY2),
illegalAssignment(A_ARRAY, A_ARRAY2),
illegalAssignment(A_ARRAY, B_ARRAY2),
// [Blob]
illegalAssignment(BLOB_ARRAY, BLOB),
illegalAssignment(BLOB_ARRAY, BOOL),
allowedAssignment(BLOB_ARRAY, NOTHING),
illegalAssignment(BLOB_ARRAY, STRING),
illegalAssignment(BLOB_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(BLOB_ARRAY, A),
allowedAssignment(BLOB_ARRAY, BLOB_ARRAY),
illegalAssignment(BLOB_ARRAY, BOOL_ARRAY),
allowedAssignment(BLOB_ARRAY, NOTHING_ARRAY),
illegalAssignment(BLOB_ARRAY, STRING_ARRAY),
illegalAssignment(BLOB_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BLOB_ARRAY, A_ARRAY),
illegalAssignment(BLOB_ARRAY, BLOB_ARRAY2),
illegalAssignment(BLOB_ARRAY, BOOL_ARRAY2),
illegalAssignment(BLOB_ARRAY, NOTHING_ARRAY2),
illegalAssignment(BLOB_ARRAY, STRING_ARRAY2),
illegalAssignment(BLOB_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BLOB_ARRAY, A_ARRAY2),
// [Bool]
illegalAssignment(BOOL_ARRAY, BLOB),
illegalAssignment(BOOL_ARRAY, BOOL),
allowedAssignment(BOOL_ARRAY, NOTHING),
illegalAssignment(BOOL_ARRAY, STRING),
illegalAssignment(BOOL_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(BOOL_ARRAY, A),
illegalAssignment(BOOL_ARRAY, BLOB_ARRAY),
allowedAssignment(BOOL_ARRAY, BOOL_ARRAY),
allowedAssignment(BOOL_ARRAY, NOTHING_ARRAY),
illegalAssignment(BOOL_ARRAY, STRING_ARRAY),
illegalAssignment(BOOL_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BOOL_ARRAY, A_ARRAY),
illegalAssignment(BOOL_ARRAY, BLOB_ARRAY2),
illegalAssignment(BOOL_ARRAY, BOOL_ARRAY2),
illegalAssignment(BOOL_ARRAY, NOTHING_ARRAY2),
illegalAssignment(BOOL_ARRAY, STRING_ARRAY2),
illegalAssignment(BOOL_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BOOL_ARRAY, A_ARRAY2),
// [Nothing]
illegalAssignment(NOTHING_ARRAY, BLOB),
illegalAssignment(NOTHING_ARRAY, BOOL),
allowedAssignment(NOTHING_ARRAY, NOTHING),
illegalAssignment(NOTHING_ARRAY, STRING),
illegalAssignment(NOTHING_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(NOTHING_ARRAY, A),
illegalAssignment(NOTHING_ARRAY, BLOB_ARRAY),
illegalAssignment(NOTHING_ARRAY, BOOL_ARRAY),
allowedAssignment(NOTHING_ARRAY, NOTHING_ARRAY),
illegalAssignment(NOTHING_ARRAY, STRING_ARRAY),
illegalAssignment(NOTHING_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(NOTHING_ARRAY, A_ARRAY),
illegalAssignment(NOTHING_ARRAY, BLOB_ARRAY2),
illegalAssignment(NOTHING_ARRAY, BOOL_ARRAY2),
illegalAssignment(NOTHING_ARRAY, NOTHING_ARRAY2),
illegalAssignment(NOTHING_ARRAY, STRING_ARRAY2),
illegalAssignment(NOTHING_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(NOTHING_ARRAY, A_ARRAY2),
// [String]
illegalAssignment(STRING_ARRAY, BLOB),
illegalAssignment(STRING_ARRAY, BOOL),
allowedAssignment(STRING_ARRAY, NOTHING),
illegalAssignment(STRING_ARRAY, STRING),
illegalAssignment(STRING_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(STRING_ARRAY, A),
illegalAssignment(STRING_ARRAY, BLOB_ARRAY),
illegalAssignment(STRING_ARRAY, BOOL_ARRAY),
allowedAssignment(STRING_ARRAY, NOTHING_ARRAY),
allowedAssignment(STRING_ARRAY, STRING_ARRAY),
allowedAssignment(STRING_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRING_ARRAY, A_ARRAY),
illegalAssignment(STRING_ARRAY, BLOB_ARRAY2),
illegalAssignment(STRING_ARRAY, BOOL_ARRAY2),
illegalAssignment(STRING_ARRAY, NOTHING_ARRAY2),
illegalAssignment(STRING_ARRAY, STRING_ARRAY2),
illegalAssignment(STRING_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRING_ARRAY, A_ARRAY2),
// [Struct]
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BLOB),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BOOL),
allowedAssignment(STRUCT_WITH_STRING_ARRAY, NOTHING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_STRING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, A),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BLOB_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BOOL_ARRAY),
allowedAssignment(STRUCT_WITH_STRING_ARRAY, NOTHING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRING_ARRAY),
allowedAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, A_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BLOB_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, BOOL_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, NOTHING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, A_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_BOOL),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_BOOL_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY, STRUCT_WITH_BOOL_ARRAY2),
// [[A]]
illegalAssignment(A_ARRAY2, BLOB),
illegalAssignment(A_ARRAY2, BOOL),
allowedAssignment(A_ARRAY2, NOTHING),
illegalAssignment(A_ARRAY2, STRING),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(A_ARRAY2, A),
illegalAssignment(A_ARRAY2, B),
illegalAssignment(A_ARRAY2, BLOB_ARRAY),
illegalAssignment(A_ARRAY2, BOOL_ARRAY),
allowedAssignment(A_ARRAY2, NOTHING_ARRAY),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(A_ARRAY2, STRING_ARRAY),
illegalAssignment(A_ARRAY2, A_ARRAY),
illegalAssignment(A_ARRAY2, B_ARRAY),
illegalAssignment(A_ARRAY2, BLOB_ARRAY2),
illegalAssignment(A_ARRAY2, BOOL_ARRAY2),
allowedAssignment(A_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(A_ARRAY2, STRING_ARRAY2),
allowedAssignment(A_ARRAY2, A_ARRAY2),
illegalAssignment(A_ARRAY2, B_ARRAY2),
// [[Blob]]
illegalAssignment(BLOB_ARRAY2, BLOB),
illegalAssignment(BLOB_ARRAY2, BOOL),
allowedAssignment(BLOB_ARRAY2, NOTHING),
illegalAssignment(BLOB_ARRAY2, STRING),
illegalAssignment(BLOB_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(BLOB_ARRAY2, A),
illegalAssignment(BLOB_ARRAY2, BLOB_ARRAY),
illegalAssignment(BLOB_ARRAY2, BOOL_ARRAY),
allowedAssignment(BLOB_ARRAY2, NOTHING_ARRAY),
illegalAssignment(BLOB_ARRAY2, STRING_ARRAY),
illegalAssignment(BLOB_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BLOB_ARRAY2, A_ARRAY),
allowedAssignment(BLOB_ARRAY2, BLOB_ARRAY2),
illegalAssignment(BLOB_ARRAY2, BOOL_ARRAY2),
allowedAssignment(BLOB_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(BLOB_ARRAY2, STRING_ARRAY2),
illegalAssignment(BLOB_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BLOB_ARRAY2, A_ARRAY2),
// [[Bool]]
illegalAssignment(BOOL_ARRAY2, BLOB),
illegalAssignment(BOOL_ARRAY2, BOOL),
allowedAssignment(BOOL_ARRAY2, NOTHING),
illegalAssignment(BOOL_ARRAY2, STRING),
illegalAssignment(BOOL_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(BOOL_ARRAY2, A),
illegalAssignment(BOOL_ARRAY2, BLOB_ARRAY),
illegalAssignment(BOOL_ARRAY2, BOOL_ARRAY),
allowedAssignment(BOOL_ARRAY2, NOTHING_ARRAY),
illegalAssignment(BOOL_ARRAY2, STRING_ARRAY),
illegalAssignment(BOOL_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(BOOL_ARRAY2, A_ARRAY),
illegalAssignment(BOOL_ARRAY2, BLOB_ARRAY2),
allowedAssignment(BOOL_ARRAY2, BOOL_ARRAY2),
allowedAssignment(BOOL_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(BOOL_ARRAY2, STRING_ARRAY2),
illegalAssignment(BOOL_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(BOOL_ARRAY2, A_ARRAY2),
// [[Nothing]]
illegalAssignment(NOTHING_ARRAY2, BLOB),
illegalAssignment(NOTHING_ARRAY2, BOOL),
allowedAssignment(NOTHING_ARRAY2, NOTHING),
illegalAssignment(NOTHING_ARRAY2, STRING),
illegalAssignment(NOTHING_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(NOTHING_ARRAY2, A),
illegalAssignment(NOTHING_ARRAY2, BLOB_ARRAY),
illegalAssignment(NOTHING_ARRAY2, BOOL_ARRAY),
allowedAssignment(NOTHING_ARRAY2, NOTHING_ARRAY),
illegalAssignment(NOTHING_ARRAY2, STRING_ARRAY),
illegalAssignment(NOTHING_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(NOTHING_ARRAY2, A_ARRAY),
illegalAssignment(NOTHING_ARRAY2, BLOB_ARRAY2),
illegalAssignment(NOTHING_ARRAY2, BOOL_ARRAY2),
allowedAssignment(NOTHING_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(NOTHING_ARRAY2, STRING_ARRAY2),
illegalAssignment(NOTHING_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(NOTHING_ARRAY2, A_ARRAY2),
// [[String]]
illegalAssignment(STRING_ARRAY2, BLOB),
illegalAssignment(STRING_ARRAY2, BOOL),
allowedAssignment(STRING_ARRAY2, NOTHING),
illegalAssignment(STRING_ARRAY2, STRING),
illegalAssignment(STRING_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(STRING_ARRAY2, A),
illegalAssignment(STRING_ARRAY2, BLOB_ARRAY),
illegalAssignment(STRING_ARRAY2, BOOL_ARRAY),
allowedAssignment(STRING_ARRAY2, NOTHING_ARRAY),
illegalAssignment(STRING_ARRAY2, STRING_ARRAY),
illegalAssignment(STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRING_ARRAY2, A_ARRAY),
illegalAssignment(STRING_ARRAY2, BLOB_ARRAY2),
illegalAssignment(STRING_ARRAY2, BOOL_ARRAY2),
allowedAssignment(STRING_ARRAY2, NOTHING_ARRAY2),
allowedAssignment(STRING_ARRAY2, STRING_ARRAY2),
allowedAssignment(STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRING_ARRAY2, A_ARRAY2),
// [[Struct]]
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BLOB),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BOOL),
allowedAssignment(STRUCT_WITH_STRING_ARRAY2, NOTHING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_STRING),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, A),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BLOB_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BOOL_ARRAY),
allowedAssignment(STRUCT_WITH_STRING_ARRAY2, NOTHING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, A_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BLOB_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, BOOL_ARRAY2),
allowedAssignment(STRUCT_WITH_STRING_ARRAY2, NOTHING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRING_ARRAY2),
allowedAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, A_ARRAY2),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_BOOL),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_BOOL_ARRAY),
illegalAssignment(STRUCT_WITH_STRING_ARRAY2, STRUCT_WITH_BOOL_ARRAY2)
);
}
public static List<TestedAssignmentSpec> parameter_assignment_test_specs() {
ArrayList<TestedAssignmentSpec> result = new ArrayList<>();
result.addAll(assignment_without_generics_test_specs());
result.addAll(parameter_assignment_generic_test_specs());
return result;
}
private static List<TestedAssignmentSpec> parameter_assignment_generic_test_specs() {
return List.of(
allowedAssignment(A, STRING),
allowedAssignment(A, STRUCT_WITH_STRING),
allowedAssignment(A, NOTHING),
allowedAssignment(A, A),
allowedAssignment(A, B),
allowedAssignment(A, STRING_ARRAY),
allowedAssignment(A, STRUCT_WITH_STRING_ARRAY),
allowedAssignment(A, NOTHING_ARRAY),
allowedAssignment(A, A_ARRAY),
allowedAssignment(A, B_ARRAY),
allowedAssignment(A, STRING_ARRAY2),
allowedAssignment(A, STRUCT_WITH_STRING_ARRAY2),
allowedAssignment(A, NOTHING_ARRAY2),
allowedAssignment(A, A_ARRAY2),
allowedAssignment(A, B_ARRAY2),
illegalAssignment(A_ARRAY, STRING),
illegalAssignment(A_ARRAY, STRUCT_WITH_STRING),
allowedAssignment(A_ARRAY, NOTHING),
illegalAssignment(A_ARRAY, A),
illegalAssignment(A_ARRAY, B),
allowedAssignment(A_ARRAY, STRING_ARRAY),
allowedAssignment(A_ARRAY, STRUCT_WITH_STRING_ARRAY),
allowedAssignment(A_ARRAY, NOTHING_ARRAY),
allowedAssignment(A_ARRAY, A_ARRAY),
allowedAssignment(A_ARRAY, B_ARRAY),
allowedAssignment(A_ARRAY, STRING_ARRAY2),
allowedAssignment(A_ARRAY, STRUCT_WITH_STRING_ARRAY2),
allowedAssignment(A_ARRAY, NOTHING_ARRAY2),
allowedAssignment(A_ARRAY, A_ARRAY2),
allowedAssignment(A_ARRAY, B_ARRAY2),
illegalAssignment(A_ARRAY2, STRING),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING),
allowedAssignment(A_ARRAY2, NOTHING),
illegalAssignment(A_ARRAY2, A),
illegalAssignment(A_ARRAY2, B),
illegalAssignment(A_ARRAY2, STRING_ARRAY),
illegalAssignment(A_ARRAY2, STRUCT_WITH_STRING_ARRAY),
allowedAssignment(A_ARRAY2, NOTHING_ARRAY),
illegalAssignment(A_ARRAY2, A_ARRAY),
illegalAssignment(A_ARRAY2, B_ARRAY),
allowedAssignment(A_ARRAY2, STRING_ARRAY2),
allowedAssignment(A_ARRAY2, STRUCT_WITH_STRING_ARRAY2),
allowedAssignment(A_ARRAY2, NOTHING_ARRAY2),
allowedAssignment(A_ARRAY2, A_ARRAY2),
allowedAssignment(A_ARRAY2, B_ARRAY2));
}
}
| reordered methods in TestedAssignmentSpec
| src/testing/java/org/smoothbuild/lang/base/type/TestedAssignmentSpec.java | reordered methods in TestedAssignmentSpec | <ide><path>rc/testing/java/org/smoothbuild/lang/base/type/TestedAssignmentSpec.java
<ide> return new TestedAssignmentSpec(target, source, true);
<ide> }
<ide>
<del> public static List<TestedAssignmentSpec> assignment_without_generics_test_specs() {
<del> return assignment_test_specs()
<del> .stream()
<del> .filter(a -> !(a.target.type().isGeneric() || a.source.type().isGeneric()))
<del> .collect(toList());
<del> }
<del>
<ide> public static List<TestedAssignmentSpec> assignment_test_specs() {
<ide> return List.of(
<ide> // A
<ide> result.addAll(assignment_without_generics_test_specs());
<ide> result.addAll(parameter_assignment_generic_test_specs());
<ide> return result;
<add> }
<add>
<add> public static List<TestedAssignmentSpec> assignment_without_generics_test_specs() {
<add> return assignment_test_specs()
<add> .stream()
<add> .filter(a -> !(a.target.type().isGeneric() || a.source.type().isGeneric()))
<add> .collect(toList());
<ide> }
<ide>
<ide> private static List<TestedAssignmentSpec> parameter_assignment_generic_test_specs() { |
|
Java | apache-2.0 | 0ef497a8834651d89cdba2feb8d2b695dcab8cef | 0 | fqdb/Hybrid-Homescreen | package fqdb.net.launcherproject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Appslistfragment extends Fragment implements OnStartDragListener {
private GridLayoutManager lLayout;
private PackageManager pm;
private ArrayList<AppDetail> apps;
private RecyclerView rView;
private ItemTouchHelper myItemTouchHelper;
private SharedPreferences prefs;
private SharedPreferences.Editor prefseditor;
private RecyclerView.OnItemTouchListener listener;
String query;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor prefseditor = prefs.edit();
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.appslistpage, container,
false);
final ArrayList<AppDetail> apps = getAppsList();
Set<String> appNamesSet = new HashSet<String>();
for (AppDetail app : apps) {
appNamesSet.add(app.name.toString());
}
prefseditor.putStringSet("app_names", appNamesSet);
prefseditor.apply();
// Remove hidden apps from recyclerview input
for (int i=0; i < apps.size(); i++) {
if (prefs.getBoolean(apps.get(i).name + "_ishidden",false)) {
apps.remove(i);
}
}
setRecyclerView(rootView);
EditText searchfield =(EditText) rootView.findViewById(R.id.search_field);
searchfield.addTextChangedListener(searchTextWatcher);
// Update drawer on package change
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
intentFilter.addDataScheme("package");
getActivity().registerReceiver(new AppReceiver(), intentFilter);
return rootView;
}
private ArrayList<AppDetail> getAppsList() {
pm = getActivity().getPackageManager();
apps = new ArrayList<AppDetail>();
Intent i = new Intent(Intent.ACTION_MAIN, null);
i.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> availableActivities = pm.queryIntentActivities(i, 0);
for(ResolveInfo ri:availableActivities){
AppDetail app = new AppDetail();
app.label = ri.loadLabel(pm);
app.name = ri.activityInfo.packageName;
app.icon = ri.activityInfo.loadIcon(pm);
apps.add(app);
}
Collections.sort(apps, new Comparator<AppDetail>() {
@Override
public int compare(AppDetail a1, AppDetail a2) {
// String implements Comparable
return (a1.label.toString()).compareTo(a2.label.toString());
}
});
return apps;
}
public void setRecyclerView(View rootView) {
// Move this to getApps() to allow easy refreshing, see Imma Wake P6
lLayout = new GridLayoutManager(rootView.getContext(), 4);
rView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayout);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(), apps);
rView.setAdapter(rcAdapter);
// Allow dragging:
ItemTouchHelper.Callback callback = new ItemTouchHelperCallback(rcAdapter);
myItemTouchHelper = new ItemTouchHelper(callback);
myItemTouchHelper.attachToRecyclerView(rView);
}
public final TextWatcher searchTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence query, int start, int before, int count) {
final ArrayList<AppDetail> filteredApps = filter(apps, query.toString());
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(), filteredApps);
rView.setAdapter(rcAdapter);
prefseditor = prefs.edit();
if (query != "") {prefseditor.putBoolean("void_query", false);}
else {prefseditor.putBoolean("void_query", true);}
}
@Override
public void afterTextChanged(Editable s) { }
};
private ArrayList<AppDetail> filter(ArrayList<AppDetail> apps, String query) {
query.toLowerCase().trim();
final ArrayList<AppDetail> filteredAppsList = new ArrayList<>();
for (AppDetail app : apps) {
final String text = app.label.toString().toLowerCase().trim();
if (text.contains(query)) {
filteredAppsList.add(app);
}
}
return filteredAppsList;
}
@Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
myItemTouchHelper.startDrag(viewHolder);
}
public class AppReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
}
| app/src/main/java/fqdb/net/launcherproject/Appslistfragment.java | package fqdb.net.launcherproject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Appslistfragment extends Fragment implements OnStartDragListener {
private GridLayoutManager lLayout;
private PackageManager pm;
private ArrayList<AppDetail> apps;
private RecyclerView rView;
private ItemTouchHelper myItemTouchHelper;
private SharedPreferences prefs;
private SharedPreferences.Editor prefseditor;
private RecyclerView.OnItemTouchListener listener;
String query;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor prefseditor = prefs.edit();
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.appslistpage, container,
false);
final ArrayList<AppDetail> apps = getAppsList();
Set<String> appNamesSet = new HashSet<String>();
for (AppDetail app : apps) {
appNamesSet.add(app.name.toString());
}
prefseditor.putStringSet("app_names", appNamesSet);
prefseditor.apply();
// Remove hidden apps from recyclerview input
for (int i=0; i < apps.size(); i++) {
if (prefs.getBoolean(apps.get(i).name + "_ishidden",false)) {
apps.remove(i);
}
}
setRecyclerView(rootView);
EditText searchfield =(EditText) rootView.findViewById(R.id.search_field);
searchfield.addTextChangedListener(searchTextWatcher);
// Update drawer on package change
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
intentFilter.addDataScheme("package");
getActivity().registerReceiver(new AppReceiver(), intentFilter);
return rootView;
}
private ArrayList<AppDetail> getAppsList() {
pm = getActivity().getPackageManager();
apps = new ArrayList<AppDetail>();
Intent i = new Intent(Intent.ACTION_MAIN, null);
i.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> availableActivities = pm.queryIntentActivities(i, 0);
for(ResolveInfo ri:availableActivities){
AppDetail app = new AppDetail();
app.label = ri.loadLabel(pm);
app.name = ri.activityInfo.packageName;
app.icon = ri.activityInfo.loadIcon(pm);
apps.add(app);
}
Collections.sort(apps, new Comparator<AppDetail>() {
@Override
public int compare(AppDetail a1, AppDetail a2) {
// String implements Comparable
return (a1.label.toString()).compareTo(a2.label.toString());
}
});
return apps;
}
public void setRecyclerView(View rootView) {
// Move this to getApps() to allow easy refreshing, see Imma Wake P6
lLayout = new GridLayoutManager(rootView.getContext(), 4);
rView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
rView.setHasFixedSize(true);
rView.setLayoutManager(lLayout);
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(), apps);
rView.setAdapter(rcAdapter);
ItemTouchHelper.Callback callback = new ItemTouchHelperCallback(rcAdapter);
myItemTouchHelper = new ItemTouchHelper(callback);
myItemTouchHelper.attachToRecyclerView(rView);
}
public final TextWatcher searchTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence query, int start, int before, int count) {
final ArrayList<AppDetail> filteredApps = filter(apps, query.toString());
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(), filteredApps);
rView.setAdapter(rcAdapter);
prefseditor = prefs.edit();
if (query != "") {prefseditor.putBoolean("void_query", false);}
else {prefseditor.putBoolean("void_query", true);}
}
@Override
public void afterTextChanged(Editable s) { }
};
private ArrayList<AppDetail> filter(ArrayList<AppDetail> apps, String query) {
query.toLowerCase().trim();
final ArrayList<AppDetail> filteredAppsList = new ArrayList<>();
for (AppDetail app : apps) {
final String text = app.label.toString().toLowerCase().trim();
if (text.contains(query)) {
filteredAppsList.add(app);
}
}
return filteredAppsList;
}
@Override
public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
myItemTouchHelper.startDrag(viewHolder);
}
public class AppReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
}
| minor fixes
| app/src/main/java/fqdb/net/launcherproject/Appslistfragment.java | minor fixes | <ide><path>pp/src/main/java/fqdb/net/launcherproject/Appslistfragment.java
<ide> rView.setLayoutManager(lLayout);
<ide> RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(getActivity(), apps);
<ide> rView.setAdapter(rcAdapter);
<add> // Allow dragging:
<ide> ItemTouchHelper.Callback callback = new ItemTouchHelperCallback(rcAdapter);
<ide> myItemTouchHelper = new ItemTouchHelper(callback);
<ide> myItemTouchHelper.attachToRecyclerView(rView); |
|
Java | apache-2.0 | aebdd5fd9743be2274d685a016f303942952b2ca | 0 | burris/dwr,burris/dwr | /*
* Copyright 2005 Joe Walker
*
* 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.
*/
package org.directwebremoting.impl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.servlet.Servlet;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.directwebremoting.Container;
import org.directwebremoting.extend.ContainerConfigurationException;
import org.directwebremoting.util.LocalUtil;
/**
* DefaultContainer is like a mini-IoC container for DWR.
* At least it is an IoC container by interface (check: no params that have
* anything to do with DWR), but it is hard coded specifically for DWR. If we
* want to make more of it we can later, but this is certainly not going to
* become a full blown IoC container.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class DefaultContainer extends AbstractContainer implements Container
{
/**
* Set the class that should be used to implement the given interface
* @param askFor The interface to implement
* @param valueParam The new implementation
* @throws ContainerConfigurationException If the specified beans could not be used
*/
public void addParameter(String askFor, Object valueParam) throws ContainerConfigurationException
{
Object value = valueParam;
// Maybe the value is a classname that needs instantiating
if (value instanceof String)
{
try
{
Class<?> impl = LocalUtil.classForName((String) value);
value = impl.newInstance();
}
catch (ClassNotFoundException ex)
{
// it's not a classname, leave it
}
catch (InstantiationException ex)
{
throw new ContainerConfigurationException("Unable to instantiate " + value);
}
catch (IllegalAccessException ex)
{
throw new ContainerConfigurationException("Unable to access " + value);
}
}
// If we have an instantiated value object and askFor is an interface
// then we can check that one implements the other
if (!(value instanceof String))
{
try
{
Class<?> iface = LocalUtil.classForName(askFor);
if (!iface.isAssignableFrom(value.getClass()))
{
log.error("Can't cast: " + value + " to " + askFor);
}
}
catch (ClassNotFoundException ex)
{
// it's not a classname, leave it
}
}
if (log.isDebugEnabled())
{
if (value instanceof String)
{
log.debug("Adding IoC setting: " + askFor + "=" + value);
}
else
{
log.debug("Adding IoC implementation: " + askFor + "=" + value.getClass().getName());
}
}
beans.put(askFor, value);
}
/**
* Retrieve a previously set parameter
* @param name The parameter name to retrieve
* @return The value of the specified parameter, or null if one is not set
*/
public String getParameter(String name)
{
Object value = beans.get(name);
return (value == null) ? null : value.toString();
}
/**
* Called to indicate that we finished adding parameters.
* The thread safety of a large part of DWR depends on this function only
* being called from {@link Servlet#init(javax.servlet.ServletConfig)},
* where all the setup is done, and where we depend on the undocumented
* feature of all servlet containers that they complete the init process
* of a Servlet before they begin servicing requests.
* @see DefaultContainer#addParameter(String, Object)
* @noinspection UnnecessaryLabelOnContinueStatement
*/
public void setupFinished()
{
// We try to autowire each bean in turn
for (Entry<String, Object> entry : beans.entrySet())
{
// Class type = (Class) entry.getKey();
Object ovalue = entry.getValue();
if (!(ovalue instanceof String))
{
log.debug("Trying to autowire: " + ovalue.getClass().getName());
Method[] methods = ovalue.getClass().getMethods();
methods:
for (Method setter : methods)
{
if (setter.getName().startsWith("set") &&
setter.getName().length() > 3 &&
setter.getParameterTypes().length == 1)
{
String name = Character.toLowerCase(setter.getName().charAt(3)) + setter.getName().substring(4);
Class<?> propertyType = setter.getParameterTypes()[0];
// First we try auto-wire by name
Object setting = beans.get(name);
if (setting != null)
{
if (propertyType.isAssignableFrom(setting.getClass()))
{
log.debug("- autowire-by-name: " + name + "=" + setting);
invoke(setter, ovalue, setting);
continue methods;
}
else if (setting.getClass() == String.class)
{
try
{
Object value = LocalUtil.simpleConvert((String) setting, propertyType);
log.debug("- autowire-by-name: " + name + "=" + value);
invoke(setter, ovalue, value);
}
catch (IllegalArgumentException ex)
{
// Ignore - this was a speculative convert anyway
}
continue methods;
}
}
// Next we try autowire-by-type
Object value = beans.get(propertyType.getName());
if (value != null)
{
log.debug("- autowire-by-type: " + name + "=" + value.getClass().getName());
invoke(setter, ovalue, value);
continue methods;
}
log.debug("- skipped autowire: " + name);
}
}
}
}
callInitializingBeans();
}
/**
* A helper to do the reflection.
* This helper throws away all exceptions, preferring to log.
* @param setter The method to invoke
* @param bean The object to invoke the method on
* @param value The value to assign to the property using the setter method
*/
private static void invoke(Method setter, Object bean, Object value)
{
try
{
setter.invoke(bean, value);
}
catch (IllegalArgumentException ex)
{
log.error("- Internal error: " + ex.getMessage());
}
catch (IllegalAccessException ex)
{
log.error("- Permission error: " + ex.getMessage());
}
catch (InvocationTargetException ex)
{
log.error("- Exception during auto-wire: ", ex.getTargetException());
}
}
/* (non-Javadoc)
* @see org.directwebremoting.Container#getBean(java.lang.String)
*/
public Object getBean(String id)
{
return beans.get(id);
}
/* (non-Javadoc)
* @see org.directwebremoting.Container#getBeanNames()
*/
public Collection<String> getBeanNames()
{
return Collections.unmodifiableCollection(beans.keySet());
}
/**
* The beans that we know of indexed by type
*/
protected Map<String, Object> beans = new TreeMap<String, Object>();
/**
* The log stream
*/
private static final Log log = LogFactory.getLog(DefaultContainer.class);
}
| java/org/directwebremoting/impl/DefaultContainer.java | /*
* Copyright 2005 Joe Walker
*
* 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.
*/
package org.directwebremoting.impl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.servlet.Servlet;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.directwebremoting.Container;
import org.directwebremoting.extend.ContainerConfigurationException;
import org.directwebremoting.util.LocalUtil;
/**
* DefaultContainer is like a mini-IoC container for DWR.
* At least it is an IoC container by interface (check: no params that have
* anything to do with DWR), but it is hard coded specifically for DWR. If we
* want to make more of it we can later, but this is certainly not going to
* become a full blown IoC container.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class DefaultContainer extends AbstractContainer implements Container
{
/**
* Set the class that should be used to implement the given interface
* @param askFor The interface to implement
* @param valueParam The new implementation
* @throws ContainerConfigurationException If the specified beans could not be used
*/
public void addParameter(String askFor, Object valueParam) throws ContainerConfigurationException
{
Object value = valueParam;
// Maybe the value is a classname that needs instantiating
if (value instanceof String)
{
try
{
Class<?> impl = LocalUtil.classForName((String) value);
value = impl.newInstance();
}
catch (ClassNotFoundException ex)
{
// it's not a classname, leave it
}
catch (InstantiationException ex)
{
throw new ContainerConfigurationException("Unable to instantiate " + value);
}
catch (IllegalAccessException ex)
{
throw new ContainerConfigurationException("Unable to access " + value);
}
}
// If we have an instantiated value object and askFor is an interface
// then we can check that one implements the other
if (!(value instanceof String))
{
try
{
Class<?> iface = LocalUtil.classForName(askFor);
if (!iface.isAssignableFrom(value.getClass()))
{
log.error("Can't cast: " + value + " to " + askFor);
}
}
catch (ClassNotFoundException ex)
{
// it's not a classname, leave it
}
}
if (log.isDebugEnabled())
{
if (value instanceof String)
{
log.debug("Adding IoC setting: " + askFor + "=" + value);
}
else
{
log.debug("Adding IoC implementation: " + askFor + "=" + value.getClass().getName());
}
}
beans.put(askFor, value);
}
/**
* Retrieve a previously set parameter
* @param name The parameter name to retrieve
* @return The value of the specified parameter, or null if one is not set
*/
public String getParameter(String name)
{
Object value = beans.get(name);
return (value == null) ? null : value.toString();
}
/**
* Called to indicate that we finished adding parameters.
* The thread safety of a large part of DWR depends on this function only
* being called from {@link Servlet#init(javax.servlet.ServletConfig)},
* where all the setup is done, and where we depend on the undocumented
* feature of all servlet containers that they complete the init process
* of a Servlet before they begin servicing requests.
* @see DefaultContainer#addParameter(String, Object)
* @noinspection UnnecessaryLabelOnContinueStatement
*/
public void setupFinished()
{
// We try to autowire each bean in turn
for (Entry<String, Object> entry : beans.entrySet())
{
// Class type = (Class) entry.getKey();
Object ovalue = entry.getValue();
if (!(ovalue instanceof String))
{
log.debug("Trying to autowire: " + ovalue.getClass().getName());
Method[] methods = ovalue.getClass().getMethods();
methods:
for (Method setter : methods)
{
if (setter.getName().startsWith("set") &&
setter.getName().length() > 3 &&
setter.getParameterTypes().length == 1)
{
String name = Character.toLowerCase(setter.getName().charAt(3)) + setter.getName().substring(4);
Class<?> propertyType = setter.getParameterTypes()[0];
// First we try auto-wire by name
Object setting = beans.get(name);
if (setting != null)
{
if (propertyType.isAssignableFrom(setting.getClass()))
{
log.debug("- autowire-by-name: " + name + "=" + setting);
invoke(setter, ovalue, setting);
continue methods;
}
else if (setting.getClass() == String.class)
{
try
{
Object value = LocalUtil.simpleConvert((String) setting, propertyType);
log.debug("- autowire-by-name: " + name + "=" + value);
invoke(setter, ovalue, value);
}
catch (IllegalArgumentException ex)
{
// Ignore - this was a speculative convert anyway
}
continue methods;
}
}
// Next we try autowire-by-type
Object value = beans.get(propertyType.getName());
if (value != null)
{
log.debug("- autowire-by-type: " + name + "=" + value.getClass().getName());
invoke(setter, ovalue, value);
continue methods;
}
log.debug("- skipped autowire: " + name);
}
}
}
}
callInitializingBeans();
}
/**
* A helper to do the reflection.
* This helper throws away all exceptions, preferring to log.
* @param setter The method to invoke
* @param bean The object to invoke the method on
* @param value The value to assign to the property using the setter method
*/
private static void invoke(Method setter, Object bean, Object value)
{
try
{
setter.invoke(bean, value);
}
catch (IllegalArgumentException ex)
{
log.error("- Internal error: " + ex.getMessage());
}
catch (IllegalAccessException ex)
{
log.error("- Permission error: " + ex.getMessage());
}
catch (InvocationTargetException ex)
{
log.error("- Exception during auto-wire: ", ex.getTargetException());
}
}
/* (non-Javadoc)
* @see org.directwebremoting.Container#getBean(java.lang.String)
*/
public Object getBean(String id)
{
Object reply = beans.get(id);
if (reply == null)
{
log.debug("DefaultContainer: No bean with id=" + id);
}
return reply;
}
/* (non-Javadoc)
* @see org.directwebremoting.Container#getBeanNames()
*/
public Collection<String> getBeanNames()
{
return Collections.unmodifiableCollection(beans.keySet());
}
/**
* The beans that we know of indexed by type
*/
protected Map<String, Object> beans = new TreeMap<String, Object>();
/**
* The log stream
*/
private static final Log log = LogFactory.getLog(DefaultContainer.class);
}
| don't debug if someone asks for a bean that does not exist
git-svn-id: ba1d8d5a2a2c535e023d6080c1e5c29aa0f5364e@1654 3a8262b2-faa5-11dc-8610-ff947880b6b2
| java/org/directwebremoting/impl/DefaultContainer.java | don't debug if someone asks for a bean that does not exist | <ide><path>ava/org/directwebremoting/impl/DefaultContainer.java
<ide> */
<ide> public Object getBean(String id)
<ide> {
<del> Object reply = beans.get(id);
<del> if (reply == null)
<del> {
<del> log.debug("DefaultContainer: No bean with id=" + id);
<del> }
<del>
<del> return reply;
<add> return beans.get(id);
<ide> }
<ide>
<ide> /* (non-Javadoc) |
|
Java | mit | 03ae087ffa2ddb2b38b057eb1106373518646a49 | 0 | zaboing/JSPlugins,zaboing/JSPlugins | package at.boing.jsplugins;
import com.avaje.ebean.EbeanServer;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.Event;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.PluginBase;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Logger;
public class JavaScriptPlugin extends PluginBase {
protected final Map<Class<? extends Event>, Set<Consumer<Event>>> listeners = new HashMap<>();
JavaScriptLoader loader;
private IJSPlugin plugin;
private PluginDescriptionFile descriptionFile;
private File dataFolder;
private FileConfiguration config;
private boolean isEnabled;
public JavaScriptPlugin(IJSPlugin plugin, JavaScriptLoader loader) {
this.plugin = plugin;
this.descriptionFile = new PluginDescriptionFile(plugin.getName(), plugin.getVersion(), plugin.getName());
this.dataFolder = new File(new File("jsplugins", plugin.getName()), "data");
if (!dataFolder.exists()) {
if (dataFolder.mkdirs()) {
getLogger().info("Created directory " + dataFolder.getPath());
}
}
this.loader = loader;
}
@Override
public File getDataFolder() {
return dataFolder;
}
@Override
public PluginDescriptionFile getDescription() {
return descriptionFile;
}
@Override
public FileConfiguration getConfig() {
if (config == null) {
reloadConfig();
}
return config;
}
@Override
public InputStream getResource(String s) {
return null;
}
@Override
public void saveConfig() {
}
@Override
public void saveDefaultConfig() {
}
@Override
public void saveResource(String s, boolean b) {
}
@Override
public void reloadConfig() {
config = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "config.yml"));
try {
config.load(new File(getDataFolder(), "default_config.yml"));
} catch (IOException e) {
getLogger().info("Did not load default configuration: " + e.getLocalizedMessage());
} catch (InvalidConfigurationException e) {
getLogger().info("Invalid default configuration: " + e.getLocalizedMessage());
}
}
@Override
public PluginLoader getPluginLoader() {
return loader;
}
@Override
public Server getServer() {
return loader.server;
}
@Override
public boolean isEnabled() {
return isEnabled;
}
@Override
public void onDisable() {
isEnabled = false;
plugin.onDisable();
listeners.clear();
}
@Override
public void onLoad() {
}
@Override
public void onEnable() {
isEnabled = true;
plugin.onEnable();
getServer().getPluginManager().registerEvents(plugin, this);
}
@SuppressWarnings("unused") // Suppress unused warnings: This method is supposed to be used in JavaScript plugins
public void on(String eventName, Consumer<Event> callback) {
Class<? extends Event> eventClass = findEventClass(eventName);
if (eventClass == null) {
getLogger().warning("Couldn't find event type " + eventName);
} else {
Set<Consumer<Event>> callbacks = listeners.get(eventClass);
if (callbacks == null) {
callbacks = new HashSet<>();
listeners.put(eventClass, callbacks);
}
callbacks.add(callback);
}
}
private Class<? extends Event> findEventClass(String name) {
for (Package pack : Package.getPackages()) {
if (pack.getName().startsWith(Event.class.getPackage().getName())) {
try {
@SuppressWarnings("unchecked")
Class<? extends Event> found = (Class<? extends Event>) Class.forName(pack.getName() + "." + name);
return found;
} catch (ClassNotFoundException e) {
// SILENTLY IGNORE AND CONTINUE SEARCHING
}
}
}
return null;
}
@Override
public boolean isNaggable() {
return false;
}
@Override
public void setNaggable(boolean b) {
}
@Override
public EbeanServer getDatabase() {
return null;
}
@Override
public ChunkGenerator getDefaultWorldGenerator(String s, String s1) {
return null;
}
@Override
public Logger getLogger() {
return getServer().getLogger();
}
@Override
public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
return false;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) {
return null;
}
}
| src/at/boing/jsplugins/JavaScriptPlugin.java | package at.boing.jsplugins;
import com.avaje.ebean.EbeanServer;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.Event;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.PluginBase;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Logger;
public class JavaScriptPlugin extends PluginBase {
protected final Map<Class<? extends Event>, Set<Consumer<Event>>> listeners = new HashMap<>();
JavaScriptLoader loader;
private IJSPlugin plugin;
private PluginDescriptionFile descriptionFile;
private File dataFolder;
private FileConfiguration config;
private boolean isEnabled;
public JavaScriptPlugin(IJSPlugin plugin, JavaScriptLoader loader) {
this.plugin = plugin;
this.descriptionFile = new PluginDescriptionFile(plugin.getName(), plugin.getVersion(), plugin.getName());
this.dataFolder = new File(new File("jsplugins", plugin.getName()), "data");
if (!dataFolder.exists()) {
if (dataFolder.mkdirs()) {
getLogger().info("Created directory " + dataFolder.getPath());
}
}
this.loader = loader;
}
@Override
public File getDataFolder() {
return dataFolder;
}
@Override
public PluginDescriptionFile getDescription() {
return descriptionFile;
}
@Override
public FileConfiguration getConfig() {
if (config == null) {
reloadConfig();
}
return config;
}
@Override
public InputStream getResource(String s) {
return null;
}
@Override
public void saveConfig() {
}
@Override
public void saveDefaultConfig() {
}
@Override
public void saveResource(String s, boolean b) {
}
@Override
public void reloadConfig() {
config = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "config.yml"));
try {
config.load(new File(getDataFolder(), "default_config.yml"));
} catch (IOException e) {
getLogger().info("Did not load default configuration: " + e.getLocalizedMessage());
} catch (InvalidConfigurationException e) {
getLogger().info("Invalid default configuration: " + e.getLocalizedMessage());
}
}
@Override
public PluginLoader getPluginLoader() {
return loader;
}
@Override
public Server getServer() {
return loader.server;
}
@Override
public boolean isEnabled() {
return isEnabled;
}
@Override
public void onDisable() {
isEnabled = false;
plugin.onDisable();
listeners.clear();
}
@Override
public void onLoad() {
}
@Override
public void onEnable() {
plugin.onEnable();
isEnabled = true;
getServer().getPluginManager().registerEvents(plugin, this);
}
@SuppressWarnings("unused") // Suppress unused warnings: This method is supposed to be used in JavaScript plugins
public void on(String eventName, Consumer<Event> callback) {
Class<? extends Event> eventClass = findEventClass(eventName);
if (eventClass == null) {
getLogger().warning("Couldn't find event type " + eventName);
} else {
Set<Consumer<Event>> callbacks = listeners.get(eventClass);
if (callbacks == null) {
callbacks = new HashSet<>();
listeners.put(eventClass, callbacks);
}
callbacks.add(callback);
}
}
private Class<? extends Event> findEventClass(String name) {
for (Package pack : Package.getPackages()) {
if (pack.getName().startsWith(Event.class.getPackage().getName())) {
try {
@SuppressWarnings("unchecked")
Class<? extends Event> found = (Class<? extends Event>) Class.forName(pack.getName() + "." + name);
return found;
} catch (ClassNotFoundException e) {
// SILENTLY IGNORE AND CONTINUE SEARCHING
}
}
}
return null;
}
@Override
public boolean isNaggable() {
return false;
}
@Override
public void setNaggable(boolean b) {
}
@Override
public EbeanServer getDatabase() {
return null;
}
@Override
public ChunkGenerator getDefaultWorldGenerator(String s, String s1) {
return null;
}
@Override
public Logger getLogger() {
return getServer().getLogger();
}
@Override
public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
return false;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) {
return null;
}
}
| Enable plugin before calling onEnable()
| src/at/boing/jsplugins/JavaScriptPlugin.java | Enable plugin before calling onEnable() | <ide><path>rc/at/boing/jsplugins/JavaScriptPlugin.java
<ide>
<ide> @Override
<ide> public void onEnable() {
<add> isEnabled = true;
<ide> plugin.onEnable();
<del> isEnabled = true;
<ide> getServer().getPluginManager().registerEvents(plugin, this);
<ide> }
<ide> |
|
Java | agpl-3.0 | 44ed20cd12b357cd9e21af0e401c11b9d24af722 | 0 | elki-project/elki,elki-project/elki,elki-project/elki |
package experimentalcode.students.waase;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.data.Cluster;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.data.model.Model;
import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.database.ids.HashSetModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.ids.ModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.query.DistanceResultPair;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.distance.distancevalue.DoubleDistance;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.math.FlexiHistogram;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.utilities.exceptions.UnableToComplyException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
/**
*
* @author Ernst
*/
public class LMCLUS<V extends NumberVector<V, ?>> extends AbstractAlgorithm<Clustering<Model>> {
/**
* The logger for this class.
*/
private static final Logging logger = Logging.getLogger(LMCLUS.class);
private final static double NOT_FROM_ONE_CLUSTER_PROBABILITY = 0.2;
private final static int BINS = 50;
private final static int NOISE_SIZE = 20;
private final static double SMALL_NUMBER = 0;
/**
* The current threshold value calculated by the findSeperation Method.
*/
private double threshold;
/**
* The basis of the linear manifold calculated by the findSeperation Method.
*/
private Matrix basis;
/**
* The id of the origin used to calculate the linear manifold in the
* findSeperation Method.
*/
private DBID origin;
private double goodness;
public static final OptionID MAXLM_ID = OptionID.getOrCreateOptionID("lmclus.maxLMDim", "Maximum linear manifold dimension to compute.");
public static final OptionID SAMPLINGL_ID = OptionID.getOrCreateOptionID("lmclus.samplingLevel", "A number used to determine how many samples are taken.");
public static final OptionID THRESHOLD_ID = OptionID.getOrCreateOptionID("lmclus.threshold", "Threshold to determine if a cluster was found.");
private final IntParameter maxLMDim = new IntParameter(MAXLM_ID);
private final IntParameter samplingLevel = new IntParameter(SAMPLINGL_ID);
private final DoubleParameter sensivityThreshold = new DoubleParameter(THRESHOLD_ID);
public LMCLUS(Parameterization config) {
super();
config = config.descend(this);
config.grab(maxLMDim);
config.grab(samplingLevel);
config.grab(sensivityThreshold);
}
public Clustering<Model> run(Database database, Relation<V> relation) throws IllegalStateException {
try {
return runLMCLUS(database, relation, maxLMDim.getValue(), samplingLevel.getValue(), sensivityThreshold.getValue());
}
catch(UnableToComplyException ex) {
throw new IllegalStateException(); // TODO
}
}
/**
* The main LMCLUS (Linear manifold clustering algorithm) is processed in this
* method.
*
* <PRE>
* The algorithm samples random linear manifolds and tries to find clusters in it.
* It calculates a distance histogram searches for a threshold and partitions the
* points in two groups the ones in the cluster and everything else.
* Then the best fitting linear manifold is searched and registered as a cluster.
* The process is started over until all points are clustered.
* The last cluster should contain all the outliers. (or the whole data if no clusters have been found.)
* For details see {@link LMCLUS}.
* </PRE>
*
* @param d The database to operate on
* @param relation
* @param maxLMDim The maximum dimension of the linear manifolds to look for.
* @param samplingLevel
* @param sensivityThreshold the threshold specifying if a manifold is good
* enough to be seen as cluster.
* @return A Clustering Object containing all the clusters found by the
* algorithm.
* @throws de.lmu.ifi.dbs.elki.utilities.UnableToComplyException
*/
private Clustering<Model> runLMCLUS(Database d, Relation<V> relation, int maxLMDim, int samplingLevel, double sensivityThreshold) throws UnableToComplyException {
Clustering<Model> ret = new Clustering<Model>("LMCLUS Clustering", "lmclus-clustering");
while(relation.size() > NOISE_SIZE) {
Database dCopy = d; // TODO copy database
int lMDim = 1;
for(int i = 1; i <= maxLMDim; i++) {
System.out.println("Current dim: " + i);
System.out.println("Sampling level:" + samplingLevel);
System.out.println("Threshold" + sensivityThreshold);
while(findSeparation(dCopy, i, samplingLevel) > sensivityThreshold) {
// FIXME: use a proper RangeQuery object
List<DistanceResultPair<DoubleDistance>> res = DatabaseQueryUtil.singleRangeQueryByDBID(d, new LMCLUSDistanceFunction<V>(basis), new DoubleDistance(threshold), origin);
if(res.size() < NOISE_SIZE) {
break;
}
ModifiableDBIDs partition = DBIDUtil.newArray();
for(DistanceResultPair<DoubleDistance> point : res) {
partition.add(point.getDBID());
}
// FIXME: Partition by using new ProxyDatabase(ids, database)
dCopy = dCopy.partition(partition);
// TODO partition database according to range
lMDim = i;
System.out.println("Partition: " + partition.size());
}
}
DBIDs delete = dCopy.getDBIDs();
HashSetModifiableDBIDs all = DBIDUtil.newHashSet(d.getDBIDs());
all.removeDBIDs(delete);
// FIXME: Partition by using new ProxyDatabase(ids, database)
d = d.partition(all);
ret.addCluster(new Cluster<Model>(all));
}
return ret;
}
/**
* This method samples a number of linear manifolds an tries to determine
* which the one with the best cluster is.
*
* <PRE>
* A number of sample points according to the dimension of the linear manifold are taken.
* The basis (B) and the origin(o) of the manifold are calculated.
* A distance histogram using the distance function ||x-o|| -||B^t*(x-o)|| is generated.
* The best threshold is searched using the elevate threshold function.
* The overall goodness of the threshold is determined.
* The process is redone until a specific number of samples is taken.
* </PRE>
*
* @param databasePartition The partition of the database to search for the
* cluster.
* @param dimension the dimension of the linear manifold to sample.
* @param samplingLevel
* @return the overall goodness of the separation. The values origin basis and
* threshold are returned indirectly over class variables.
*/
private double findSeparation(Relation<V> databasePartition, int dimension, int samplingLevel) {
double goodness = -1;
double threshold = -1;
DBID origin = null;
Matrix basis = null;
// determine the number of samples needed, to secure that with a specific
// probability
// in at least on sample every sampled point is from the same cluster.
int samples = (int) Math.min(Math.log(NOT_FROM_ONE_CLUSTER_PROBABILITY) / (Math.log(1 - Math.pow((1.0d / samplingLevel), dimension))), (double) databasePartition.size());
System.out.println("Dimension: " + dimension);
;
System.out.println("Number of samples: " + samples);
Random r = new Random();
for(int i = 1; i <= samples; i++) {
System.out.println(i);
DBIDs sample = DBIDUtil.randomSample(databasePartition.getDBIDs(), dimension + 1, r.nextLong());
DBID o = sample.iterator().next();
V tempOrigin = databasePartition.get(o);
java.util.Vector<V> vectors = new java.util.Vector<V>();
for(DBID point : sample) {
if(point == o)
continue;
V vec = databasePartition.get(point);
vectors.add(vec.minus(tempOrigin));
}
// generate orthogonal basis
Matrix tempBasis = null;
try {
tempBasis = generateOrthonormalBasis(vectors);
}
catch(RuntimeException e) {
// new sample has to be taken.
i--;
continue;
}
// Generate and fill a histogramm.
FlexiHistogram<Double, Double> histogramm = FlexiHistogram.DoubleSumHistogram(BINS);
DBIDs data = databasePartition.getDBIDs();
LMCLUSDistanceFunction<V> fun = new LMCLUSDistanceFunction<V>(tempBasis);
for(DBID point : data) {
if(sample.contains(point))
continue;
V vec = databasePartition.get(point);
System.out.println("Distance" + fun.distance(vec, tempOrigin).getValue());
histogramm.aggregate(fun.distance(vec, tempOrigin).getValue(), 1.0);
}
System.out.println("breakPoint");
double t = evaluateThreshold(histogramm);// evaluate threshold
double g = this.goodness;// Evaluate goodness
if(g > goodness) {
goodness = g;
threshold = t;
origin = o;
basis = tempBasis;
}
}
this.basis = basis;
this.origin = origin;
this.threshold = threshold;
System.out.println("Goodness:" + goodness);
return goodness;
}
/**
* This Method generates an orthonormal basis from a set of Vectors. It uses
* the established Gram-Schmidt algorithm for orthonormalisation:
*
* <PRE>
* u_1 = v_1
* u_k = v_k -proj_u1(v_k)...proj_u(k-1)(v_k);
*
* Where proj_u(v) = <v,u>/<u,u> *u
* </PRE>
*
* @param vectors The set of vectors to generate the orthonormal basis from
* @return the orthonormal basis generated by this method.
* @throws RuntimeException if the given vectors are not linear independent.
*/
private Matrix generateOrthonormalBasis(java.util.Vector<V> vectors) {
Matrix ret = new Matrix(vectors.get(0).getDimensionality(), vectors.size());
ret.setColumnVector(0, vectors.get(0).getColumnVector());
for(int i = 1; i < vectors.size(); i++) {
Vector partialSol = vectors.get(i).getColumnVector();
System.out.println("Vector1:" + partialSol.get(1));
for(int j = 0; j < i; j++) {
partialSol = partialSol.minus(projection(ret.getColumnVector(j), vectors.get(i).getColumnVector()));
}
// check if the vectors weren't independent
if(partialSol.euclideanLength() == 0.0) {
System.out.println(partialSol.euclideanLength());
throw new RuntimeException();
}
partialSol.normalize();
ret.setColumnVector(i, partialSol);
}
return ret;
}
/**
* This Method calculates: <v,u>/<u,u> *u
*
* @param u a vector
* @param v a vector
* @return the result of the calculation.
*/
private Vector projection(Vector u, Vector v) {
return u.times(v.scalarProduct(u) / u.scalarProduct(u));
}
/**
*
* @param histogramm
* @return
*/
private double evaluateThreshold(FlexiHistogram<Double, Double> histogramm) {
histogramm.replace(threshold, threshold);
double ret = 0;
int n = histogramm.getNumBins();
double[] p1 = new double[n];
double[] p2 = new double[n];
double[] mu1 = new double[n];
double[] mu2 = new double[n];
double[] sigma1 = new double[n];
double[] sigma2 = new double[n];
double[] jt = new double[n - 1];
Iterator<Pair<Double, Double>> forward = histogramm.iterator();
Iterator<Pair<Double, Double>> backwards = histogramm.reverseIterator();
backwards.next();
p1[0] = forward.next().second;
p2[n - 2] = backwards.next().second;
mu1[0] = 0;
mu2[n - 2] = (p2[n - 2] == 0 ? 0 : (n - 1));
sigma1[0] = 0;
sigma2[n - 2] = 0;
for(int i = 1, j = n - 3; i <= n - 2; i++, j--) {
double hi = forward.next().second;
double hj = backwards.next().second;
p1[i] = p1[i - 1] + hi;
if(p1[i] != 0) {
mu1[i] = ((mu1[i - 1] * p1[i - 1]) + (i * hi)) / p1[i];
sigma1[i] = (p1[i - 1] * (sigma1[i - 1] + (mu1[i - 1] - mu1[i]) * (mu1[i - 1] - mu1[i])) + hi * (i - mu1[i]) * (i - mu1[i])) / p1[i];
}
else {
mu1[i] = 0;
sigma1[i] = 0;
}
p2[j] = p2[j + 1] + hj;
if(p2[j] != 0) {
mu2[j] = ((mu2[j + 1] * p2[j + 1]) + ((j + 1) * hj)) / p2[j];
sigma2[j] = (p2[j + 1] * (sigma2[j + 1] + (mu2[j + 1] - mu2[j]) * (mu2[j + 1] - mu2[j])) + hj * (j + 1 - mu2[j]) * (j + 1 - mu2[j])) / p2[j];
}
else {
mu2[j] = 0;
sigma2[j] = 0;
}
}
for(int i = 0; i < n - 1; i++) {
if(p1[i] != 0 && p2[i] != 0 && sigma1[i] > SMALL_NUMBER && sigma2[i] > SMALL_NUMBER)
jt[i] = 1.0d + 2.0d * (p1[i] * Math.log(Math.sqrt(sigma1[i])) + p2[i] * Math.log(Math.sqrt(sigma2[i]))) - 2.0d * (p1[i] * Math.log(p1[i]) + p2[i] * Math.log(p2[i]));
else
jt[i] = -1;
}
int min = 0;
double devPrev = jt[1] - jt[0];
double globalDepth = -1;
double discriminability = -1;
for(int i = 1; i < jt.length - 1; i++) {
double devCur = jt[i + 1] - jt[i];
System.out.println(p1[i]);
System.out.println(jt[i + 1]);
System.out.println(jt[i]);
System.out.println(devCur);
// Minimum found calculate depth
if(devCur >= 0 && devPrev <= 0) {
double localDepth = 0;
int leftHeight = i;
while(leftHeight >= 1 && jt[leftHeight - 1] >= jt[leftHeight])
leftHeight--;
int rightHeight = i;
while(rightHeight < jt.length - 1 && jt[rightHeight] <= jt[rightHeight + 1])
rightHeight++;
if(jt[leftHeight] < jt[rightHeight])
localDepth = jt[leftHeight] - jt[i];
else
localDepth = jt[rightHeight] - jt[i];
if(localDepth > globalDepth) {
System.out.println("Minimum");
System.out.println(localDepth);
min = i;
globalDepth = localDepth;
discriminability = Math.abs(mu1[i] - mu2[i]) / (Math.sqrt(sigma1[i] - sigma2[i]));
System.out.println(discriminability);
}
}
}
ret = min * histogramm.getBinsize();
goodness = globalDepth * discriminability;
System.out.println("GLobal goodness:" + goodness + ";" + globalDepth + ";" + discriminability);
return ret;
}
@Override
protected Logging getLogger() {
return logger;
}
@Override
public TypeInformation[] getInputTypeRestriction() {
return TypeUtil.array(TypeUtil.NUMBER_VECTOR_FIELD);
}
} | src/experimentalcode/students/waase/LMCLUS.java |
package experimentalcode.students.waase;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.data.Cluster;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.data.model.Model;
import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil;
import de.lmu.ifi.dbs.elki.database.ids.DBIDs;
import de.lmu.ifi.dbs.elki.database.ids.HashSetModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.ids.ModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.query.DistanceResultPair;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.distance.distancevalue.DoubleDistance;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.math.FlexiHistogram;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.utilities.exceptions.UnableToComplyException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
/**
*
* @author Ernst
*/
public class LMCLUS<V extends NumberVector<V, ?>> extends AbstractAlgorithm<Clustering<Model>> {
/**
* The logger for this class.
*/
private static final Logging logger = Logging.getLogger(LMCLUS.class);
private final static double NOT_FROM_ONE_CLUSTER_PROBABILITY = 0.2;
private final static int BINS = 50;
private final static int NOISE_SIZE = 20;
private final static double SMALL_NUMBER = 0;
/**
* The current threshold value calculated by the findSeperation Method.
*/
private double threshold;
/**
* The basis of the linear manifold calculated by the findSeperation Method.
*/
private Matrix basis;
/**
* The id of the origin used to calculate the linear manifold in the
* findSeperation Method.
*/
private DBID origin;
private double goodness;
public static final OptionID MAXLM_ID = OptionID.getOrCreateOptionID("lmclus.maxLMDim", "Maximum linear manifold dimension to compute.");
public static final OptionID SAMPLINGL_ID = OptionID.getOrCreateOptionID("lmclus.samplingLevel", "A number used to determine how many samples are taken.");
public static final OptionID THRESHOLD_ID = OptionID.getOrCreateOptionID("lmclus.threshold", "Threshold to determine if a cluster was found.");
private final IntParameter maxLMDim = new IntParameter(MAXLM_ID);
private final IntParameter samplingLevel = new IntParameter(SAMPLINGL_ID);
private final DoubleParameter sensivityThreshold = new DoubleParameter(THRESHOLD_ID);
public LMCLUS(Parameterization config) {
super();
config = config.descend(this);
config.grab(maxLMDim);
config.grab(samplingLevel);
config.grab(sensivityThreshold);
}
@Override
public Clustering<Model> run(Database database) throws IllegalStateException {
try {
return runLMCLUS(database, maxLMDim.getValue(), samplingLevel.getValue(), sensivityThreshold.getValue());
}
catch(UnableToComplyException ex) {
throw new IllegalStateException(); // TODO
}
}
/**
* The main LMCLUS (Linear manifold clustering algorithm) is processed in this
* method.
*
* <PRE>
* The algorithm samples random linear manifolds and tries to find clusters in it.
* It calculates a distance histogram searches for a threshold and partitions the
* points in two groups the ones in the cluster and everything else.
* Then the best fitting linear manifold is searched and registered as a cluster.
* The process is started over until all points are clustered.
* The last cluster should contain all the outliers. (or the whole data if no clusters have been found.)
* For details see {@link LMCLUS}.
* </PRE>
*
* @param d The database to operate on
* @param maxLMDim The maximum dimension of the linear manifolds to look for.
* @param samplingLevel
* @param sensivityThreshold the threshold specifying if a manifold is good
* enough to be seen as cluster.
* @return A Clustering Object containing all the clusters found by the
* algorithm.
* @throws de.lmu.ifi.dbs.elki.utilities.UnableToComplyException
*/
private Clustering<Model> runLMCLUS(Database d, int maxLMDim, int samplingLevel, double sensivityThreshold) throws UnableToComplyException {
Clustering<Model> ret = new Clustering<Model>("LMCLUS Clustering", "lmclus-clustering");
while(d.size() > NOISE_SIZE) {
Database dCopy = d; // TODO copy database
int lMDim = 1;
for(int i = 1; i <= maxLMDim; i++) {
System.out.println("Current dim: " + i);
System.out.println("Sampling level:" + samplingLevel);
System.out.println("Threshold" + sensivityThreshold);
while(findSeparation(dCopy, i, samplingLevel) > sensivityThreshold) {
// FIXME: use a proper RangeQuery object
List<DistanceResultPair<DoubleDistance>> res = DatabaseQueryUtil.singleRangeQueryByDBID(d, new LMCLUSDistanceFunction<V>(basis), new DoubleDistance(threshold), origin);
if(res.size() < NOISE_SIZE) {
break;
}
ModifiableDBIDs partition = DBIDUtil.newArray();
for(DistanceResultPair<DoubleDistance> point : res) {
partition.add(point.getDBID());
}
// FIXME: Partition by using new ProxyDatabase(ids, database)
dCopy = dCopy.partition(partition);
// TODO partition database according to range
lMDim = i;
System.out.println("Partition: " + partition.size());
}
}
DBIDs delete = dCopy.getDBIDs();
HashSetModifiableDBIDs all = DBIDUtil.newHashSet(d.getDBIDs());
all.removeDBIDs(delete);
// FIXME: Partition by using new ProxyDatabase(ids, database)
d = d.partition(all);
ret.addCluster(new Cluster<Model>(all));
}
return ret;
}
/**
* This method samples a number of linear manifolds an tries to determine
* which the one with the best cluster is.
*
* <PRE>
* A number of sample points according to the dimension of the linear manifold are taken.
* The basis (B) and the origin(o) of the manifold are calculated.
* A distance histogram using the distance function ||x-o|| -||B^t*(x-o)|| is generated.
* The best threshold is searched using the elevate threshold function.
* The overall goodness of the threshold is determined.
* The process is redone until a specific number of samples is taken.
* </PRE>
*
* @param databasePartition The partition of the database to search for the
* cluster.
* @param dimension the dimension of the linear manifold to sample.
* @param samplingLevel
* @return the overall goodness of the separation. The values origin basis and
* threshold are returned indirectly over class variables.
*/
private double findSeparation(Relation<V> databasePartition, int dimension, int samplingLevel) {
double goodness = -1;
double threshold = -1;
DBID origin = null;
Matrix basis = null;
// determine the number of samples needed, to secure that with a specific
// probability
// in at least on sample every sampled point is from the same cluster.
int samples = (int) Math.min(Math.log(NOT_FROM_ONE_CLUSTER_PROBABILITY) / (Math.log(1 - Math.pow((1.0d / samplingLevel), dimension))), (double) databasePartition.size());
System.out.println("Dimension: " + dimension);
;
System.out.println("Number of samples: " + samples);
Random r = new Random();
for(int i = 1; i <= samples; i++) {
System.out.println(i);
DBIDs sample = DBIDUtil.randomSample(databasePartition.getDBIDs(), dimension + 1, r.nextLong());
DBID o = sample.iterator().next();
V tempOrigin = databasePartition.get(o);
java.util.Vector<V> vectors = new java.util.Vector<V>();
for(DBID point : sample) {
if(point == o)
continue;
V vec = databasePartition.get(point);
vectors.add(vec.minus(tempOrigin));
}
// generate orthogonal basis
Matrix tempBasis = null;
try {
tempBasis = generateOrthonormalBasis(vectors);
}
catch(RuntimeException e) {
// new sample has to be taken.
i--;
continue;
}
// Generate and fill a histogramm.
FlexiHistogram<Double, Double> histogramm = FlexiHistogram.DoubleSumHistogram(BINS);
DBIDs data = databasePartition.getDBIDs();
LMCLUSDistanceFunction<V> fun = new LMCLUSDistanceFunction<V>(tempBasis);
for(DBID point : data) {
if(sample.contains(point))
continue;
V vec = databasePartition.get(point);
System.out.println("Distance" + fun.distance(vec, tempOrigin).getValue());
histogramm.aggregate(fun.distance(vec, tempOrigin).getValue(), 1.0);
}
System.out.println("breakPoint");
double t = evaluateThreshold(histogramm);// evaluate threshold
double g = this.goodness;// Evaluate goodness
if(g > goodness) {
goodness = g;
threshold = t;
origin = o;
basis = tempBasis;
}
}
this.basis = basis;
this.origin = origin;
this.threshold = threshold;
System.out.println("Goodness:" + goodness);
return goodness;
}
/**
* This Method generates an orthonormal basis from a set of Vectors. It uses
* the established Gram-Schmidt algorithm for orthonormalisation:
*
* <PRE>
* u_1 = v_1
* u_k = v_k -proj_u1(v_k)...proj_u(k-1)(v_k);
*
* Where proj_u(v) = <v,u>/<u,u> *u
* </PRE>
*
* @param vectors The set of vectors to generate the orthonormal basis from
* @return the orthonormal basis generated by this method.
* @throws RuntimeException if the given vectors are not linear independent.
*/
private Matrix generateOrthonormalBasis(java.util.Vector<V> vectors) {
Matrix ret = new Matrix(vectors.get(0).getDimensionality(), vectors.size());
ret.setColumnVector(0, vectors.get(0).getColumnVector());
for(int i = 1; i < vectors.size(); i++) {
Vector partialSol = vectors.get(i).getColumnVector();
System.out.println("Vector1:" + partialSol.get(1));
for(int j = 0; j < i; j++) {
partialSol = partialSol.minus(projection(ret.getColumnVector(j), vectors.get(i).getColumnVector()));
}
// check if the vectors weren't independent
if(partialSol.euclideanLength() == 0.0) {
System.out.println(partialSol.euclideanLength());
throw new RuntimeException();
}
partialSol.normalize();
ret.setColumnVector(i, partialSol);
}
return ret;
}
/**
* This Method calculates: <v,u>/<u,u> *u
*
* @param u a vector
* @param v a vector
* @return the result of the calculation.
*/
private Vector projection(Vector u, Vector v) {
return u.times(v.scalarProduct(u) / u.scalarProduct(u));
}
/**
*
* @param histogramm
* @return
*/
private double evaluateThreshold(FlexiHistogram<Double, Double> histogramm) {
histogramm.replace(threshold, threshold);
double ret = 0;
int n = histogramm.getNumBins();
double[] p1 = new double[n];
double[] p2 = new double[n];
double[] mu1 = new double[n];
double[] mu2 = new double[n];
double[] sigma1 = new double[n];
double[] sigma2 = new double[n];
double[] jt = new double[n - 1];
Iterator<Pair<Double, Double>> forward = histogramm.iterator();
Iterator<Pair<Double, Double>> backwards = histogramm.reverseIterator();
backwards.next();
p1[0] = forward.next().second;
p2[n - 2] = backwards.next().second;
mu1[0] = 0;
mu2[n - 2] = (p2[n - 2] == 0 ? 0 : (n - 1));
sigma1[0] = 0;
sigma2[n - 2] = 0;
for(int i = 1, j = n - 3; i <= n - 2; i++, j--) {
double hi = forward.next().second;
double hj = backwards.next().second;
p1[i] = p1[i - 1] + hi;
if(p1[i] != 0) {
mu1[i] = ((mu1[i - 1] * p1[i - 1]) + (i * hi)) / p1[i];
sigma1[i] = (p1[i - 1] * (sigma1[i - 1] + (mu1[i - 1] - mu1[i]) * (mu1[i - 1] - mu1[i])) + hi * (i - mu1[i]) * (i - mu1[i])) / p1[i];
}
else {
mu1[i] = 0;
sigma1[i] = 0;
}
p2[j] = p2[j + 1] + hj;
if(p2[j] != 0) {
mu2[j] = ((mu2[j + 1] * p2[j + 1]) + ((j + 1) * hj)) / p2[j];
sigma2[j] = (p2[j + 1] * (sigma2[j + 1] + (mu2[j + 1] - mu2[j]) * (mu2[j + 1] - mu2[j])) + hj * (j + 1 - mu2[j]) * (j + 1 - mu2[j])) / p2[j];
}
else {
mu2[j] = 0;
sigma2[j] = 0;
}
}
for(int i = 0; i < n - 1; i++) {
if(p1[i] != 0 && p2[i] != 0 && sigma1[i] > SMALL_NUMBER && sigma2[i] > SMALL_NUMBER)
jt[i] = 1.0d + 2.0d * (p1[i] * Math.log(Math.sqrt(sigma1[i])) + p2[i] * Math.log(Math.sqrt(sigma2[i]))) - 2.0d * (p1[i] * Math.log(p1[i]) + p2[i] * Math.log(p2[i]));
else
jt[i] = -1;
}
int min = 0;
double devPrev = jt[1] - jt[0];
double globalDepth = -1;
double discriminability = -1;
for(int i = 1; i < jt.length - 1; i++) {
double devCur = jt[i + 1] - jt[i];
System.out.println(p1[i]);
System.out.println(jt[i + 1]);
System.out.println(jt[i]);
System.out.println(devCur);
// Minimum found calculate depth
if(devCur >= 0 && devPrev <= 0) {
double localDepth = 0;
int leftHeight = i;
while(leftHeight >= 1 && jt[leftHeight - 1] >= jt[leftHeight])
leftHeight--;
int rightHeight = i;
while(rightHeight < jt.length - 1 && jt[rightHeight] <= jt[rightHeight + 1])
rightHeight++;
if(jt[leftHeight] < jt[rightHeight])
localDepth = jt[leftHeight] - jt[i];
else
localDepth = jt[rightHeight] - jt[i];
if(localDepth > globalDepth) {
System.out.println("Minimum");
System.out.println(localDepth);
min = i;
globalDepth = localDepth;
discriminability = Math.abs(mu1[i] - mu2[i]) / (Math.sqrt(sigma1[i] - sigma2[i]));
System.out.println(discriminability);
}
}
}
ret = min * histogramm.getBinsize();
goodness = globalDepth * discriminability;
System.out.println("GLobal goodness:" + goodness + ";" + globalDepth + ";" + discriminability);
return ret;
}
@Override
protected Logging getLogger() {
return logger;
}
@Override
public TypeInformation[] getInputTypeRestriction() {
return TypeUtil.array(TypeUtil.NUMBER_VECTOR_FIELD);
}
} | Hints on how to adjust to the new API
| src/experimentalcode/students/waase/LMCLUS.java | Hints on how to adjust to the new API | <ide><path>rc/experimentalcode/students/waase/LMCLUS.java
<ide> config.grab(sensivityThreshold);
<ide> }
<ide>
<del> @Override
<del> public Clustering<Model> run(Database database) throws IllegalStateException {
<add> public Clustering<Model> run(Database database, Relation<V> relation) throws IllegalStateException {
<ide> try {
<del> return runLMCLUS(database, maxLMDim.getValue(), samplingLevel.getValue(), sensivityThreshold.getValue());
<add> return runLMCLUS(database, relation, maxLMDim.getValue(), samplingLevel.getValue(), sensivityThreshold.getValue());
<ide> }
<ide> catch(UnableToComplyException ex) {
<ide> throw new IllegalStateException(); // TODO
<ide> * </PRE>
<ide> *
<ide> * @param d The database to operate on
<add> * @param relation
<ide> * @param maxLMDim The maximum dimension of the linear manifolds to look for.
<ide> * @param samplingLevel
<ide> * @param sensivityThreshold the threshold specifying if a manifold is good
<ide> * algorithm.
<ide> * @throws de.lmu.ifi.dbs.elki.utilities.UnableToComplyException
<ide> */
<del> private Clustering<Model> runLMCLUS(Database d, int maxLMDim, int samplingLevel, double sensivityThreshold) throws UnableToComplyException {
<add> private Clustering<Model> runLMCLUS(Database d, Relation<V> relation, int maxLMDim, int samplingLevel, double sensivityThreshold) throws UnableToComplyException {
<ide> Clustering<Model> ret = new Clustering<Model>("LMCLUS Clustering", "lmclus-clustering");
<del> while(d.size() > NOISE_SIZE) {
<add> while(relation.size() > NOISE_SIZE) {
<ide> Database dCopy = d; // TODO copy database
<ide> int lMDim = 1;
<ide> for(int i = 1; i <= maxLMDim; i++) { |
|
Java | apache-2.0 | f9c2378c5d48e23e3c7abe8b554345836f150994 | 0 | maichler/izpack,mtjandra/izpack,Helpstone/izpack,Helpstone/izpack,yukron/izpack,rkrell/izpack,rsharipov/izpack,Helpstone/izpack,optotronic/izpack,Murdock01/izpack,rkrell/izpack,rsharipov/izpack,codehaus/izpack,akuhtz/izpack,stenix71/izpack,bradcfisher/izpack,rkrell/izpack,Murdock01/izpack,tomas-forsman/izpack,rsharipov/izpack,Helpstone/izpack,codehaus/izpack,optotronic/izpack,Helpstone/izpack,mtjandra/izpack,mtjandra/izpack,akuhtz/izpack,izpack/izpack,codehaus/izpack,codehaus/izpack,bradcfisher/izpack,optotronic/izpack,tomas-forsman/izpack,rsharipov/izpack,stenix71/izpack,rkrell/izpack,maichler/izpack,maichler/izpack,mtjandra/izpack,izpack/izpack,akuhtz/izpack,akuhtz/izpack,izpack/izpack,tomas-forsman/izpack,yukron/izpack,optotronic/izpack,yukron/izpack,rkrell/izpack,mtjandra/izpack,yukron/izpack,izpack/izpack,stenix71/izpack,Murdock01/izpack,bradcfisher/izpack,rsharipov/izpack,maichler/izpack,rkrell/izpack,rsharipov/izpack,codehaus/izpack,maichler/izpack,rkrell/izpack,akuhtz/izpack,Helpstone/izpack,Murdock01/izpack,izpack/izpack,bradcfisher/izpack,akuhtz/izpack,tomas-forsman/izpack,maichler/izpack,Helpstone/izpack,tomas-forsman/izpack,stenix71/izpack,tomas-forsman/izpack,izpack/izpack,yukron/izpack,izpack/izpack,tomas-forsman/izpack,stenix71/izpack,codehaus/izpack,stenix71/izpack,bradcfisher/izpack,Murdock01/izpack,optotronic/izpack,yukron/izpack,mtjandra/izpack,bradcfisher/izpack,optotronic/izpack,stenix71/izpack,rsharipov/izpack,akuhtz/izpack,maichler/izpack,optotronic/izpack,codehaus/izpack,yukron/izpack,mtjandra/izpack,bradcfisher/izpack,Murdock01/izpack,Murdock01/izpack | /*
* $Id$
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2001 Johannes Lehtinen
* Copyright 2002 Paul Wilkinson
* Copyright 2004 Gaganis Giorgos
*
*
* 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.
*/
package com.izforge.izpack.compiler;
import com.izforge.izpack.api.data.Pack;
import com.izforge.izpack.api.data.PackColor;
import com.izforge.izpack.api.exception.CompilerException;
import com.izforge.izpack.api.substitutor.SubstitutionType;
import com.izforge.izpack.api.substitutor.VariableSubstitutor;
import com.izforge.izpack.compiler.data.CompilerData;
import com.izforge.izpack.compiler.data.PropertyManager;
import com.izforge.izpack.compiler.helper.AssertionHelper;
import com.izforge.izpack.compiler.helper.CompilerHelper;
import com.izforge.izpack.compiler.packager.IPackager;
import com.izforge.izpack.data.CustomData;
import com.izforge.izpack.data.PackInfo;
import com.izforge.izpack.util.Debug;
import com.izforge.izpack.util.OsConstraint;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
/**
* The IzPack compiler class. This is now a java bean style class that can be
* configured using the object representations of the install.xml
* configuration. The install.xml configuration is now handled by the
* CompilerConfig class.
*
* @author Julien Ponge
* @author Tino Schwarze
* @author Chadwick McHenry
* @see CompilerConfig
*/
public class Compiler extends Thread {
/**
* Collects and packs files into installation jars, as told.
*/
private IPackager packager;
/**
* Error code, set to true if compilation succeeded.
*/
private boolean compileFailed = true;
private CompilerHelper compilerHelper;
/**
* Replaces the properties in the install.xml file prior to compiling
*/
private VariableSubstitutor propertySubstitutor;
public PropertyManager propertyManager;
/**
* The constructor.
*
* @throws CompilerException
*/
public Compiler(VariableSubstitutor variableSubstitutor, PropertyManager propertyManager, CompilerHelper compilerHelper, IPackager packager) throws CompilerException {
this.propertyManager = propertyManager;
this.propertySubstitutor = variableSubstitutor;
this.compilerHelper = compilerHelper;
this.packager = packager;
// add izpack built in property
}
/**
* The run() method.
*/
public void run() {
try {
createInstaller(); // Execute the compiler - may send info to
// System.out
}
catch (CompilerException ce) {
System.out.println(ce.getMessage() + "\n");
}
catch (Exception e) {
if (Debug.stackTracing()) {
e.printStackTrace();
} else {
System.out.println("ERROR: " + e.getMessage());
}
}
}
/**
* Compiles the installation.
*
* @throws Exception Description of the Exception
*/
public void createInstaller() throws Exception {
// We ask the packager to create the installer
packager.createInstaller();
this.compileFailed = false;
}
/**
* Returns whether the installation was successful or not.
*
* @return whether the installation was successful or not
*/
public boolean wasSuccessful() {
return !this.compileFailed;
}
/**
* Checks whether the dependencies stated in the configuration file are correct. Specifically it
* checks that no pack point to a non existent pack and also that there are no circular
* dependencies in the packs.
*
* @throws CompilerException
*/
public void checkDependencies() throws CompilerException {
checkDependencies(packager.getPacksList());
}
/**
* Checks whether the excluded packs exist. (simply calles the other function)
*
* @throws CompilerException
*/
public void checkExcludes() throws CompilerException {
checkExcludes(packager.getPacksList());
}
/**
* This checks if there are more than one preselected packs per excludeGroup.
*
* @param packs list of packs which should be checked
* @throws CompilerException
*/
public void checkExcludes(List<PackInfo> packs) throws CompilerException {
for (int q = 0; q < packs.size(); q++) {
PackInfo packinfo1 = packs.get(q);
Pack pack1 = packinfo1.getPack();
for (int w = 0; w < q; w++) {
PackInfo packinfo2 = packs.get(w);
Pack pack2 = packinfo2.getPack();
if (pack1.excludeGroup != null && pack2.excludeGroup != null) {
if (pack1.excludeGroup.equals(pack2.excludeGroup)) {
if (pack1.preselected && pack2.preselected) {
parseError("Packs " + pack1.name + " and " + pack2.name +
" belong to the same excludeGroup " + pack1.excludeGroup +
" and are both preselected. This is not allowed.");
}
}
}
}
}
}
/**
* Checks whether the dependencies among the given Packs. Specifically it
* checks that no pack point to a non existent pack and also that there are no circular
* dependencies in the packs.
*
* @param packs - List<Pack> representing the packs in the installation
* @throws CompilerException
*/
public void checkDependencies(List<PackInfo> packs) throws CompilerException {
// Because we use package names in the configuration file we assosiate
// the names with the objects
Map<String, PackInfo> names = new HashMap<String, PackInfo>();
for (PackInfo pack : packs) {
names.put(pack.getPack().name, pack);
}
int result = dfs(packs, names);
// @todo More informative messages to include the source of the error
if (result == -2) {
parseError("Circular dependency detected");
} else if (result == -1) {
parseError("A dependency doesn't exist");
}
}
/**
* We use the dfs graph search algorithm to check whether the graph is acyclic as described in:
* Thomas H. Cormen, Charles Leiserson, Ronald Rivest and Clifford Stein. Introduction to
* algorithms 2nd Edition 540-549,MIT Press, 2001
*
* @param packs The graph
* @param names The name map
* @return -2 if back edges exist, else 0
*/
private int dfs(List<PackInfo> packs, Map<String, PackInfo> names) {
Map<Edge, PackColor> edges = new HashMap<Edge, PackColor>();
for (PackInfo pack : packs) {
if (pack.colour == PackColor.WHITE) {
if (dfsVisit(pack, names, edges) != 0) {
return -1;
}
}
}
return checkBackEdges(edges);
}
/**
* This function checks for the existence of back edges.
*
* @param edges map to be checked
* @return -2 if back edges exist, else 0
*/
private int checkBackEdges(Map<Edge, PackColor> edges) {
Set<Edge> keys = edges.keySet();
for (final Edge key : keys) {
PackColor color = edges.get(key);
if (color == PackColor.GREY) {
return -2;
}
}
return 0;
}
/**
* This class is used for the classification of the edges
*/
private class Edge {
PackInfo u;
PackInfo v;
Edge(PackInfo u, PackInfo v) {
this.u = u;
this.v = v;
}
}
private int dfsVisit(PackInfo u, Map<String, PackInfo> names, Map<Edge, PackColor> edges) {
u.colour = PackColor.GREY;
List<String> deps = u.getDependencies();
if (deps != null) {
for (String name : deps) {
PackInfo v = names.get(name);
if (v == null) {
System.out.println("Failed to find dependency: " + name);
return -1;
}
Edge edge = new Edge(u, v);
if (edges.get(edge) == null) {
edges.put(edge, v.colour);
}
if (v.colour == PackColor.WHITE) {
final int result = dfsVisit(v, names, edges);
if (result != 0) {
return result;
}
}
}
}
u.colour = PackColor.BLACK;
return 0;
}
public URL findIzPackResource(String path, String desc) throws CompilerException {
return findIzPackResource(path, desc, false);
}
/**
* Look for an IzPack resource either in the compiler jar, or within IZPACK_HOME. The path must
* not be absolute. The path must use '/' as the fileSeparator (it's used to access the jar
* file). If the resource is not found, take appropriate action base on ignoreWhenNotFound flag.
*
* @param path the relative path (using '/' as separator) to the resource.
* @param desc the description of the resource used to report errors
* @param ignoreWhenNotFound when false, throws a CompilerException indicate
* fault in the parent element when resource not found.
* @return a URL to the resource.
* @throws CompilerException
*/
public URL findIzPackResource(String path, String desc, boolean ignoreWhenNotFound)
throws CompilerException {
URL url = getClass().getResource("/" + path);
if (url == null) {
File resource = new File(path);
if (!resource.isAbsolute()) {
resource = new File(CompilerData.IZPACK_HOME, path);
}
if (!resource.exists()) {
if (ignoreWhenNotFound) {
AssertionHelper.parseWarn(desc + " not found: " + resource);
} else {
parseError(desc + " not found: " + resource); // fatal
}
} else {
try {
url = resource.toURI().toURL();
}
catch (MalformedURLException how) {
parseError(desc + "(" + resource + ")", how);
}
}
}
return url;
}
/**
* Create parse error with consistent messages. Includes file name. For use When parent is
* unknown.
*
* @param message Brief message explaining error
* @throws CompilerException
*/
public void parseError(String message) throws CompilerException {
this.compileFailed = true;
throw new CompilerException(message);
}
/**
* Create parse error with consistent messages. Includes file name. For use When parent is
* unknown.
*
* @param message Brief message explaining error
* @param how throwable which was catched
* @throws CompilerException
*/
public void parseError(String message, Throwable how) throws CompilerException {
this.compileFailed = true;
throw new CompilerException(message, how);
}
// -------------------------------------------------------------------------
// ------------- Listener stuff ------------------------- START ------------
/**
* This method parses install.xml for defined listeners and put them in the right position. If
* posible, the listeners will be validated. Listener declaration is a fragmention in
* install.xml like : <listeners> <listener compiler="PermissionCompilerListener"
* installer="PermissionInstallerListener"/1gt; </listeners>
*
* @param type The listener type.
* @param className The class name.
* @param jarPath The jar path.
* @param constraints The list of constraints.
* @throws Exception Thrown in case an error occurs.
*/
public void addCustomListener(int type, String className, String jarPath, List<OsConstraint> constraints) throws Exception {
jarPath = propertySubstitutor.substitute(jarPath, SubstitutionType.TYPE_AT);
String fullClassName = className;
List<String> filePaths = null;
URL url = findIzPackResource(jarPath, "CustomAction jar file", true);
if (url != null) {
fullClassName = getFullClassName(url, className);
if (fullClassName == null) {
throw new CompilerException("CustomListener class '" + className + "' not found in '"
+ url + "'. The class and listener name must match");
}
filePaths = compilerHelper.getContainedFilePaths(url);
}
CustomData ca = new CustomData(fullClassName, filePaths, constraints, type);
packager.addCustomJar(ca, url);
}
/**
* Returns the qualified class name for the given class. This method expects as the url param a
* jar file which contains the given class. It scans the zip entries of the jar file.
*
* @param url url of the jar file which contains the class
* @param className short name of the class for which the full name should be resolved
* @return full qualified class name
* @throws Exception
*/
private String getFullClassName(URL url, String className) throws Exception {
JarInputStream jis = new JarInputStream(url.openStream());
ZipEntry zentry;
while ((zentry = jis.getNextEntry()) != null) {
String name = zentry.getName();
int lastPos = name.lastIndexOf(".class");
if (lastPos < 0) {
continue; // No class file.
}
name = name.replace('/', '.');
int pos;
if (className != null) {
pos = name.indexOf(className);
if (pos >= 0 && name.length() == pos + className.length() + 6) // "Main" class
// found
{
jis.close();
return (name.substring(0, lastPos));
}
}
}
jis.close();
return (null);
}
}
| izpack-compiler/src/main/java/com/izforge/izpack/compiler/Compiler.java | /*
* $Id$
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2001 Johannes Lehtinen
* Copyright 2002 Paul Wilkinson
* Copyright 2004 Gaganis Giorgos
*
*
* 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.
*/
package com.izforge.izpack.compiler;
import com.izforge.izpack.api.data.Pack;
import com.izforge.izpack.api.data.PackColor;
import com.izforge.izpack.api.exception.CompilerException;
import com.izforge.izpack.api.substitutor.SubstitutionType;
import com.izforge.izpack.api.substitutor.VariableSubstitutor;
import com.izforge.izpack.compiler.data.CompilerData;
import com.izforge.izpack.compiler.data.PropertyManager;
import com.izforge.izpack.compiler.helper.AssertionHelper;
import com.izforge.izpack.compiler.helper.CompilerHelper;
import com.izforge.izpack.compiler.packager.IPackager;
import com.izforge.izpack.data.CustomData;
import com.izforge.izpack.data.PackInfo;
import com.izforge.izpack.util.Debug;
import com.izforge.izpack.util.OsConstraint;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
/**
* The IzPack compiler class. This is now a java bean style class that can be
* configured using the object representations of the install.xml
* configuration. The install.xml configuration is now handled by the
* CompilerConfig class.
*
* @author Julien Ponge
* @author Tino Schwarze
* @author Chadwick McHenry
* @see CompilerConfig
*/
public class Compiler extends Thread {
/**
* Collects and packs files into installation jars, as told.
*/
private IPackager packager;
/**
* Error code, set to true if compilation succeeded.
*/
private boolean compileFailed = true;
private CompilerHelper compilerHelper;
/**
* Replaces the properties in the install.xml file prior to compiling
*/
private VariableSubstitutor propertySubstitutor;
public PropertyManager propertyManager;
/**
* The constructor.
*
* @throws CompilerException
*/
public Compiler(VariableSubstitutor variableSubstitutor, PropertyManager propertyManager, CompilerHelper compilerHelper, IPackager packager) throws CompilerException {
this.propertyManager = propertyManager;
this.propertySubstitutor = variableSubstitutor;
this.compilerHelper = compilerHelper;
this.packager = packager;
// add izpack built in property
}
/**
* The run() method.
*/
public void run() {
try {
createInstaller(); // Execute the compiler - may send info to
// System.out
}
catch (CompilerException ce) {
System.out.println(ce.getMessage() + "\n");
}
catch (Exception e) {
if (Debug.stackTracing()) {
e.printStackTrace();
} else {
System.out.println("ERROR: " + e.getMessage());
}
}
}
/**
* Compiles the installation.
*
* @throws Exception Description of the Exception
*/
public void createInstaller() throws Exception {
// We ask the packager to create the installer
packager.createInstaller();
this.compileFailed = false;
}
/**
* Returns whether the installation was successful or not.
*
* @return whether the installation was successful or not
*/
public boolean wasSuccessful() {
return !this.compileFailed;
}
/**
* Checks whether the dependencies stated in the configuration file are correct. Specifically it
* checks that no pack point to a non existent pack and also that there are no circular
* dependencies in the packs.
*
* @throws CompilerException
*/
public void checkDependencies() throws CompilerException {
checkDependencies(packager.getPacksList());
}
/**
* Checks whether the excluded packs exist. (simply calles the other function)
*
* @throws CompilerException
*/
public void checkExcludes() throws CompilerException {
checkExcludes(packager.getPacksList());
}
/**
* This checks if there are more than one preselected packs per excludeGroup.
*
* @param packs list of packs which should be checked
* @throws CompilerException
*/
public void checkExcludes(List<PackInfo> packs) throws CompilerException {
for (int q = 0; q < packs.size(); q++) {
PackInfo packinfo1 = packs.get(q);
Pack pack1 = packinfo1.getPack();
for (int w = 0; w < q; w++) {
PackInfo packinfo2 = packs.get(w);
Pack pack2 = packinfo2.getPack();
if (pack1.excludeGroup != null && pack2.excludeGroup != null) {
if (pack1.excludeGroup.equals(pack2.excludeGroup)) {
if (pack1.preselected && pack2.preselected) {
parseError("Packs " + pack1.name + " and " + pack2.name +
" belong to the same excludeGroup " + pack1.excludeGroup +
" and are both preselected. This is not allowed.");
}
}
}
}
}
}
/**
* Checks whether the dependencies among the given Packs. Specifically it
* checks that no pack point to a non existent pack and also that there are no circular
* dependencies in the packs.
*
* @param packs - List<Pack> representing the packs in the installation
* @throws CompilerException
*/
public void checkDependencies(List<PackInfo> packs) throws CompilerException {
// Because we use package names in the configuration file we assosiate
// the names with the objects
Map<String, PackInfo> names = new HashMap<String, PackInfo>();
for (PackInfo pack : packs) {
names.put(pack.getPack().name, pack);
}
int result = dfs(packs, names);
// @todo More informative messages to include the source of the error
if (result == -2) {
parseError("Circular dependency detected");
} else if (result == -1) {
parseError("A dependency doesn't exist");
}
}
/**
* We use the dfs graph search algorithm to check whether the graph is acyclic as described in:
* Thomas H. Cormen, Charles Leiserson, Ronald Rivest and Clifford Stein. Introduction to
* algorithms 2nd Edition 540-549,MIT Press, 2001
*
* @param packs The graph
* @param names The name map
* @return -2 if back edges exist, else 0
*/
private int dfs(List<PackInfo> packs, Map<String, PackInfo> names) {
Map<Edge, PackColor> edges = new HashMap<Edge, PackColor>();
for (PackInfo pack : packs) {
if (pack.colour == PackColor.WHITE) {
if (dfsVisit(pack, names, edges) != 0) {
return -1;
}
}
}
return checkBackEdges(edges);
}
/**
* This function checks for the existence of back edges.
*
* @param edges map to be checked
* @return -2 if back edges exist, else 0
*/
private int checkBackEdges(Map<Edge, PackColor> edges) {
Set<Edge> keys = edges.keySet();
for (final Edge key : keys) {
PackColor color = edges.get(key);
if (color == PackColor.GREY) {
return -2;
}
}
return 0;
}
/**
* This class is used for the classification of the edges
*/
private class Edge {
PackInfo u;
PackInfo v;
Edge(PackInfo u, PackInfo v) {
this.u = u;
this.v = v;
}
}
private int dfsVisit(PackInfo u, Map<String, PackInfo> names, Map<Edge, PackColor> edges) {
u.colour = PackColor.GREY;
List<String> deps = u.getDependencies();
if (deps != null) {
for (String name : deps) {
PackInfo v = names.get(name);
if (v == null) {
System.out.println("Failed to find dependency: " + name);
return -1;
}
Edge edge = new Edge(u, v);
if (edges.get(edge) == null) {
edges.put(edge, v.colour);
}
if (v.colour == PackColor.WHITE) {
final int result = dfsVisit(v, names, edges);
if (result != 0) {
return result;
}
}
}
}
u.colour = PackColor.BLACK;
return 0;
}
public URL findIzPackResource(String path, String desc) throws CompilerException {
return findIzPackResource(path, desc, false);
}
/**
* Look for an IzPack resource either in the compiler jar, or within IZPACK_HOME. The path must
* not be absolute. The path must use '/' as the fileSeparator (it's used to access the jar
* file). If the resource is not found, take appropriate action base on ignoreWhenNotFound flag.
*
* @param path the relative path (using '/' as separator) to the resource.
* @param desc the description of the resource used to report errors
* @param ignoreWhenNotFound when false, throws a CompilerException indicate
* fault in the parent element when resource not found.
* @return a URL to the resource.
* @throws CompilerException
*/
public URL findIzPackResource(String path, String desc, boolean ignoreWhenNotFound)
throws CompilerException {
URL url = getClass().getResource("/" + path);
if (url == null) {
File resource = new File(path);
if (!resource.isAbsolute()) {
resource = new File(CompilerData.IZPACK_HOME, path);
}
if (!resource.exists()) {
if (ignoreWhenNotFound) {
AssertionHelper.parseWarn(desc + " not found: " + resource);
} else {
parseError(desc + " not found: " + resource); // fatal
}
} else {
try {
url = resource.toURI().toURL();
}
catch (MalformedURLException how) {
parseError(desc + "(" + resource + ")", how);
}
}
}
return url;
}
/**
* Create parse error with consistent messages. Includes file name. For use When parent is
* unknown.
*
* @param message Brief message explaining error
* @throws CompilerException
*/
public void parseError(String message) throws CompilerException {
this.compileFailed = true;
throw new CompilerException(message);
}
/**
* Create parse error with consistent messages. Includes file name. For use When parent is
* unknown.
*
* @param message Brief message explaining error
* @param how throwable which was catched
* @throws CompilerException
*/
public void parseError(String message, Throwable how) throws CompilerException {
this.compileFailed = true;
throw new CompilerException(message, how);
}
// -------------------------------------------------------------------------
// ------------- Listener stuff ------------------------- START ------------
/**
* This method parses install.xml for defined listeners and put them in the right position. If
* posible, the listeners will be validated. Listener declaration is a fragmention in
* install.xml like : <listeners> <listener compiler="PermissionCompilerListener"
* installer="PermissionInstallerListener"/1gt; </listeners>
*
* @param type The listener type.
* @param className The class name.
* @param jarPath The jar path.
* @param constraints The list of constraints.
* @throws Exception Thrown in case an error occurs.
*/
public void addCustomListener(int type, String className, String jarPath, List<OsConstraint> constraints) throws Exception {
jarPath = propertySubstitutor.substitute(jarPath, SubstitutionType.TYPE_AT);
String fullClassName = className;
List<String> filePaths = null;
URL url = findIzPackResource(jarPath, "CustomAction jar file", true);
if (url != null) {
fullClassName = getFullClassName(url, className);
if (fullClassName == null) {
throw new CompilerException("CustomListener class '" + className + "' not found in '"
+ url + "'. The class and listener name must match");
}
filePaths = compilerHelper.getContainedFilePaths(url);
}
CustomData ca = new CustomData(fullClassName, filePaths, constraints, type);
packager.addCustomJar(ca, url);
}
/**
* Returns the qualified class name for the given class. This method expects as the url param a
* jar file which contains the given class. It scans the zip entries of the jar file.
*
* @param url url of the jar file which contains the class
* @param className short name of the class for which the full name should be resolved
* @return full qualified class name
* @throws Exception
*/
private String getFullClassName(URL url, String className) throws Exception {
JarInputStream jis = new JarInputStream(url.openStream());
ZipEntry zentry;
while ((zentry = jis.getNextEntry()) != null) {
String name = zentry.getName();
int lastPos = name.lastIndexOf(".class");
if (lastPos < 0) {
continue; // No class file.
}
name = name.replace('/', '.');
int pos;
if (className != null) {
pos = name.indexOf(className);
if (pos >= 0 && name.length() == pos + className.length() + 6) // "Main" class
// found
{
jis.close();
return (name.substring(0, lastPos));
}
}
}
jis.close();
return (null);
}
// -------------------------------------------------------------------------
// ------------- Listener stuff ------------------------- END ------------
}
| Clean compiler and compilerConfig
| izpack-compiler/src/main/java/com/izforge/izpack/compiler/Compiler.java | Clean compiler and compilerConfig | <ide><path>zpack-compiler/src/main/java/com/izforge/izpack/compiler/Compiler.java
<ide> return (null);
<ide> }
<ide>
<del> // -------------------------------------------------------------------------
<del> // ------------- Listener stuff ------------------------- END ------------
<del>
<ide> } |
|
Java | mit | c9650cdba3b34a100b46e3ce4fe3a26db2600a40 | 0 | PolymorphGit/SJI-DEV,PolymorphGit/SJI-DEV | import java.net.URISyntaxException;
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import com.heroku.sdk.jdbc.DatabaseUrl;
class IdealPrice
{
private Connection connection = null;
private Statement stmt = null;
private ArrayList<NPD> listNPD;
private Account account;
private ArrayList<FG> listFG;
public IdealPrice(ArrayList<NPD> newNPD)
{
ConnectDB();
listNPD = newNPD;
LoadData();
}
public IdealPrice(Account newAcc)
{
ConnectDB();
account = newAcc;
listNPD = new ArrayList<NPD>();
try {
ResultSet rs = stmt.executeQuery("SELECT * FROM salesforce.NPD__c where Account_Name__c='" + newAcc.Id + "'");
while (rs.next())
{
listNPD.add(new NPD(rs));
}
LoadData();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void ConnectDB()
{
try {
connection = DatabaseUrl.extract().getConnection();
stmt = connection.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void LoadData()
{
String listID = "a0fO000000AlPnSIAV, a0fO000000AlBIQIA3";
/*
for(NPD npd : listNPD)
{
listID += npd.Id + ", ";
}
*/
try
{
ResultSet rs = stmt.executeQuery("SELECT * FROM salesforce.FG__c where NPD__c in (" + listID + ")");
while (rs.next())
{
listFG.add(new FG(rs));
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getResult()
{
String output = "";
for(FG fg : listFG)
{
output += fg.Name + "(" + fg.AnnualVolume + "), ";
}
return output;
//return "Success";
}
}
| src/main/java/IdealPrice.java | import java.net.URISyntaxException;
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import com.heroku.sdk.jdbc.DatabaseUrl;
class IdealPrice
{
private Connection connection = null;
private Statement stmt = null;
private ArrayList<NPD> listNPD;
private Account account;
private ArrayList<FG> listFG;
public IdealPrice(ArrayList<NPD> newNPD)
{
ConnectDB();
listNPD = newNPD;
LoadData();
}
public IdealPrice(Account newAcc)
{
ConnectDB();
account = newAcc;
listNPD = new ArrayList<NPD>();
try {
ResultSet rs = stmt.executeQuery("SELECT * FROM salesforce.NPD__c where Account_Name__c='" + newAcc.Id + "'");
while (rs.next())
{
listNPD.add(new NPD(rs));
}
//LoadData();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void ConnectDB()
{
try {
connection = DatabaseUrl.extract().getConnection();
stmt = connection.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void LoadData()
{
String listID = "";
for(NPD npd : listNPD)
{
listID += npd.Id + ", ";
}
try
{
ResultSet rs = stmt.executeQuery("SELECT * FROM salesforce.FG__c where NPD__c in (" + listID + ")");
while (rs.next())
{
listFG.add(new FG(rs));
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getResult()
{
String output = "";
/*
* for(FG fg : listFG)
{
output += fg.Name + "(" + fg.AnnualVolume + "), ";
}
*/
for(NPD npd : listNPD)
{
output += "Name: " + npd.Name + ", ";
}
return output;
//return "Success";
}
}
| Test Query Where IN v0.2
| src/main/java/IdealPrice.java | Test Query Where IN v0.2 | <ide><path>rc/main/java/IdealPrice.java
<ide> listNPD.add(new NPD(rs));
<ide> }
<ide>
<del> //LoadData();
<add> LoadData();
<ide> }
<ide> catch (SQLException e) {
<ide> // TODO Auto-generated catch block
<ide>
<ide> private void LoadData()
<ide> {
<del> String listID = "";
<add> String listID = "a0fO000000AlPnSIAV, a0fO000000AlBIQIA3";
<add> /*
<ide> for(NPD npd : listNPD)
<ide> {
<ide> listID += npd.Id + ", ";
<ide> }
<add> */
<ide> try
<ide> {
<ide> ResultSet rs = stmt.executeQuery("SELECT * FROM salesforce.FG__c where NPD__c in (" + listID + ")");
<ide> {
<ide>
<ide> String output = "";
<del> /*
<del> * for(FG fg : listFG)
<add>
<add> for(FG fg : listFG)
<ide> {
<ide> output += fg.Name + "(" + fg.AnnualVolume + "), ";
<ide> }
<del> */
<del> for(NPD npd : listNPD)
<del> {
<del> output += "Name: " + npd.Name + ", ";
<del> }
<ide> return output;
<ide>
<ide> |
|
JavaScript | bsd-3-clause | 23d275211a9430b3802c668028961855bae68033 | 0 | urvashi01/react-native,ankitsinghania94/react-native,martinbigio/react-native,happypancake/react-native,salanki/react-native,facebook/react-native,tszajna0/react-native,peterp/react-native,Bhullnatik/react-native,hoastoolshop/react-native,Livyli/react-native,esauter5/react-native,nathanajah/react-native,xiayz/react-native,satya164/react-native,corbt/react-native,corbt/react-native,happypancake/react-native,ultralame/react-native,callstack-io/react-native,foghina/react-native,nickhudkins/react-native,xiayz/react-native,tadeuzagallo/react-native,adamjmcgrath/react-native,ptmt/react-native-macos,shrutic/react-native,thotegowda/react-native,salanki/react-native,DannyvanderJagt/react-native,hoangpham95/react-native,catalinmiron/react-native,vjeux/react-native,dikaiosune/react-native,tsjing/react-native,callstack-io/react-native,exponent/react-native,jevakallio/react-native,BretJohnson/react-native,skatpgusskat/react-native,ndejesus1227/react-native,jhen0409/react-native,farazs/react-native,formatlos/react-native,Bhullnatik/react-native,negativetwelve/react-native,hammerandchisel/react-native,facebook/react-native,Guardiannw/react-native,arthuralee/react-native,forcedotcom/react-native,cpunion/react-native,gilesvangruisen/react-native,mrspeaker/react-native,nickhudkins/react-native,Purii/react-native,makadaw/react-native,jevakallio/react-native,tadeuzagallo/react-native,eduardinni/react-native,jhen0409/react-native,jhen0409/react-native,catalinmiron/react-native,thotegowda/react-native,rickbeerendonk/react-native,htc2u/react-native,javache/react-native,gilesvangruisen/react-native,skatpgusskat/react-native,Maxwell2022/react-native,corbt/react-native,mironiasty/react-native,javache/react-native,martinbigio/react-native,vjeux/react-native,skevy/react-native,tgoldenberg/react-native,makadaw/react-native,Livyli/react-native,formatlos/react-native,hoangpham95/react-native,skatpgusskat/react-native,Swaagie/react-native,wesley1001/react-native,jaggs6/react-native,exponent/react-native,Andreyco/react-native,Tredsite/react-native,tadeuzagallo/react-native,gre/react-native,csatf/react-native,browniefed/react-native,CntChen/react-native,CntChen/react-native,rebeccahughes/react-native,tgoldenberg/react-native,lprhodes/react-native,farazs/react-native,dikaiosune/react-native,gilesvangruisen/react-native,callstack-io/react-native,Livyli/react-native,tszajna0/react-native,ptmt/react-native-macos,negativetwelve/react-native,iodine/react-native,foghina/react-native,kesha-antonov/react-native,pandiaraj44/react-native,jevakallio/react-native,hammerandchisel/react-native,csatf/react-native,jevakallio/react-native,compulim/react-native,arbesfeld/react-native,gitim/react-native,ultralame/react-native,esauter5/react-native,cdlewis/react-native,hoastoolshop/react-native,philikon/react-native,imjerrybao/react-native,skatpgusskat/react-native,dikaiosune/react-native,shrutic123/react-native,BretJohnson/react-native,InterfaceInc/react-native,luqin/react-native,exponent/react-native,dikaiosune/react-native,kesha-antonov/react-native,facebook/react-native,Bhullnatik/react-native,BretJohnson/react-native,cpunion/react-native,Guardiannw/react-native,nathanajah/react-native,Emilios1995/react-native,formatlos/react-native,aljs/react-native,foghina/react-native,Guardiannw/react-native,janicduplessis/react-native,jevakallio/react-native,corbt/react-native,ptomasroos/react-native,Tredsite/react-native,skevy/react-native,callstack-io/react-native,hammerandchisel/react-native,jasonnoahchoi/react-native,adamjmcgrath/react-native,hayeah/react-native,DerayGa/react-native,chnfeeeeeef/react-native,satya164/react-native,jadbox/react-native,aaron-goshine/react-native,martinbigio/react-native,janicduplessis/react-native,mironiasty/react-native,ultralame/react-native,DannyvanderJagt/react-native,gilesvangruisen/react-native,makadaw/react-native,adamjmcgrath/react-native,janicduplessis/react-native,doochik/react-native,wesley1001/react-native,formatlos/react-native,browniefed/react-native,alin23/react-native,myntra/react-native,rickbeerendonk/react-native,nickhudkins/react-native,xiayz/react-native,BretJohnson/react-native,orenklein/react-native,catalinmiron/react-native,charlesvinette/react-native,jaggs6/react-native,javache/react-native,CntChen/react-native,DanielMSchmidt/react-native,ptmt/react-native-macos,naoufal/react-native,thotegowda/react-native,charlesvinette/react-native,csatf/react-native,Maxwell2022/react-native,rickbeerendonk/react-native,wesley1001/react-native,myntra/react-native,DerayGa/react-native,ptmt/react-native-macos,eduardinni/react-native,dubert/react-native,Swaagie/react-native,callstack-io/react-native,forcedotcom/react-native,DannyvanderJagt/react-native,hoangpham95/react-native,luqin/react-native,CntChen/react-native,hayeah/react-native,tszajna0/react-native,alin23/react-native,CodeLinkIO/react-native,jeffchienzabinet/react-native,aljs/react-native,tsjing/react-native,facebook/react-native,frantic/react-native,hoangpham95/react-native,cdlewis/react-native,rickbeerendonk/react-native,eduardinni/react-native,DerayGa/react-native,lelandrichardson/react-native,imDangerous/react-native,jeffchienzabinet/react-native,dubert/react-native,dubert/react-native,lelandrichardson/react-native,kesha-antonov/react-native,formatlos/react-native,Ehesp/react-native,naoufal/react-native,nickhudkins/react-native,ptomasroos/react-native,imjerrybao/react-native,jadbox/react-native,nickhudkins/react-native,Emilios1995/react-native,cpunion/react-native,Tredsite/react-native,mrspeaker/react-native,csatf/react-native,orenklein/react-native,Ehesp/react-native,eduardinni/react-native,jeffchienzabinet/react-native,cpunion/react-native,Swaagie/react-native,satya164/react-native,hoastoolshop/react-native,cpunion/react-native,machard/react-native,aaron-goshine/react-native,farazs/react-native,DerayGa/react-native,charlesvinette/react-native,myntra/react-native,pandiaraj44/react-native,kesha-antonov/react-native,aljs/react-native,martinbigio/react-native,cosmith/react-native,arbesfeld/react-native,doochik/react-native,cdlewis/react-native,happypancake/react-native,Maxwell2022/react-native,imDangerous/react-native,skevy/react-native,Ehesp/react-native,shrutic/react-native,imjerrybao/react-native,dubert/react-native,skatpgusskat/react-native,Bhullnatik/react-native,InterfaceInc/react-native,iodine/react-native,mironiasty/react-native,wenpkpk/react-native,kesha-antonov/react-native,alin23/react-native,happypancake/react-native,InterfaceInc/react-native,farazs/react-native,browniefed/react-native,facebook/react-native,happypancake/react-native,javache/react-native,urvashi01/react-native,ptomasroos/react-native,clozr/react-native,Tredsite/react-native,htc2u/react-native,arbesfeld/react-native,DerayGa/react-native,satya164/react-native,formatlos/react-native,catalinmiron/react-native,tszajna0/react-native,hoangpham95/react-native,Ehesp/react-native,pandiaraj44/react-native,dubert/react-native,cdlewis/react-native,DanielMSchmidt/react-native,orenklein/react-native,salanki/react-native,luqin/react-native,nathanajah/react-native,nickhudkins/react-native,cosmith/react-native,exponent/react-native,gre/react-native,hoangpham95/react-native,machard/react-native,Swaagie/react-native,gre/react-native,skatpgusskat/react-native,chnfeeeeeef/react-native,BretJohnson/react-native,orenklein/react-native,DannyvanderJagt/react-native,machard/react-native,wesley1001/react-native,DannyvanderJagt/react-native,pandiaraj44/react-native,shrutic123/react-native,jhen0409/react-native,Maxwell2022/react-native,Tredsite/react-native,Swaagie/react-native,gilesvangruisen/react-native,negativetwelve/react-native,christopherdro/react-native,mironiasty/react-native,pandiaraj44/react-native,javache/react-native,Guardiannw/react-native,ptmt/react-native-macos,orenklein/react-native,Bhullnatik/react-native,tadeuzagallo/react-native,PlexChat/react-native,Andreyco/react-native,frantic/react-native,ultralame/react-native,callstack-io/react-native,imDangerous/react-native,brentvatne/react-native,makadaw/react-native,PlexChat/react-native,rickbeerendonk/react-native,tsjing/react-native,Emilios1995/react-native,philikon/react-native,tarkus/react-native-appletv,gitim/react-native,machard/react-native,ankitsinghania94/react-native,Maxwell2022/react-native,adamjmcgrath/react-native,shrutic123/react-native,lelandrichardson/react-native,imjerrybao/react-native,skevy/react-native,PlexChat/react-native,arthuralee/react-native,machard/react-native,DanielMSchmidt/react-native,christopherdro/react-native,foghina/react-native,mironiasty/react-native,tszajna0/react-native,eduardinni/react-native,lelandrichardson/react-native,happypancake/react-native,hoastoolshop/react-native,exponentjs/react-native,rebeccahughes/react-native,htc2u/react-native,Purii/react-native,esauter5/react-native,clozr/react-native,DanielMSchmidt/react-native,aaron-goshine/react-native,corbt/react-native,ankitsinghania94/react-native,aaron-goshine/react-native,InterfaceInc/react-native,CodeLinkIO/react-native,wenpkpk/react-native,hayeah/react-native,eduardinni/react-native,Andreyco/react-native,nickhudkins/react-native,browniefed/react-native,dikaiosune/react-native,CntChen/react-native,esauter5/react-native,Guardiannw/react-native,xiayz/react-native,javache/react-native,corbt/react-native,cdlewis/react-native,Andreyco/react-native,brentvatne/react-native,peterp/react-native,naoufal/react-native,nickhudkins/react-native,naoufal/react-native,janicduplessis/react-native,forcedotcom/react-native,facebook/react-native,CntChen/react-native,clozr/react-native,tgoldenberg/react-native,doochik/react-native,charlesvinette/react-native,negativetwelve/react-native,urvashi01/react-native,gitim/react-native,jaggs6/react-native,jevakallio/react-native,imDangerous/react-native,Ehesp/react-native,iodine/react-native,aaron-goshine/react-native,csatf/react-native,cosmith/react-native,Livyli/react-native,wesley1001/react-native,makadaw/react-native,jeffchienzabinet/react-native,christopherdro/react-native,cpunion/react-native,lelandrichardson/react-native,Purii/react-native,CodeLinkIO/react-native,esauter5/react-native,catalinmiron/react-native,adamjmcgrath/react-native,tadeuzagallo/react-native,BretJohnson/react-native,urvashi01/react-native,philikon/react-native,satya164/react-native,shrutic/react-native,urvashi01/react-native,brentvatne/react-native,gre/react-native,satya164/react-native,imDangerous/react-native,rickbeerendonk/react-native,lprhodes/react-native,hammerandchisel/react-native,esauter5/react-native,gilesvangruisen/react-native,aljs/react-native,thotegowda/react-native,shrutic123/react-native,rebeccahughes/react-native,janicduplessis/react-native,wenpkpk/react-native,ndejesus1227/react-native,corbt/react-native,skevy/react-native,formatlos/react-native,hammerandchisel/react-native,gitim/react-native,catalinmiron/react-native,foghina/react-native,imDangerous/react-native,dubert/react-native,forcedotcom/react-native,ndejesus1227/react-native,foghina/react-native,jadbox/react-native,ankitsinghania94/react-native,alin23/react-native,urvashi01/react-native,tadeuzagallo/react-native,Purii/react-native,xiayz/react-native,CodeLinkIO/react-native,happypancake/react-native,negativetwelve/react-native,peterp/react-native,ptomasroos/react-native,myntra/react-native,PlexChat/react-native,CodeLinkIO/react-native,Maxwell2022/react-native,browniefed/react-native,doochik/react-native,iodine/react-native,javache/react-native,jhen0409/react-native,compulim/react-native,tgoldenberg/react-native,iodine/react-native,chnfeeeeeef/react-native,jeffchienzabinet/react-native,chnfeeeeeef/react-native,vjeux/react-native,InterfaceInc/react-native,jasonnoahchoi/react-native,cpunion/react-native,shrutic/react-native,catalinmiron/react-native,wenpkpk/react-native,myntra/react-native,tarkus/react-native-appletv,salanki/react-native,htc2u/react-native,exponentjs/react-native,tarkus/react-native-appletv,gre/react-native,satya164/react-native,salanki/react-native,peterp/react-native,charlesvinette/react-native,DannyvanderJagt/react-native,makadaw/react-native,brentvatne/react-native,ndejesus1227/react-native,myntra/react-native,christopherdro/react-native,Maxwell2022/react-native,compulim/react-native,aaron-goshine/react-native,foghina/react-native,exponentjs/react-native,martinbigio/react-native,chnfeeeeeef/react-native,luqin/react-native,Andreyco/react-native,csatf/react-native,Purii/react-native,browniefed/react-native,imjerrybao/react-native,wesley1001/react-native,shrutic123/react-native,pandiaraj44/react-native,InterfaceInc/react-native,esauter5/react-native,thotegowda/react-native,hoastoolshop/react-native,alin23/react-native,doochik/react-native,exponent/react-native,janicduplessis/react-native,javache/react-native,mironiasty/react-native,tsjing/react-native,aaron-goshine/react-native,hammerandchisel/react-native,gre/react-native,Emilios1995/react-native,christopherdro/react-native,myntra/react-native,forcedotcom/react-native,xiayz/react-native,Guardiannw/react-native,frantic/react-native,jaggs6/react-native,arthuralee/react-native,Bhullnatik/react-native,gre/react-native,luqin/react-native,tsjing/react-native,arthuralee/react-native,gre/react-native,iodine/react-native,dikaiosune/react-native,charlesvinette/react-native,peterp/react-native,facebook/react-native,rickbeerendonk/react-native,iodine/react-native,salanki/react-native,ptomasroos/react-native,gitim/react-native,xiayz/react-native,tarkus/react-native-appletv,facebook/react-native,luqin/react-native,rickbeerendonk/react-native,Livyli/react-native,jevakallio/react-native,jadbox/react-native,jeffchienzabinet/react-native,Andreyco/react-native,htc2u/react-native,Purii/react-native,lelandrichardson/react-native,vjeux/react-native,martinbigio/react-native,salanki/react-native,ndejesus1227/react-native,shrutic/react-native,shrutic/react-native,naoufal/react-native,Guardiannw/react-native,clozr/react-native,cdlewis/react-native,skevy/react-native,shrutic123/react-native,shrutic123/react-native,jasonnoahchoi/react-native,tsjing/react-native,kesha-antonov/react-native,naoufal/react-native,skevy/react-native,mrspeaker/react-native,compulim/react-native,DerayGa/react-native,peterp/react-native,Andreyco/react-native,lprhodes/react-native,htc2u/react-native,christopherdro/react-native,cpunion/react-native,jeffchienzabinet/react-native,ankitsinghania94/react-native,forcedotcom/react-native,martinbigio/react-native,makadaw/react-native,farazs/react-native,jasonnoahchoi/react-native,wenpkpk/react-native,mrspeaker/react-native,callstack-io/react-native,lelandrichardson/react-native,peterp/react-native,cdlewis/react-native,wenpkpk/react-native,dubert/react-native,ptomasroos/react-native,peterp/react-native,christopherdro/react-native,brentvatne/react-native,mironiasty/react-native,makadaw/react-native,rebeccahughes/react-native,jeffchienzabinet/react-native,frantic/react-native,naoufal/react-native,machard/react-native,Swaagie/react-native,philikon/react-native,hoangpham95/react-native,hammerandchisel/react-native,dikaiosune/react-native,negativetwelve/react-native,exponent/react-native,wesley1001/react-native,pandiaraj44/react-native,urvashi01/react-native,negativetwelve/react-native,formatlos/react-native,farazs/react-native,negativetwelve/react-native,farazs/react-native,machard/react-native,chnfeeeeeef/react-native,Emilios1995/react-native,forcedotcom/react-native,thotegowda/react-native,arbesfeld/react-native,Ehesp/react-native,jhen0409/react-native,PlexChat/react-native,brentvatne/react-native,aaron-goshine/react-native,doochik/react-native,tgoldenberg/react-native,Emilios1995/react-native,DanielMSchmidt/react-native,gitim/react-native,kesha-antonov/react-native,shrutic123/react-native,alin23/react-native,philikon/react-native,jadbox/react-native,tsjing/react-native,lprhodes/react-native,hammerandchisel/react-native,myntra/react-native,lprhodes/react-native,orenklein/react-native,happypancake/react-native,ankitsinghania94/react-native,csatf/react-native,philikon/react-native,tadeuzagallo/react-native,charlesvinette/react-native,PlexChat/react-native,htc2u/react-native,rickbeerendonk/react-native,exponentjs/react-native,cdlewis/react-native,philikon/react-native,Livyli/react-native,arbesfeld/react-native,CntChen/react-native,negativetwelve/react-native,tarkus/react-native-appletv,browniefed/react-native,tarkus/react-native-appletv,skatpgusskat/react-native,mironiasty/react-native,CodeLinkIO/react-native,chnfeeeeeef/react-native,jevakallio/react-native,exponent/react-native,tszajna0/react-native,mrspeaker/react-native,tszajna0/react-native,facebook/react-native,aljs/react-native,Purii/react-native,gitim/react-native,wenpkpk/react-native,exponentjs/react-native,orenklein/react-native,Bhullnatik/react-native,esauter5/react-native,InterfaceInc/react-native,Tredsite/react-native,Emilios1995/react-native,dikaiosune/react-native,CntChen/react-native,Guardiannw/react-native,janicduplessis/react-native,Maxwell2022/react-native,salanki/react-native,brentvatne/react-native,skatpgusskat/react-native,Purii/react-native,browniefed/react-native,Andreyco/react-native,hoastoolshop/react-native,ankitsinghania94/react-native,clozr/react-native,myntra/react-native,hoastoolshop/react-native,nathanajah/react-native,mironiasty/react-native,catalinmiron/react-native,shrutic/react-native,eduardinni/react-native,ptmt/react-native-macos,makadaw/react-native,jhen0409/react-native,alin23/react-native,CodeLinkIO/react-native,ndejesus1227/react-native,eduardinni/react-native,clozr/react-native,mrspeaker/react-native,martinbigio/react-native,hayeah/react-native,ptomasroos/react-native,luqin/react-native,nathanajah/react-native,lelandrichardson/react-native,callstack-io/react-native,doochik/react-native,brentvatne/react-native,frantic/react-native,htc2u/react-native,exponentjs/react-native,PlexChat/react-native,jaggs6/react-native,tgoldenberg/react-native,DerayGa/react-native,thotegowda/react-native,jevakallio/react-native,imDangerous/react-native,Tredsite/react-native,BretJohnson/react-native,Swaagie/react-native,dubert/react-native,clozr/react-native,vjeux/react-native,compulim/react-native,urvashi01/react-native,cosmith/react-native,doochik/react-native,lprhodes/react-native,cosmith/react-native,doochik/react-native,arbesfeld/react-native,Emilios1995/react-native,jaggs6/react-native,tgoldenberg/react-native,jasonnoahchoi/react-native,naoufal/react-native,imjerrybao/react-native,cosmith/react-native,exponentjs/react-native,jadbox/react-native,cdlewis/react-native,Livyli/react-native,ptmt/react-native-macos,alin23/react-native,xiayz/react-native,adamjmcgrath/react-native,jaggs6/react-native,nathanajah/react-native,gitim/react-native,adamjmcgrath/react-native,pandiaraj44/react-native,wenpkpk/react-native,exponentjs/react-native,hayeah/react-native,javache/react-native,jaggs6/react-native,ptmt/react-native-macos,imDangerous/react-native,DannyvanderJagt/react-native,Bhullnatik/react-native,tsjing/react-native,iodine/react-native,cosmith/react-native,Swaagie/react-native,aljs/react-native,Ehesp/react-native,exponent/react-native,tszajna0/react-native,wesley1001/react-native,machard/react-native,arbesfeld/react-native,DanielMSchmidt/react-native,foghina/react-native,jadbox/react-native,nathanajah/react-native,DanielMSchmidt/react-native,tarkus/react-native-appletv,jadbox/react-native,chnfeeeeeef/react-native,philikon/react-native,rebeccahughes/react-native,DerayGa/react-native,christopherdro/react-native,skevy/react-native,charlesvinette/react-native,aljs/react-native,forcedotcom/react-native,farazs/react-native,ankitsinghania94/react-native,kesha-antonov/react-native,mrspeaker/react-native,thotegowda/react-native,tarkus/react-native-appletv,ultralame/react-native,brentvatne/react-native,CodeLinkIO/react-native,kesha-antonov/react-native,nathanajah/react-native,hoastoolshop/react-native,gilesvangruisen/react-native,lprhodes/react-native,cosmith/react-native,Livyli/react-native,tadeuzagallo/react-native,lprhodes/react-native,ptomasroos/react-native,ndejesus1227/react-native,ndejesus1227/react-native,PlexChat/react-native,hoangpham95/react-native,imjerrybao/react-native,DanielMSchmidt/react-native,janicduplessis/react-native,farazs/react-native,tgoldenberg/react-native,aljs/react-native,orenklein/react-native,imjerrybao/react-native,adamjmcgrath/react-native,InterfaceInc/react-native,formatlos/react-native,jasonnoahchoi/react-native,corbt/react-native,gilesvangruisen/react-native,csatf/react-native,jhen0409/react-native,clozr/react-native,Ehesp/react-native,arbesfeld/react-native,arthuralee/react-native,jasonnoahchoi/react-native,satya164/react-native,BretJohnson/react-native,DannyvanderJagt/react-native,jasonnoahchoi/react-native,mrspeaker/react-native,Tredsite/react-native,luqin/react-native,shrutic/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var React = require('React');
var Site = require('Site');
var center = require('center');
var featured = [
{
name: 'Facebook Groups',
icon: 'http://is4.mzstatic.com/image/pf/us/r30/Purple69/v4/57/f8/4c/57f84c0c-793d-5f9a-95ee-c212d0369e37/mzl.ugjwfhzx.png',
link: 'https://itunes.apple.com/us/app/facebook-groups/id931735837?mt=8',
author: 'Facebook',
},
{
name: 'Facebook Ads Manager',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple5/v4/9e/16/86/9e1686ef-cc55-805a-c977-538ddb5e6832/mzl.gqbhwitj.png',
linkAppStore: 'https://itunes.apple.com/us/app/facebook-ads-manager/id964397083?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.facebook.adsmanager',
author: 'Facebook',
blogs: [
"https://code.facebook.com/posts/1014532261909640/react-native-bringing-modern-web-techniques-to-mobile/",
"https://code.facebook.com/posts/1189117404435352/react-native-for-android-how-we-built-the-first-cross-platform-react-native-app/",
"https://code.facebook.com/posts/435862739941212/making-react-native-apps-accessible/",
],
},
{
name: 'AIGA Design Conference 2015',
icon: 'http://a5.mzstatic.com/us/r30/Purple69/v4/b0/4b/29/b04b2939-88d2-f61f-dec9-24fae083d8b3/icon175x175.png',
link: 'https://itunes.apple.com/us/app/aiga-design-conference-2015/id1038145272?ls=1&mt=8',
author: 'W&Co',
},
{
name: 'Discord',
icon: 'http://a5.mzstatic.com/us/r30/Purple5/v4/c1/2f/4c/c12f4cba-1d9a-f6bf-2240-04085d3470ec/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/discord-chat-for-gamers/id985746746?mt=8',
author: 'Hammer & Chisel',
},
{
name: 'Discovery VR',
icon: 'http://a2.mzstatic.com/us/r30/Purple6/v4/d1/d5/f4/d1d5f437-9f6b-b5aa-5fe7-47bd19f934bf/icon175x175.png',
link: 'https://itunes.apple.com/us/app/discovery-vr/id1030815031?mt=8',
author: 'Discovery Communications',
blog: [
"https://medium.com/ios-os-x-development/an-ios-developer-on-react-native-1f24786c29f0",
],
},
{
name: 'Exponent',
icon: 'http://a4.mzstatic.com/us/r30/Purple2/v4/3a/d3/c9/3ad3c96c-5e14-f988-4bdd-0fdc95efd140/icon175x175.png',
link: 'http://exponentjs.com/',
author: 'Exponent',
},
{
name: 'Lrn',
icon: 'http://is4.mzstatic.com/image/pf/us/r30/Purple1/v4/41/a9/e9/41a9e9b6-7801-aef7-2400-2eca14923321/mzl.adyswxad.png',
link: 'https://itunes.apple.com/us/app/lrn-learn-to-code-at-your/id1019622677',
author: 'Lrn Labs, Inc',
},
{
name: 'Movie Trailers by MovieLaLa',
icon: 'https://lh3.googleusercontent.com/16aug4m_6tvJB7QZden9w1SOMqpZgNp7rHqDhltZNvofw1a4V_ojGGXUMPGiK0dDCqzL=w300',
linkAppStore: 'https://itunes.apple.com/us/app/movie-trailers-by-movielala/id1001416601?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.movielala.trailers',
author: 'MovieLaLa'
},
{
name: 'MyMuesli',
icon: 'https://lh3.googleusercontent.com/1dCCeiyjuWRgY-Cnv-l-lOA1sVH3Cn0vkVWWZnaBQbhHOhsngLcnfy68WEerudPUysc=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.mymuesli',
author: 'Shawn Khameneh (@shawnscode), 3DWD'
},
{
name: 'Myntra',
icon: 'http://a5.mzstatic.com/us/r30/Purple6/v4/9c/78/df/9c78dfa6-0061-1af2-5026-3e1d5a073c94/icon350x350.png',
link: 'https://itunes.apple.com/in/app/myntra-fashion-shopping-app/id907394059',
author: 'Myntra Designs',
},
{
name: 'Noodler',
icon: 'http://a5.mzstatic.com/us/r30/Purple6/v4/d9/9a/69/d99a6919-7f11-35ad-76ea-f1741643d875/icon175x175.png',
link: 'http://www.noodler-app.com/',
author: 'Michele Humes & Joshua Sierles',
},
{
name: 'React Native Playground',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple1/v4/20/ec/8e/20ec8eb8-9e12-6686-cd16-7ac9e3ef1d52/mzl.ngvuoybx.png',
linkAppStore: 'https://itunes.apple.com/us/app/react-native-playground/id1002032944?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=org.rnplay.playground',
author: 'Joshua Sierles',
},
{
name: 'Round - A better way to remember your medicine',
icon: 'https://s3.mzstatic.com/us/r30/Purple69/v4/d3/ee/54/d3ee54cf-13b6-5f56-0edc-6c70ac90b2be/icon175x175.png',
link: 'https://itunes.apple.com/us/app/round-beautiful-medication/id1059591124?mt=8',
author: 'Circadian Design',
},
{
name: 'Running',
icon: 'http://a1.mzstatic.com/us/r30/Purple3/v4/33/eb/4f/33eb4f73-c7e3-8659-9285-f758e403485b/icon175x175.jpeg',
link: 'https://gyrosco.pe/running/',
author: 'Gyroscope Innovations',
blogs: [
'https://blog.gyrosco.pe/the-making-of-gyroscope-running-a4ad10acc0d0',
],
},
{
name: 'SoundCloud Pulse',
icon: 'https://i1.sndcdn.com/artworks-000149203716-k5je96-original.jpg',
link: 'https://itunes.apple.com/us/app/soundcloud-pulse-for-creators/id1074278256?mt=8',
author: 'SoundCloud',
},
{
name: 'Spero for Cancer',
icon: 'https://s3-us-west-1.amazonaws.com/cancerspot/site_images/Spero1024.png',
link: 'https://geo.itunes.apple.com/us/app/spero-for-cancer/id1033923573?mt=8',
author: 'Spero.io',
videos: [
'https://www.youtube.com/watch?v=JImX3L6qnj8',
],
},
{
name: 'Squad',
icon: 'http://a4.mzstatic.com/us/r30/Purple69/v4/e8/5b/3f/e85b3f52-72f3-f427-a32e-a73efe2e9682/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/squad-snaps-for-groups-friends/id1043626975?mt=8',
author: 'Tackk Inc.',
},
{
name: 'Start - medication manager for depression',
icon: 'http://a1.mzstatic.com/us/r30/Purple49/v4/de/9b/6f/de9b6fe8-84ea-7a12-ba2c-0a6d6c7b10b0/icon175x175.png',
link: 'https://itunes.apple.com/us/app/start-medication-manager-for/id1012099928?mt=8',
author: 'Iodine Inc.',
},
{
name: 'This AM',
icon: 'http://s3.r29static.com//bin/public/efe/x/1542038/image.png',
link: 'https://itunes.apple.com/us/app/refinery29-this-am-top-breaking/id988472315?mt=8',
author: 'Refinery29',
},
{
name: 'Townske',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/8b/42/20/8b4220af-5165-91fd-0f05-014332df73ef/icon175x175.png',
link: 'https://itunes.apple.com/us/app/townske-stunning-city-guides/id1018136179?ls=1&mt=8',
author: 'Townske PTY LTD',
},
{
name: 'Tucci',
icon: 'http://a3.mzstatic.com/us/r30/Purple3/v4/c0/0c/95/c00c95ce-4cc5-e516-db77-5c5164b89189/icon175x175.jpeg',
link: 'https://itunes.apple.com/app/apple-store/id1039661754?mt=8',
author: 'Clay Allsopp & Tiffany Young',
blogs: [
'https://medium.com/@clayallsopp/making-tucci-what-is-it-and-why-eaa2bf94c1df#.lmm3dmkaf',
'https://medium.com/@clayallsopp/making-tucci-the-technical-details-cc7aded6c75f#.wf72nq372',
],
},
{
name: 'WPV',
icon: 'http://a2.mzstatic.com/us/r30/Purple49/v4/a8/26/d7/a826d7bf-337b-c6b8-488d-aca98027754d/icon350x350.png',
link: 'https://itunes.apple.com/us/app/wpv/id725222647?mt=8',
author: 'Yamill Vallecillo',
},
{
name: 'Zhopout',
icon: 'http://zhopout.com/Content/Images/zhopout-logo-app-3.png',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.zhopout',
author: 'Jarvis Software Private Limited ',
blogs: [
"https://medium.com/@murugandurai/how-we-developed-our-mobile-app-in-30-days-using-react-native-45affa6449e8#.29nnretsi",
],
},
];
var apps = [
{
name: 'Accio',
icon: 'http://a3.mzstatic.com/us/r30/Purple3/v4/03/a1/5b/03a15b9f-04d7-a70a-620a-9c9850a859aa/icon175x175.png',
link: 'https://itunes.apple.com/us/app/accio-on-demand-delivery/id1047060673?mt=8',
author: 'Accio Delivery Inc.',
},
{
name: 'ArcChat.com',
icon: 'https://lh3.googleusercontent.com/mZJjidMobu3NAZApdtp-vdBBzIWzCNTaIcKShbGqwXRRzL3B9bbi6E0eRuykgT6vmg=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.arcchat',
author: 'Lukas Liesis',
},
{
name: 'Beetroot',
icon: 'http://is1.mzstatic.com/image/pf/us/r30/Purple5/v4/66/fd/dd/66fddd70-f848-4fc5-43ee-4d52197ccab8/pr_source.png',
link: 'https://itunes.apple.com/us/app/beetroot/id1016159001?ls=1&mt=8',
author: 'Alex Duckmanton',
},
{
name: 'Bhagavad Gita Lite',
icon: 'https://s3-us-west-2.amazonaws.com/bhagavadgitaapp/gita-free.png',
link: 'https://itunes.apple.com/us/app/bhagavad-gita-lite/id1071711190?ls=1&mt=8',
author: 'Tom Goldenberg & Nick Brown'
},
{
name: 'Bionic eStore',
icon: 'http://a5.mzstatic.com/us/r30/Purple7/v4/c1/9a/3f/c19a3f82-ecc3-d60b-f983-04acc203705f/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/bionic-estore/id994537615?mt=8',
author: 'Digidemon',
},
{
name: 'breathe Meditation Timer',
icon: 'http://a2.mzstatic.com/eu/r30/Purple49/v4/09/21/d2/0921d265-087a-98f0-58ce-bbf9d44b114d/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/de/app/breathe-meditation-timer/id1087354227?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.idearockers.breathe',
author: 'idearockers UG',
},
{
name: 'CANDDi',
icon: 'http://a5.mzstatic.com/eu/r30/Purple7/v4/c4/e4/85/c4e48546-7127-a133-29f2-3e2e1aa0f9af/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/gb/app/canddi/id1018168131?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.canddi',
author: 'CANDDi LTD.',
},
{
name: 'CaratLane',
icon: 'https://lh3.googleusercontent.com/wEN-Vvpbnw_n89dbXPxWkNnXB7sALKBKvpX_hbzrWbuC4tFi5tVkWHq8k5TAvdbf5UQ=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.caratlane.android&hl=en',
author: 'CaratLane',
},
{
name: 'CBS Sports Franchise Football',
icon: 'http://a2.mzstatic.com/us/r30/Purple69/v4/7b/0c/a0/7b0ca007-885a-7cfc-9fa2-2ec4394c2ecc/icon175x175.png',
link: 'https://play.google.com/store/apps/details?id=com.cbssports.fantasy.franchisefootball2015',
author: 'CBS Sports',
},
{
name: 'Choke - Rap Battle With Friends',
icon: 'http://a3.mzstatic.com/us/r30/Purple49/v4/3e/83/85/3e8385d8-140f-da38-a100-1393cef3e816/icon175x175.png',
link: 'https://itunes.apple.com/us/app/choke-rap-battle-with-friends/id1077937445?ls=1&mt=8',
author: 'Henry Kirkness',
},
{
name: 'Codementor - Live 1:1 Expert Developer Help',
icon: 'http://a1.mzstatic.com/us/r30/Purple3/v4/db/cf/35/dbcf3523-bac7-0f54-c6a8-a80bf4f43c38/icon175x175.jpeg',
link: 'https://www.codementor.io/downloads',
author: 'Codementor',
},
{
name: 'Collegiate - Learn Anywhere',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/17/a9/60/17a960d3-8cbd-913a-9f08-ebd9139c116c/icon175x175.png',
link: 'https://itunes.apple.com/app/id1072463482',
author: 'Gaurav Arora',
},
{
name: 'Company name search',
icon: 'http://a4.mzstatic.com/us/r30/Purple69/v4/fd/47/53/fd47537c-5861-e208-d1d1-1e26b5e45a36/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/company-name-search/id1043824076',
author: 'The Formations Factory Ltd',
blogs: [
'https://medium.com/formations-factory/creating-company-name-search-app-with-react-native-36a049b0848d',
],
},
{
name: 'DareU',
icon: 'http://a3.mzstatic.com/us/r30/Purple6/v4/10/fb/6a/10fb6a50-57c8-061a-d865-503777bf7f00/icon175x175.png',
link: 'https://itunes.apple.com/us/app/dareu-dare-your-friends-dare/id1046434563?mt=8',
author: 'Rishabh Mehan',
},
{
name: 'Deskbookers',
icon: 'http://a4.mzstatic.com/eu/r30/Purple69/v4/be/61/7d/be617d63-88f5-5629-7ac0-bc2c9eb4802a/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/nl/app/deskbookers/id964447401?mt=8',
author: 'Emilio Rodriguez'
},
{
name: 'DockMan',
icon: 'http://a1.mzstatic.com/us/r30/Purple49/v4/91/b5/75/91b57552-d9bc-d8bc-10a1-617de920aaa6/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/app/dockman/id1061469696',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.s21g.DockMan',
blogs: [
'http://www.s21g.com/DockMan.html',
],
author: 'Genki Takiuchi (s21g Inc.)',
},
{
name: 'Due',
icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/a2/41/5d/a2415d5f-407a-c565-ffb4-4f27f23d8ac2/icon175x175.png',
link: 'https://itunes.apple.com/us/app/due-countdown-reminders-for/id1050909468?mt=8',
author: 'Dotan Nahum',
},
{
name: 'Eat or Not',
icon: 'http://a3.mzstatic.com/us/r30/Purple5/v4/51/be/34/51be3462-b015-ebf2-11c5-69165b37fadc/icon175x175.jpeg',
linkAppStore: 'https://itunes.apple.com/us/app/eat-or-not/id1054565697?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.eon',
author: 'Sharath Prabhal',
},
{
name: 'Fan of it',
icon: 'http://a4.mzstatic.com/us/r30/Purple3/v4/c9/3f/e8/c93fe8fb-9332-e744-f04a-0f4f78e42aa8/icon350x350.png',
link: 'https://itunes.apple.com/za/app/fan-of-it/id1017025530?mt=8',
author: 'Fan of it (Pty) Ltd',
},
{
name: 'FastPaper',
icon: 'http://a2.mzstatic.com/us/r30/Purple5/v4/72/b4/d8/72b4d866-90d2-3aad-d1dc-0315f2d9d045/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/fast-paper/id1001174614',
author: 'Liubomyr Mykhalchenko (@liubko)',
},
{
name: 'Feline for Product Hunt',
icon: 'https://lh3.googleusercontent.com/MCoiCCwUan0dxzqRR_Mrr7kO308roYdI2aTsIpUGYWzUmpJT1-R2_J04weQKFEd3Mg=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.arjunkomath.product_hunt&hl=en',
author: 'Arjun Komath',
},
{
name: 'Fixt',
icon: 'http://a5.mzstatic.com/us/r30/Purple69/v4/46/bc/66/46bc66a2-7775-4d24-235d-e1fe28d55d7f/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/us/app/dropbot-phone-replacement/id1000855694?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=co.fixt',
author: 'Fixt',
},
{
name: 'Foodstand',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/33/c1/3b/33c13b88-8ec2-23c1-56bb-712ad9938290/icon350x350.jpeg',
link: 'https://www.thefoodstand.com/download',
author: 'Foodstand, Inc.',
},
{
name: 'Go Fire',
icon: 'http://a2.mzstatic.com/us/r30/Purple5/v4/42/50/5a/42505a8d-3c7a-e49a-16e3-422315f24cf1/icon350x350.png',
link: 'https://itunes.apple.com/us/app/gou-huo/id1001476888?ls=1&mt=8',
author: 'beijing qingfengyun Technology Co., Ltd.',
},
{
name: 'HackerWeb',
icon: 'http://a5.mzstatic.com/us/r30/Purple49/v4/5a/bd/39/5abd3951-782c-ef12-8e40-33ebe1e43768/icon175x175.png',
link: 'https://itunes.apple.com/us/app/hackerweb/id1084209377?mt=8',
author: 'Lim Chee Aun',
},
{
name: 'Harmonizome',
icon: 'http://is1.mzstatic.com/image/thumb/Purple6/v4/18/a9/bc/18a9bcde-d2d9-7574-2664-e82fff7b7208/pr_source.png/350x350-75.png',
link: 'https://itunes.apple.com/us/app/harmonizome/id1046990905?mt=8',
author: 'Michael McDermott (@_mgmcdermott)',
},
{
name: 'Hashley',
icon: 'http://a2.mzstatic.com/us/r30/Purple4/v4/5f/19/fc/5f19fc13-e7af-cd6b-6749-cedabdaeee7d/icon350x350.png',
link: 'https://itunes.apple.com/us/app/hashtag-by-hashley-ironic/id1022724462?mt=8',
author: 'Elephant, LLC',
},
{
name: 'Hey, Neighbor!',
icon: 'https://raw.githubusercontent.com/scrollback/io.scrollback.neighborhoods/master/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png',
link: 'https://play.google.com/store/apps/details?id=io.scrollback.neighborhoods',
author: 'Scrollback',
},
{
name: 'Honest Reviews',
icon: 'http://honestreviews.techulus.com/icon.png',
link: 'https://play.google.com/store/apps/details?id=com.techulus.honestreviews&hl=en',
author: 'Arjun Komath',
},
{
name: 'Hover',
icon: 'http://a5.mzstatic.com/us/r30/Purple3/v4/ba/55/e6/ba55e6ee-71cf-b843-f592-0917c9b6c645/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/us/app/hover-1-drone-uav-pilot-app!/id947641516?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.analyticadevelopment.android.hover',
author: 'KevinEJohn',
},
{
name: 'HSK Level 1 Chinese Flashcards',
icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple1/v4/b2/4f/3a/b24f3ae3-2597-cc70-1040-731b425a5904/mzl.amxdcktl.jpg',
link: 'https://itunes.apple.com/us/app/hsk-level-1-chinese-flashcards/id936639994',
author: 'HS Schaaf',
},
{
name: 'Hubhopper',
icon: 'http://hubhopper.com/images/h_logo.jpg',
link: 'https://play.google.com/store/apps/details?id=com.hubhopper',
author: 'Soch Technologies',
},
{
name: 'Jukebox',
icon: 'https://s3.amazonaws.com/theartistunion-production/Jukebox-logo.png',
link: 'https://itunes.apple.com/us/app/jukebox-offline-music-player/id1072583255?ls=1&mt=8',
author: 'The Beat Drop Inc'
},
{
name: 'Kakapo',
icon: 'http://a2.mzstatic.com/eu/r30/Purple3/v4/12/ab/2a/12ab2a01-3a3c-9482-b8df-ab38ad281165/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/gb/app/kakapo/id1046673139?ls=1&mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.kakaponative',
author: 'Daniel Levitt',
},
{
name: 'Koza Gujarati Dictionary',
icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/77/95/83/77958377-05ae-4754-684a-3c9dbb67b517/icon175x175.jpeg',
link: 'https://itunes.apple.com/in/app/koza-english-to-gujarati-dictionary/id982752928?mt=8',
author: 'KozaApps',
},
{
name: 'Leanpub',
icon: 'http://a2.mzstatic.com/us/r30/Purple6/v4/9f/4a/6f/9f4a6f8c-8951-ed89-4083-74ace23df9ef/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/leanpub/id913517110?ls=1&mt=8',
author: 'Leanpub',
},
{
name: 'LoadDocs',
icon: 'http://a2.mzstatic.com/us/r30/Purple3/v4/b5/ca/78/b5ca78ca-392d-6874-48bf-762293482d42/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/loaddocs/id1041596066',
author: 'LoadDocs',
},
{
name: 'Lugg – Your On-Demand Mover',
icon: 'http://lh3.googleusercontent.com/EV9z7kRRME2KPMBRNHnje7bBNEl_Why2CFq-MfKzBC88uSFJTYr1HO3-nPt-JuVJwKFb=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.lugg',
author: 'Lugg',
},
{
name: 'Lumpen Radio',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple1/v4/46/43/00/464300b1-fae3-9640-d4a2-0eb050ea3ff2/mzl.xjjawige.png',
link: 'https://itunes.apple.com/us/app/lumpen-radio/id1002193127?mt=8',
author: 'Joshua Habdas',
},
{
name: 'Makerist Mediathek',
icon: 'http://a5.mzstatic.com/eu/r30/Purple3/v4/fa/5f/4c/fa5f4ce8-5aaa-5a4b-ddcc-a0c6f681d08a/icon175x175.png',
link: 'https://itunes.apple.com/de/app/makerist-mediathek/id1019504544',
author: 'Railslove',
},
{
name: 'MaxReward - Android',
icon: 'https://lh3.googleusercontent.com/yynCUCdEnyW6T96xCto8KzWQr4Yeiy0M6c2p8auYMIyFgAZVBsjf4JCEX7QkPijhBg=w175-rw',
linkAppStore: 'https://itunes.apple.com/us/app/maxreward/id1050479192?ls=1&mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.bitstrek.maxreward&hl=en',
author: 'Neil Ma',
},
{
name: 'MinTrain',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple5/v4/51/51/68/51516875-1323-3100-31a8-cd1853d9a2c0/mzl.gozwmstp.png',
link: 'https://itunes.apple.com/us/app/mintrain/id1015739031?mt=8',
author: 'Peter Cottle',
},
{
name: 'Mobabuild',
icon: 'http://mobabuild.co/images/applogo.png',
linkAppStore: 'https://itunes.apple.com/tr/app/mobabuild-builds-for-league/id1059193502?l=tr&mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.sercanov.mobabuild',
author: 'Sercan Demircan ( @sercanov )',
},
{
name: 'MockingBot',
icon: 'https://s3.cn-north-1.amazonaws.com.cn/modao/downloads/images/MockingBot175.png',
link: 'https://itunes.apple.com/cn/app/mockingbot/id1050565468?l=en&mt=8',
author: 'YuanYi Zhang (@mockingbot)',
},
{
name: 'MoneyLion',
icon: 'http://a5.mzstatic.com/us/r30/Purple69/v4/d7/9d/ad/d79daddc-8d67-8a6c-61e2-950425946dd2/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/moneylion/id1064677082?mt=8',
author: 'MoneyLion LLC',
},
{
name: 'Mr. Dapper',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple4/v4/e8/3f/7c/e83f7cb3-2602-f8e8-de9a-ce0a775a4a14/mzl.hmdjhfai.png',
link: 'https://itunes.apple.com/us/app/mr.-dapper-men-fashion-app/id989735184?ls=1&mt=8',
author: 'wei ping woon',
},
{
name: 'My IP',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/a2/61/58/a261584d-a4cd-cbfa-cf9d-b5f1f15a7139/icon175x175.jpeg',
link: 'https://itunes.apple.com/app/id1031729525?mt=8&at=11l7ss&ct=reactnativeshowcase',
author: 'Josh Buchea',
},
{
name: 'MyPED',
icon: 'http://a2.mzstatic.com/eu/r30/Purple69/v4/88/1f/fb/881ffb3b-7986-d427-7fcf-eb5920a883af/icon175x175.png',
link: 'https://itunes.apple.com/it/app/myped/id1064907558?ls=1&mt=8',
author: 'Impronta Advance',
},
{
name: 'Nalathe Kerala',
icon: 'https://lh3.googleusercontent.com/5N0WYat5WuFbhi5yR2ccdbqmiZ0wbTtKRG9GhT3YK7Z-qRvmykZyAgk0HNElOxD2JOPr=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.rhyble.nalathekerala',
author: 'Rhyble',
},
{
name: 'No Fluff: Hiragana',
icon: 'https://lh3.googleusercontent.com/kStXwjpbPsu27E1nIEU1gfG0I8j9t5bAR_20OMhGZvu0j2vab3EbBV7O_KNZChjflZ_O',
link: 'https://play.google.com/store/apps/details?id=com.hiragana',
author: 'Matthias Sieber',
source: 'https://github.com/manonthemat/no-fluff-hiragana'
},
{
name: 'Night Light',
icon: 'http://is3.mzstatic.com/image/pf/us/r30/Purple7/v4/5f/50/5f/5f505fe5-0a30-6bbf-6ed9-81ef09351aba/mzl.lkeqxyeo.png',
link: 'https://itunes.apple.com/gb/app/night-light-feeding-light/id1016843582?mt=8',
author: 'Tian Yuan',
},
{
name: 'Okanagan News',
icon: 'http://a5.mzstatic.com/us/r30/Purple69/v4/aa/93/17/aa93171e-d0ed-7e07-54a1-be27490e210c/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/okanagan-news-reader-for-viewing/id1049147148?mt=8',
author: 'Levi Cabral',
},
{
name: 'Pimmr',
icon: 'http://a2.mzstatic.com/eu/r30/Purple69/v4/99/da/0e/99da0ee6-bc87-e1a6-1d95-7027c78f50e1/icon175x175.jpeg',
link: 'https://itunes.apple.com/nl/app/pimmr/id1023343303?mt=8',
author: 'Pimmr'
},
{
name: 'Posyt - Tinder for ideas',
icon: 'http://a3.mzstatic.com/us/r30/Purple6/v4/a5/b3/86/a5b38618-a5e9-6089-7425-7fa51ecd5d30/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/posyt-anonymously-meet-right/id1037842845?mt=8',
author: 'Posyt.com',
},
{
name: 'Raindrop.io',
icon: 'http://a5.mzstatic.com/us/r30/Purple3/v4/f0/a4/57/f0a4574e-4a59-033f-05ff-5c421f0a0b00/icon175x175.png',
link: 'https://itunes.apple.com/us/app/raindrop.io-keep-your-favorites/id1021913807',
author: 'Mussabekov Rustem',
},
{
name: 'ReactTo36',
icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple5/v4/e3/c8/79/e3c87934-70c6-4974-f20d-4adcfc68d71d/mzl.wevtbbkq.png',
link: 'https://itunes.apple.com/us/app/reactto36/id989009293?mt=8',
author: 'Jonathan Solichin',
},
{
name: 'Reading',
icon: 'http://7xr0xq.com1.z0.glb.clouddn.com/about_logo.png',
link: 'http://www.wandoujia.com/apps/com.reading',
author: 'RichardCao',
blogs: [
'http://richard-cao.github.io/2016/02/06/Reading-App-Write-In-React-Native/',
],
},
{
name: 'RenovationFind',
icon: 'http://a2.mzstatic.com/us/r30/Purple3/v4/4f/89/af/4f89af72-9733-2f59-6876-161983a0ee82/icon175x175.png',
link: 'https://itunes.apple.com/ca/app/renovationfind/id1040331641?mt=8',
author: 'Christopher Lord'
},
{
name: 'RepairShopr',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/fa/96/ee/fa96ee57-c5f0-0c6f-1a34-64c9d3266b86/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/repairshopr-payments-lite/id1023262888?mt=8',
author: 'Jed Tiotuico',
},
{
name: 'Rota Employer - Hire On Demand',
link: 'https://itunes.apple.com/us/app/rota-employer-hire-on-demand/id1042270305?mt=8',
icon: 'https://avatars2.githubusercontent.com/u/15051833?v=3&s=200',
author: 'Rota',
},
{
name: 'Rota Worker - Shifts On Demand',
icon: 'http://a5.mzstatic.com/us/r30/Purple3/v4/51/ca/49/51ca4924-61c8-be1d-ab6d-afa510b1d393/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/rota-worker-shifts-on-demand/id1042111289?mt=8',
author: 'Rota',
},
{
name: 'RWpodPlayer - audio player for RWpod podcast',
icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/a8/c0/b1/a8c0b130-e44b-742d-6458-0c89fcc15b6b/icon175x175.png',
link: 'https://itunes.apple.com/us/app/rwpodplayer/id1053885042?mt=8',
author: 'Alexey Vasiliev aka leopard',
},
{
name: 'SG Toto 4d',
icon: 'http://a4.mzstatic.com/us/r30/Purple7/v4/d2/bc/46/d2bc4696-84d6-9681-a49f-7f660d6b04a7/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/sg-toto-4d/id1006371481?mt=8',
author: 'Steve Ng'
},
{
name: 'ShareHows',
icon: 'http://a4.mzstatic.com/us/r30/Purple5/v4/78/1c/83/781c8325-a1e1-4afc-f106-a629bcf3c6ef/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/kr/app/sweeohauseu-sesang-ui-modeun/id1060914858?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=kr.dobbit.sharehows',
author: 'Dobbit Co., Ltd.'
},
{
name: 'sneat: réservez les meilleurs restaurants de Paris',
icon: 'http://a3.mzstatic.com/eu/r30/Purple49/v4/71/71/df/7171df47-6e03-8619-19a8-07f52186b0ed/icon175x175.jpeg',
link: 'https://itunes.apple.com/fr/app/sneat-reservez-les-meilleurs/id1062510079?l=en&mt=8',
author: 'sneat'
},
{
name: 'Spero for Cancer',
icon: 'https://s3-us-west-1.amazonaws.com/cancerspot/site_images/Spero1024.png',
link: 'https://geo.itunes.apple.com/us/app/spero-for-cancer/id1033923573?mt=8',
author: 'Spero.io',
},
{
name: 'Tabtor Parent',
icon: 'http://a1.mzstatic.com/us/r30/Purple4/v4/80/50/9d/80509d05-18f4-a0b8-0cbb-9ba927d04477/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/tabtor-math/id1018651199?utm_source=ParentAppLP',
author: 'PrazAs Learning Inc.',
},
{
name: 'TeamWarden',
icon: 'http://a1.mzstatic.com/eu/r30/Purple69/v4/09/37/61/0937613a-46e3-3278-5457-5de49a4ee9ab/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/gb/app/teamwarden/id1052570507?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.teamwarden',
author: 'nittygritty.net',
},
{
name: 'Text Blast',
icon: 'http://a3.mzstatic.com/us/r30/Purple49/v4/4f/29/58/4f2958a1-7f35-9260-6340-c67ac29d7740/icon175x175.png',
link: 'https://itunes.apple.com/us/app/text-blast-2016/id1023852862?mt=8',
author: 'Sesh',
},
{
name: 'Thai Tone',
icon: 'http://a5.mzstatic.com/us/r30/Purple2/v4/b1/e6/2b/b1e62b3d-6747-0d0b-2a21-b6ba316a7890/icon175x175.png',
link: 'https://itunes.apple.com/us/app/thai-tone/id1064086189?mt=8',
author: 'Alexey Ledak',
},
{
name: 'Tong Xing Wang',
icon: 'http://a3.mzstatic.com/us/r30/Purple1/v4/7d/52/a7/7d52a71f-9532-82a5-b92f-87076624fdb2/icon175x175.jpeg',
link: 'https://itunes.apple.com/cn/app/tong-xing-wang/id914254459?mt=8',
author: 'Ho Yin Tsun Eugene',
},
{
name: 'Veggies in Season',
icon: 'https://s3.amazonaws.com/veggies-assets/icon175x175.png',
link: 'https://itunes.apple.com/es/app/veggies-in-season/id1088215278?mt=8',
author: 'Victor Delgado',
},
{
name: 'WEARVR',
icon: 'http://a2.mzstatic.com/eu/r30/Purple69/v4/4f/5a/28/4f5a2876-9530-ef83-e399-c5ef5b2dab80/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/gb/app/wearvr/id1066288171?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.wearvr.app',
author: 'WEARVR LLC',
},
{
name: 'Whammy',
icon: 'http://a4.mzstatic.com/us/r30/Purple49/v4/8f/1c/21/8f1c2158-c7fb-1bbb-94db-e77b867aad1a/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/whammy/id899759777',
author: 'Play Company',
},
{
name: 'WOOP',
icon: 'http://a4.mzstatic.com/us/r30/Purple6/v4/b0/44/f9/b044f93b-dbf3-9ae5-0f36-9b4956628cab/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/woop-app/id790247988?mt=8',
author: 'Moritz Schwörer (@mosch)',
},
{
name: 'Yoloci',
icon: 'http://a5.mzstatic.com/eu/r30/Purple7/v4/fa/e5/26/fae52635-b97c-bd53-2ade-89e2a4326745/icon175x175.jpeg',
link: 'https://itunes.apple.com/de/app/yoloci/id991323225?mt=8',
author: 'Yonduva GmbH (@PhilippKrone)',
},
{
name: 'youmeyou',
icon: 'http://is1.mzstatic.com/image/pf/us/r30/Purple7/v4/7c/42/30/7c423042-8945-7733-8af3-1523468706a8/mzl.qlecxphf.png',
link: 'https://itunes.apple.com/us/app/youmeyou/id949540333?mt=8',
author: 'youmeyou, LLC',
},
{
name: 'Ziliun',
icon: 'https://lh3.googleusercontent.com/c6ot13BVlU-xONcQi-llFmKXZCLRGbfrCv1RnctWtOELtPYMc0A52srXAfkU897QIg=w300',
link: 'https://play.google.com/store/apps/details?id=com.ziliunapp',
author: 'Sonny Lazuardi',
},
{
name: 'YazBoz',
icon: 'http://a4.mzstatic.com/us/r30/Purple6/v4/80/4f/43/804f431d-2828-05aa-2593-99cfb0475351/icon175x175.png',
link: 'https://itunes.apple.com/us/app/yazboz-batak-esli-batak-okey/id1048620855?ls=1&mt=8',
author: 'Melih Mucuk',
},
{
name: '天才段子手',
icon: 'http://pp.myapp.com/ma_icon/0/icon_12236104_1451810987/96',
linkAppStore: 'https://itunes.apple.com/us/app/tian-cai-duan-zi-shou-shen/id992312701?l=zh&ls=1&mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.geniusJokeWriter.app',
author: 'Ran Zhao&Ji Zhao'
},
{
name: '你造么',
icon: 'http://7xk1ez.com2.z0.glb.qiniucdn.com/logo-mobile-0114logo_welcom.png',
link: 'https://itunes.apple.com/us/app/ni-zao-me/id1025294933?l=zh&ls=1&mt=8',
author: 'Scott Chen(@NZAOM)'
},
{
name: 'うたよみん',
icon: 'http://a4.mzstatic.com/jp/r30/Purple69/v4/19/8f/fa/198ffafe-66a6-d682-c8d1-47faf2b0badb/icon175x175.jpeg',
linkAppStore: 'https://itunes.apple.com/jp/app/minnano-duan-ge-tou-gaokomyuniti/id675671254?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.plasticaromantica.utayomin',
author: 'Takayuki IMAI'
},
{
name: '烘焙帮',
icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/79/85/ba/7985ba1d-a807-7c34-98f1-e9e2ed5d2cb5/icon175x175.jpeg',
linkAppStore: 'https://itunes.apple.com/cn/app/hong-bei-bang-hai-liang-hong/id1007812319?mt=8',
author: 'Hongbeibang'
},
];
var AppList = React.createClass({
render: function() {
return (
<div>
{this.props.apps.map(this._renderApp)}
</div>
)
},
_renderApp: function(app, i) {
var inner = (
<div>
<img src={app.icon} alt={app.name} />
<h3>{app.name}</h3>
{app.linkAppStore && app.linkPlayStore ? this._renderLinks(app) : null}
<p>By {app.author}</p>
{this._renderBlogPosts(app)}
{this._renderSourceLink(app)}
{this._renderVideos(app)}
</div>
);
if (app.linkAppStore && app.linkPlayStore) {
return (<div className="showcase" key={i}>{inner}</div>);
}
return (
<div className="showcase" key={i}>
<a href={app.link} target="_blank">
{inner}
</a>
</div>
);
},
_renderBlogPosts: function(app) {
if (!app.blogs) {
return;
}
if (app.blogs.length === 1) {
return (
<p><a href={app.blogs[0]} target="_blank">Blog post</a></p>
);
} else if (app.blogs.length > 1) {
return (
<p>Blog posts: {app.blogs.map(this._renderBlogPost)}</p>
);
}
},
_renderBlogPost: function(url, i) {
return (
<a href={url} target="_blank">
{i + 1}
</a>
);
},
_renderSourceLink: function(app) {
if (!app.source) {
return;
}
return (
<p><a href={app.source} target="_blank">Source</a></p>
);
},
_renderVideos: function(app) {
if (!app.videos) {
return;
}
if (app.videos.length === 1) {
return (
<p><a href={app.videos[0]} target="_blank">Video</a></p>
);
} else if (app.videos.length > 1) {
return (
<p>Videos: {app.videos.map(this._renderVideo)}</p>
);
}
},
_renderVideo: function(url, i) {
return (
<a href={url} target="_blank">
{i + 1}
</a>
);
},
_renderLinks: function(app) {
return (
<p>
<a href={app.linkAppStore} target="_blank">iOS</a> -
<a href={app.linkPlayStore} target="_blank">Android</a>
</p>
);
},
});
var showcase = React.createClass({
render: function() {
return (
<Site section="showcase" title="Showcase">
<section className="content wrap documentationContent nosidebar showcaseSection">
<div className="inner-content showcaseHeader">
<h1 style={{textAlign: 'center'}}>Apps using React Native</h1>
<div className="subHeader"></div>
<p>The following is a list of some of the public apps using <strong>React Native</strong> and are published on the Apple App Store or the Google Play Store. Not all are implemented 100% in React Native -- many are hybrid native/React Native. Can you tell which parts are which? :)</p>
<p>Want to add your app? Found an app that no longer works or no longer uses React Native? Please submit a pull request on <a href="https://github.com/facebook/react-native">GitHub</a> to update this page!</p>
</div>
<div className="inner-content showcaseHeader">
<h1 style={{textAlign: 'center'}}>Featured Apps</h1>
<div className="subHeader"></div>
<p>These are some of the most well-crafted React Native apps that we have come across.<br/>Be sure to check them out to get a feel for what React Native is capable of!</p>
</div>
<div className="inner-content">
<AppList apps={featured} />
</div>
<div className="inner-content showcaseHeader">
<h1 style={{textAlign: 'center'}}>All Apps</h1>
<p>Not all apps can be featured, otherwise we would have to create some other category like "super featured" and that's just silly. But that doesn't mean you shouldn't check these apps out!</p>
</div>
<div className="inner-content">
<AppList apps={apps} />
</div>
</section>
</Site>
);
}
});
module.exports = showcase;
| website/src/react-native/showcase.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var React = require('React');
var Site = require('Site');
var center = require('center');
var featured = [
{
name: 'Facebook Groups',
icon: 'http://is4.mzstatic.com/image/pf/us/r30/Purple69/v4/57/f8/4c/57f84c0c-793d-5f9a-95ee-c212d0369e37/mzl.ugjwfhzx.png',
link: 'https://itunes.apple.com/us/app/facebook-groups/id931735837?mt=8',
author: 'Facebook',
},
{
name: 'Facebook Ads Manager',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple5/v4/9e/16/86/9e1686ef-cc55-805a-c977-538ddb5e6832/mzl.gqbhwitj.png',
linkAppStore: 'https://itunes.apple.com/us/app/facebook-ads-manager/id964397083?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.facebook.adsmanager',
author: 'Facebook',
blogs: [
"https://code.facebook.com/posts/1014532261909640/react-native-bringing-modern-web-techniques-to-mobile/",
"https://code.facebook.com/posts/1189117404435352/react-native-for-android-how-we-built-the-first-cross-platform-react-native-app/",
"https://code.facebook.com/posts/435862739941212/making-react-native-apps-accessible/",
],
},
{
name: 'AIGA Design Conference 2015',
icon: 'http://a5.mzstatic.com/us/r30/Purple69/v4/b0/4b/29/b04b2939-88d2-f61f-dec9-24fae083d8b3/icon175x175.png',
link: 'https://itunes.apple.com/us/app/aiga-design-conference-2015/id1038145272?ls=1&mt=8',
author: 'W&Co',
},
{
name: 'Discord',
icon: 'http://a5.mzstatic.com/us/r30/Purple5/v4/c1/2f/4c/c12f4cba-1d9a-f6bf-2240-04085d3470ec/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/discord-chat-for-gamers/id985746746?mt=8',
author: 'Hammer & Chisel',
},
{
name: 'Discovery VR',
icon: 'http://a2.mzstatic.com/us/r30/Purple6/v4/d1/d5/f4/d1d5f437-9f6b-b5aa-5fe7-47bd19f934bf/icon175x175.png',
link: 'https://itunes.apple.com/us/app/discovery-vr/id1030815031?mt=8',
author: 'Discovery Communications',
blog: [
"https://medium.com/ios-os-x-development/an-ios-developer-on-react-native-1f24786c29f0",
],
},
{
name: 'Exponent',
icon: 'http://a4.mzstatic.com/us/r30/Purple2/v4/3a/d3/c9/3ad3c96c-5e14-f988-4bdd-0fdc95efd140/icon175x175.png',
link: 'http://exponentjs.com/',
author: 'Exponent',
},
{
name: 'Lrn',
icon: 'http://is4.mzstatic.com/image/pf/us/r30/Purple1/v4/41/a9/e9/41a9e9b6-7801-aef7-2400-2eca14923321/mzl.adyswxad.png',
link: 'https://itunes.apple.com/us/app/lrn-learn-to-code-at-your/id1019622677',
author: 'Lrn Labs, Inc',
},
{
name: 'Movie Trailers by MovieLaLa',
icon: 'https://lh3.googleusercontent.com/16aug4m_6tvJB7QZden9w1SOMqpZgNp7rHqDhltZNvofw1a4V_ojGGXUMPGiK0dDCqzL=w300',
linkAppStore: 'https://itunes.apple.com/us/app/movie-trailers-by-movielala/id1001416601?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.movielala.trailers',
author: 'MovieLaLa'
},
{
name: 'MyMuesli',
icon: 'https://lh3.googleusercontent.com/1dCCeiyjuWRgY-Cnv-l-lOA1sVH3Cn0vkVWWZnaBQbhHOhsngLcnfy68WEerudPUysc=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.mymuesli',
author: 'Shawn Khameneh (@shawnscode), 3DWD'
},
{
name: 'Myntra',
icon: 'http://a5.mzstatic.com/us/r30/Purple6/v4/9c/78/df/9c78dfa6-0061-1af2-5026-3e1d5a073c94/icon350x350.png',
link: 'https://itunes.apple.com/in/app/myntra-fashion-shopping-app/id907394059',
author: 'Myntra Designs',
},
{
name: 'Noodler',
icon: 'http://a5.mzstatic.com/us/r30/Purple6/v4/d9/9a/69/d99a6919-7f11-35ad-76ea-f1741643d875/icon175x175.png',
link: 'http://www.noodler-app.com/',
author: 'Michele Humes & Joshua Sierles',
},
{
name: 'React Native Playground',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple1/v4/20/ec/8e/20ec8eb8-9e12-6686-cd16-7ac9e3ef1d52/mzl.ngvuoybx.png',
linkAppStore: 'https://itunes.apple.com/us/app/react-native-playground/id1002032944?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=org.rnplay.playground',
author: 'Joshua Sierles',
},
{
name: 'Round - A better way to remember your medicine',
icon: 'https://s3.mzstatic.com/us/r30/Purple69/v4/d3/ee/54/d3ee54cf-13b6-5f56-0edc-6c70ac90b2be/icon175x175.png',
link: 'https://itunes.apple.com/us/app/round-beautiful-medication/id1059591124?mt=8',
author: 'Circadian Design',
},
{
name: 'Running',
icon: 'http://a1.mzstatic.com/us/r30/Purple3/v4/33/eb/4f/33eb4f73-c7e3-8659-9285-f758e403485b/icon175x175.jpeg',
link: 'https://gyrosco.pe/running/',
author: 'Gyroscope Innovations',
blogs: [
'https://blog.gyrosco.pe/the-making-of-gyroscope-running-a4ad10acc0d0',
],
},
{
name: 'SoundCloud Pulse',
icon: 'https://i1.sndcdn.com/artworks-000149203716-k5je96-original.jpg',
link: 'https://itunes.apple.com/us/app/soundcloud-pulse-for-creators/id1074278256?mt=8',
author: 'SoundCloud',
},
{
name: 'Spero for Cancer',
icon: 'https://s3-us-west-1.amazonaws.com/cancerspot/site_images/Spero1024.png',
link: 'https://geo.itunes.apple.com/us/app/spero-for-cancer/id1033923573?mt=8',
author: 'Spero.io',
videos: [
'https://www.youtube.com/watch?v=JImX3L6qnj8',
],
},
{
name: 'Squad',
icon: 'http://a4.mzstatic.com/us/r30/Purple69/v4/e8/5b/3f/e85b3f52-72f3-f427-a32e-a73efe2e9682/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/squad-snaps-for-groups-friends/id1043626975?mt=8',
author: 'Tackk Inc.',
},
{
name: 'Start - medication manager for depression',
icon: 'http://a1.mzstatic.com/us/r30/Purple49/v4/de/9b/6f/de9b6fe8-84ea-7a12-ba2c-0a6d6c7b10b0/icon175x175.png',
link: 'https://itunes.apple.com/us/app/start-medication-manager-for/id1012099928?mt=8',
author: 'Iodine Inc.',
},
{
name: 'This AM',
icon: 'http://s3.r29static.com//bin/public/efe/x/1542038/image.png',
link: 'https://itunes.apple.com/us/app/refinery29-this-am-top-breaking/id988472315?mt=8',
author: 'Refinery29',
},
{
name: 'Townske',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/8b/42/20/8b4220af-5165-91fd-0f05-014332df73ef/icon175x175.png',
link: 'https://itunes.apple.com/us/app/townske-stunning-city-guides/id1018136179?ls=1&mt=8',
author: 'Townske PTY LTD',
},
{
name: 'Tucci',
icon: 'http://a3.mzstatic.com/us/r30/Purple3/v4/c0/0c/95/c00c95ce-4cc5-e516-db77-5c5164b89189/icon175x175.jpeg',
link: 'https://itunes.apple.com/app/apple-store/id1039661754?mt=8',
author: 'Clay Allsopp & Tiffany Young',
blogs: [
'https://medium.com/@clayallsopp/making-tucci-what-is-it-and-why-eaa2bf94c1df#.lmm3dmkaf',
'https://medium.com/@clayallsopp/making-tucci-the-technical-details-cc7aded6c75f#.wf72nq372',
],
},
{
name: 'WPV',
icon: 'http://a2.mzstatic.com/us/r30/Purple49/v4/a8/26/d7/a826d7bf-337b-c6b8-488d-aca98027754d/icon350x350.png',
link: 'https://itunes.apple.com/us/app/wpv/id725222647?mt=8',
author: 'Yamill Vallecillo',
},
{
name: 'Zhopout',
icon: 'http://zhopout.com/Content/Images/zhopout-logo-app-3.png',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.zhopout',
author: 'Jarvis Software Private Limited ',
blogs: [
"https://medium.com/@murugandurai/how-we-developed-our-mobile-app-in-30-days-using-react-native-45affa6449e8#.29nnretsi",
],
},
];
var apps = [
{
name: 'Accio',
icon: 'http://a3.mzstatic.com/us/r30/Purple3/v4/03/a1/5b/03a15b9f-04d7-a70a-620a-9c9850a859aa/icon175x175.png',
link: 'https://itunes.apple.com/us/app/accio-on-demand-delivery/id1047060673?mt=8',
author: 'Accio Delivery Inc.',
},
{
name: 'ArcChat.com',
icon: 'https://lh3.googleusercontent.com/mZJjidMobu3NAZApdtp-vdBBzIWzCNTaIcKShbGqwXRRzL3B9bbi6E0eRuykgT6vmg=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.arcchat',
author: 'Lukas Liesis',
},
{
name: 'Beetroot',
icon: 'http://is1.mzstatic.com/image/pf/us/r30/Purple5/v4/66/fd/dd/66fddd70-f848-4fc5-43ee-4d52197ccab8/pr_source.png',
link: 'https://itunes.apple.com/us/app/beetroot/id1016159001?ls=1&mt=8',
author: 'Alex Duckmanton',
},
{
name: 'Bhagavad Gita Lite',
icon: 'https://s3-us-west-2.amazonaws.com/bhagavadgitaapp/gita-free.png',
link: 'https://itunes.apple.com/us/app/bhagavad-gita-lite/id1071711190?ls=1&mt=8',
author: 'Tom Goldenberg & Nick Brown'
},
{
name: 'Bionic eStore',
icon: 'http://a5.mzstatic.com/us/r30/Purple7/v4/c1/9a/3f/c19a3f82-ecc3-d60b-f983-04acc203705f/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/bionic-estore/id994537615?mt=8',
author: 'Digidemon',
},
{
name: 'breathe Meditation Timer',
icon: 'http://a2.mzstatic.com/eu/r30/Purple49/v4/09/21/d2/0921d265-087a-98f0-58ce-bbf9d44b114d/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/de/app/breathe-meditation-timer/id1087354227?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.idearockers.breathe',
author: 'idearockers UG',
},
{
name: 'CANDDi',
icon: 'http://a5.mzstatic.com/eu/r30/Purple7/v4/c4/e4/85/c4e48546-7127-a133-29f2-3e2e1aa0f9af/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/gb/app/canddi/id1018168131?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.canddi',
author: 'CANDDi LTD.',
},
{
name: 'CaratLane',
icon: 'https://lh3.googleusercontent.com/wEN-Vvpbnw_n89dbXPxWkNnXB7sALKBKvpX_hbzrWbuC4tFi5tVkWHq8k5TAvdbf5UQ=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.caratlane.android&hl=en',
author: 'CaratLane',
},
{
name: 'CBS Sports Franchise Football',
icon: 'http://a2.mzstatic.com/us/r30/Purple69/v4/7b/0c/a0/7b0ca007-885a-7cfc-9fa2-2ec4394c2ecc/icon175x175.png',
link: 'https://play.google.com/store/apps/details?id=com.cbssports.fantasy.franchisefootball2015',
author: 'CBS Sports',
},
{
name: 'Choke - Rap Battle With Friends',
icon: 'http://a3.mzstatic.com/us/r30/Purple49/v4/3e/83/85/3e8385d8-140f-da38-a100-1393cef3e816/icon175x175.png',
link: 'https://itunes.apple.com/us/app/choke-rap-battle-with-friends/id1077937445?ls=1&mt=8',
author: 'Henry Kirkness',
},
{
name: 'Codementor - Live 1:1 Expert Developer Help',
icon: 'http://a1.mzstatic.com/us/r30/Purple3/v4/db/cf/35/dbcf3523-bac7-0f54-c6a8-a80bf4f43c38/icon175x175.jpeg',
link: 'https://www.codementor.io/downloads',
author: 'Codementor',
},
{
name: 'Collegiate - Learn Anywhere',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/17/a9/60/17a960d3-8cbd-913a-9f08-ebd9139c116c/icon175x175.png',
link: 'https://itunes.apple.com/app/id1072463482',
author: 'Gaurav Arora',
},
{
name: 'Company name search',
icon: 'http://a4.mzstatic.com/us/r30/Purple69/v4/fd/47/53/fd47537c-5861-e208-d1d1-1e26b5e45a36/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/company-name-search/id1043824076',
author: 'The Formations Factory Ltd',
blogs: [
'https://medium.com/formations-factory/creating-company-name-search-app-with-react-native-36a049b0848d',
],
},
{
name: 'DareU',
icon: 'http://a3.mzstatic.com/us/r30/Purple6/v4/10/fb/6a/10fb6a50-57c8-061a-d865-503777bf7f00/icon175x175.png',
link: 'https://itunes.apple.com/us/app/dareu-dare-your-friends-dare/id1046434563?mt=8',
author: 'Rishabh Mehan',
},
{
name: 'Deskbookers',
icon: 'http://a4.mzstatic.com/eu/r30/Purple69/v4/be/61/7d/be617d63-88f5-5629-7ac0-bc2c9eb4802a/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/nl/app/deskbookers/id964447401?mt=8',
author: 'Emilio Rodriguez'
},
{
name: 'DockMan',
icon: 'http://a1.mzstatic.com/us/r30/Purple49/v4/91/b5/75/91b57552-d9bc-d8bc-10a1-617de920aaa6/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/app/dockman/id1061469696',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.s21g.DockMan',
blogs: [
'http://www.s21g.com/DockMan.html',
],
author: 'Genki Takiuchi (s21g Inc.)',
},
{
name: 'Due',
icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/a2/41/5d/a2415d5f-407a-c565-ffb4-4f27f23d8ac2/icon175x175.png',
link: 'https://itunes.apple.com/us/app/due-countdown-reminders-for/id1050909468?mt=8',
author: 'Dotan Nahum',
},
{
name: 'Eat or Not',
icon: 'http://a3.mzstatic.com/us/r30/Purple5/v4/51/be/34/51be3462-b015-ebf2-11c5-69165b37fadc/icon175x175.jpeg',
linkAppStore: 'https://itunes.apple.com/us/app/eat-or-not/id1054565697?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.eon',
author: 'Sharath Prabhal',
},
{
name: 'Fan of it',
icon: 'http://a4.mzstatic.com/us/r30/Purple3/v4/c9/3f/e8/c93fe8fb-9332-e744-f04a-0f4f78e42aa8/icon350x350.png',
link: 'https://itunes.apple.com/za/app/fan-of-it/id1017025530?mt=8',
author: 'Fan of it (Pty) Ltd',
},
{
name: 'FastPaper',
icon: 'http://a2.mzstatic.com/us/r30/Purple5/v4/72/b4/d8/72b4d866-90d2-3aad-d1dc-0315f2d9d045/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/fast-paper/id1001174614',
author: 'Liubomyr Mykhalchenko (@liubko)',
},
{
name: 'Feline for Product Hunt',
icon: 'https://lh3.googleusercontent.com/MCoiCCwUan0dxzqRR_Mrr7kO308roYdI2aTsIpUGYWzUmpJT1-R2_J04weQKFEd3Mg=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.arjunkomath.product_hunt&hl=en',
author: 'Arjun Komath',
},
{
name: 'Fixt',
icon: 'http://a5.mzstatic.com/us/r30/Purple69/v4/46/bc/66/46bc66a2-7775-4d24-235d-e1fe28d55d7f/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/us/app/dropbot-phone-replacement/id1000855694?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=co.fixt',
author: 'Fixt',
},
{
name: 'Foodstand',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/33/c1/3b/33c13b88-8ec2-23c1-56bb-712ad9938290/icon350x350.jpeg',
link: 'https://www.thefoodstand.com/download',
author: 'Foodstand, Inc.',
},
{
name: 'Go Fire',
icon: 'http://a2.mzstatic.com/us/r30/Purple5/v4/42/50/5a/42505a8d-3c7a-e49a-16e3-422315f24cf1/icon350x350.png',
link: 'https://itunes.apple.com/us/app/gou-huo/id1001476888?ls=1&mt=8',
author: 'beijing qingfengyun Technology Co., Ltd.',
},
{
name: 'HackerWeb',
icon: 'http://a5.mzstatic.com/us/r30/Purple49/v4/5a/bd/39/5abd3951-782c-ef12-8e40-33ebe1e43768/icon175x175.png',
link: 'https://itunes.apple.com/us/app/hackerweb/id1084209377?mt=8',
author: 'Lim Chee Aun',
},
{
name: 'Harmonizome',
icon: 'http://is1.mzstatic.com/image/thumb/Purple6/v4/18/a9/bc/18a9bcde-d2d9-7574-2664-e82fff7b7208/pr_source.png/350x350-75.png',
link: 'https://itunes.apple.com/us/app/harmonizome/id1046990905?mt=8',
author: 'Michael McDermott (@_mgmcdermott)',
},
{
name: 'Hashley',
icon: 'http://a2.mzstatic.com/us/r30/Purple4/v4/5f/19/fc/5f19fc13-e7af-cd6b-6749-cedabdaeee7d/icon350x350.png',
link: 'https://itunes.apple.com/us/app/hashtag-by-hashley-ironic/id1022724462?mt=8',
author: 'Elephant, LLC',
},
{
name: 'Hey, Neighbor!',
icon: 'https://raw.githubusercontent.com/scrollback/io.scrollback.neighborhoods/master/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png',
link: 'https://play.google.com/store/apps/details?id=io.scrollback.neighborhoods',
author: 'Scrollback',
},
{
name: 'Honest Reviews',
icon: 'http://honestreviews.techulus.com/icon.png',
link: 'https://play.google.com/store/apps/details?id=com.techulus.honestreviews&hl=en',
author: 'Arjun Komath',
},
{
name: 'Hover',
icon: 'http://a5.mzstatic.com/us/r30/Purple3/v4/ba/55/e6/ba55e6ee-71cf-b843-f592-0917c9b6c645/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/us/app/hover-1-drone-uav-pilot-app!/id947641516?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.analyticadevelopment.android.hover',
author: 'KevinEJohn',
},
{
name: 'HSK Level 1 Chinese Flashcards',
icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple1/v4/b2/4f/3a/b24f3ae3-2597-cc70-1040-731b425a5904/mzl.amxdcktl.jpg',
link: 'https://itunes.apple.com/us/app/hsk-level-1-chinese-flashcards/id936639994',
author: 'HS Schaaf',
},
{
name: 'Hubhopper',
icon: 'http://hubhopper.com/images/h_logo.jpg',
link: 'https://play.google.com/store/apps/details?id=com.hubhopper',
author: 'Soch Technologies',
},
{
name: 'Jukebox',
icon: 'https://s3.amazonaws.com/theartistunion-production/Jukebox-logo.png',
link: 'https://itunes.apple.com/us/app/jukebox-offline-music-player/id1072583255?ls=1&mt=8',
author: 'The Beat Drop Inc'
},
{
name: 'Kakapo',
icon: 'http://a2.mzstatic.com/eu/r30/Purple3/v4/12/ab/2a/12ab2a01-3a3c-9482-b8df-ab38ad281165/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/gb/app/kakapo/id1046673139?ls=1&mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.kakaponative',
author: 'Daniel Levitt',
},
{
name: 'Koza Gujarati Dictionary',
icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/77/95/83/77958377-05ae-4754-684a-3c9dbb67b517/icon175x175.jpeg',
link: 'https://itunes.apple.com/in/app/koza-english-to-gujarati-dictionary/id982752928?mt=8',
author: 'KozaApps',
},
{
name: 'Leanpub',
icon: 'http://a2.mzstatic.com/us/r30/Purple6/v4/9f/4a/6f/9f4a6f8c-8951-ed89-4083-74ace23df9ef/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/leanpub/id913517110?ls=1&mt=8',
author: 'Leanpub',
},
{
name: 'LoadDocs',
icon: 'http://a2.mzstatic.com/us/r30/Purple3/v4/b5/ca/78/b5ca78ca-392d-6874-48bf-762293482d42/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/loaddocs/id1041596066',
author: 'LoadDocs',
},
{
name: 'Lugg – Your On-Demand Mover',
icon: 'http://lh3.googleusercontent.com/EV9z7kRRME2KPMBRNHnje7bBNEl_Why2CFq-MfKzBC88uSFJTYr1HO3-nPt-JuVJwKFb=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.lugg',
author: 'Lugg',
},
{
name: 'Lumpen Radio',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple1/v4/46/43/00/464300b1-fae3-9640-d4a2-0eb050ea3ff2/mzl.xjjawige.png',
link: 'https://itunes.apple.com/us/app/lumpen-radio/id1002193127?mt=8',
author: 'Joshua Habdas',
},
{
name: 'Makerist Mediathek',
icon: 'http://a5.mzstatic.com/eu/r30/Purple3/v4/fa/5f/4c/fa5f4ce8-5aaa-5a4b-ddcc-a0c6f681d08a/icon175x175.png',
link: 'https://itunes.apple.com/de/app/makerist-mediathek/id1019504544',
author: 'Railslove',
},
{
name: 'MaxReward - Android',
icon: 'https://lh3.googleusercontent.com/yynCUCdEnyW6T96xCto8KzWQr4Yeiy0M6c2p8auYMIyFgAZVBsjf4JCEX7QkPijhBg=w175-rw',
linkAppStore: 'https://itunes.apple.com/us/app/maxreward/id1050479192?ls=1&mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.bitstrek.maxreward&hl=en',
author: 'Neil Ma',
},
{
name: 'MinTrain',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple5/v4/51/51/68/51516875-1323-3100-31a8-cd1853d9a2c0/mzl.gozwmstp.png',
link: 'https://itunes.apple.com/us/app/mintrain/id1015739031?mt=8',
author: 'Peter Cottle',
},
{
name: 'Mobabuild',
icon: 'http://mobabuild.co/images/applogo.png',
link: 'http://mobabuild.co',
author: 'Sercan Demircan ( @sercanov )',
},
{
name: 'MockingBot',
icon: 'https://s3.cn-north-1.amazonaws.com.cn/modao/downloads/images/MockingBot175.png',
link: 'https://itunes.apple.com/cn/app/mockingbot/id1050565468?l=en&mt=8',
author: 'YuanYi Zhang (@mockingbot)',
},
{
name: 'MoneyLion',
icon: 'http://a5.mzstatic.com/us/r30/Purple69/v4/d7/9d/ad/d79daddc-8d67-8a6c-61e2-950425946dd2/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/moneylion/id1064677082?mt=8',
author: 'MoneyLion LLC',
},
{
name: 'Mr. Dapper',
icon: 'http://is5.mzstatic.com/image/pf/us/r30/Purple4/v4/e8/3f/7c/e83f7cb3-2602-f8e8-de9a-ce0a775a4a14/mzl.hmdjhfai.png',
link: 'https://itunes.apple.com/us/app/mr.-dapper-men-fashion-app/id989735184?ls=1&mt=8',
author: 'wei ping woon',
},
{
name: 'My IP',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/a2/61/58/a261584d-a4cd-cbfa-cf9d-b5f1f15a7139/icon175x175.jpeg',
link: 'https://itunes.apple.com/app/id1031729525?mt=8&at=11l7ss&ct=reactnativeshowcase',
author: 'Josh Buchea',
},
{
name: 'MyPED',
icon: 'http://a2.mzstatic.com/eu/r30/Purple69/v4/88/1f/fb/881ffb3b-7986-d427-7fcf-eb5920a883af/icon175x175.png',
link: 'https://itunes.apple.com/it/app/myped/id1064907558?ls=1&mt=8',
author: 'Impronta Advance',
},
{
name: 'Nalathe Kerala',
icon: 'https://lh3.googleusercontent.com/5N0WYat5WuFbhi5yR2ccdbqmiZ0wbTtKRG9GhT3YK7Z-qRvmykZyAgk0HNElOxD2JOPr=w300-rw',
link: 'https://play.google.com/store/apps/details?id=com.rhyble.nalathekerala',
author: 'Rhyble',
},
{
name: 'No Fluff: Hiragana',
icon: 'https://lh3.googleusercontent.com/kStXwjpbPsu27E1nIEU1gfG0I8j9t5bAR_20OMhGZvu0j2vab3EbBV7O_KNZChjflZ_O',
link: 'https://play.google.com/store/apps/details?id=com.hiragana',
author: 'Matthias Sieber',
source: 'https://github.com/manonthemat/no-fluff-hiragana'
},
{
name: 'Night Light',
icon: 'http://is3.mzstatic.com/image/pf/us/r30/Purple7/v4/5f/50/5f/5f505fe5-0a30-6bbf-6ed9-81ef09351aba/mzl.lkeqxyeo.png',
link: 'https://itunes.apple.com/gb/app/night-light-feeding-light/id1016843582?mt=8',
author: 'Tian Yuan',
},
{
name: 'Okanagan News',
icon: 'http://a5.mzstatic.com/us/r30/Purple69/v4/aa/93/17/aa93171e-d0ed-7e07-54a1-be27490e210c/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/okanagan-news-reader-for-viewing/id1049147148?mt=8',
author: 'Levi Cabral',
},
{
name: 'Pimmr',
icon: 'http://a2.mzstatic.com/eu/r30/Purple69/v4/99/da/0e/99da0ee6-bc87-e1a6-1d95-7027c78f50e1/icon175x175.jpeg',
link: 'https://itunes.apple.com/nl/app/pimmr/id1023343303?mt=8',
author: 'Pimmr'
},
{
name: 'Posyt - Tinder for ideas',
icon: 'http://a3.mzstatic.com/us/r30/Purple6/v4/a5/b3/86/a5b38618-a5e9-6089-7425-7fa51ecd5d30/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/posyt-anonymously-meet-right/id1037842845?mt=8',
author: 'Posyt.com',
},
{
name: 'Raindrop.io',
icon: 'http://a5.mzstatic.com/us/r30/Purple3/v4/f0/a4/57/f0a4574e-4a59-033f-05ff-5c421f0a0b00/icon175x175.png',
link: 'https://itunes.apple.com/us/app/raindrop.io-keep-your-favorites/id1021913807',
author: 'Mussabekov Rustem',
},
{
name: 'ReactTo36',
icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple5/v4/e3/c8/79/e3c87934-70c6-4974-f20d-4adcfc68d71d/mzl.wevtbbkq.png',
link: 'https://itunes.apple.com/us/app/reactto36/id989009293?mt=8',
author: 'Jonathan Solichin',
},
{
name: 'Reading',
icon: 'http://7xr0xq.com1.z0.glb.clouddn.com/about_logo.png',
link: 'http://www.wandoujia.com/apps/com.reading',
author: 'RichardCao',
blogs: [
'http://richard-cao.github.io/2016/02/06/Reading-App-Write-In-React-Native/',
],
},
{
name: 'RenovationFind',
icon: 'http://a2.mzstatic.com/us/r30/Purple3/v4/4f/89/af/4f89af72-9733-2f59-6876-161983a0ee82/icon175x175.png',
link: 'https://itunes.apple.com/ca/app/renovationfind/id1040331641?mt=8',
author: 'Christopher Lord'
},
{
name: 'RepairShopr',
icon: 'http://a3.mzstatic.com/us/r30/Purple69/v4/fa/96/ee/fa96ee57-c5f0-0c6f-1a34-64c9d3266b86/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/repairshopr-payments-lite/id1023262888?mt=8',
author: 'Jed Tiotuico',
},
{
name: 'Rota Employer - Hire On Demand',
link: 'https://itunes.apple.com/us/app/rota-employer-hire-on-demand/id1042270305?mt=8',
icon: 'https://avatars2.githubusercontent.com/u/15051833?v=3&s=200',
author: 'Rota',
},
{
name: 'Rota Worker - Shifts On Demand',
icon: 'http://a5.mzstatic.com/us/r30/Purple3/v4/51/ca/49/51ca4924-61c8-be1d-ab6d-afa510b1d393/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/rota-worker-shifts-on-demand/id1042111289?mt=8',
author: 'Rota',
},
{
name: 'RWpodPlayer - audio player for RWpod podcast',
icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/a8/c0/b1/a8c0b130-e44b-742d-6458-0c89fcc15b6b/icon175x175.png',
link: 'https://itunes.apple.com/us/app/rwpodplayer/id1053885042?mt=8',
author: 'Alexey Vasiliev aka leopard',
},
{
name: 'SG Toto 4d',
icon: 'http://a4.mzstatic.com/us/r30/Purple7/v4/d2/bc/46/d2bc4696-84d6-9681-a49f-7f660d6b04a7/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/sg-toto-4d/id1006371481?mt=8',
author: 'Steve Ng'
},
{
name: 'ShareHows',
icon: 'http://a4.mzstatic.com/us/r30/Purple5/v4/78/1c/83/781c8325-a1e1-4afc-f106-a629bcf3c6ef/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/kr/app/sweeohauseu-sesang-ui-modeun/id1060914858?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=kr.dobbit.sharehows',
author: 'Dobbit Co., Ltd.'
},
{
name: 'sneat: réservez les meilleurs restaurants de Paris',
icon: 'http://a3.mzstatic.com/eu/r30/Purple49/v4/71/71/df/7171df47-6e03-8619-19a8-07f52186b0ed/icon175x175.jpeg',
link: 'https://itunes.apple.com/fr/app/sneat-reservez-les-meilleurs/id1062510079?l=en&mt=8',
author: 'sneat'
},
{
name: 'Spero for Cancer',
icon: 'https://s3-us-west-1.amazonaws.com/cancerspot/site_images/Spero1024.png',
link: 'https://geo.itunes.apple.com/us/app/spero-for-cancer/id1033923573?mt=8',
author: 'Spero.io',
},
{
name: 'Tabtor Parent',
icon: 'http://a1.mzstatic.com/us/r30/Purple4/v4/80/50/9d/80509d05-18f4-a0b8-0cbb-9ba927d04477/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/tabtor-math/id1018651199?utm_source=ParentAppLP',
author: 'PrazAs Learning Inc.',
},
{
name: 'TeamWarden',
icon: 'http://a1.mzstatic.com/eu/r30/Purple69/v4/09/37/61/0937613a-46e3-3278-5457-5de49a4ee9ab/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/gb/app/teamwarden/id1052570507?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.teamwarden',
author: 'nittygritty.net',
},
{
name: 'Text Blast',
icon: 'http://a3.mzstatic.com/us/r30/Purple49/v4/4f/29/58/4f2958a1-7f35-9260-6340-c67ac29d7740/icon175x175.png',
link: 'https://itunes.apple.com/us/app/text-blast-2016/id1023852862?mt=8',
author: 'Sesh',
},
{
name: 'Thai Tone',
icon: 'http://a5.mzstatic.com/us/r30/Purple2/v4/b1/e6/2b/b1e62b3d-6747-0d0b-2a21-b6ba316a7890/icon175x175.png',
link: 'https://itunes.apple.com/us/app/thai-tone/id1064086189?mt=8',
author: 'Alexey Ledak',
},
{
name: 'Tong Xing Wang',
icon: 'http://a3.mzstatic.com/us/r30/Purple1/v4/7d/52/a7/7d52a71f-9532-82a5-b92f-87076624fdb2/icon175x175.jpeg',
link: 'https://itunes.apple.com/cn/app/tong-xing-wang/id914254459?mt=8',
author: 'Ho Yin Tsun Eugene',
},
{
name: 'Veggies in Season',
icon: 'https://s3.amazonaws.com/veggies-assets/icon175x175.png',
link: 'https://itunes.apple.com/es/app/veggies-in-season/id1088215278?mt=8',
author: 'Victor Delgado',
},
{
name: 'WEARVR',
icon: 'http://a2.mzstatic.com/eu/r30/Purple69/v4/4f/5a/28/4f5a2876-9530-ef83-e399-c5ef5b2dab80/icon175x175.png',
linkAppStore: 'https://itunes.apple.com/gb/app/wearvr/id1066288171?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.wearvr.app',
author: 'WEARVR LLC',
},
{
name: 'Whammy',
icon: 'http://a4.mzstatic.com/us/r30/Purple49/v4/8f/1c/21/8f1c2158-c7fb-1bbb-94db-e77b867aad1a/icon175x175.jpeg',
link: 'https://itunes.apple.com/us/app/whammy/id899759777',
author: 'Play Company',
},
{
name: 'WOOP',
icon: 'http://a4.mzstatic.com/us/r30/Purple6/v4/b0/44/f9/b044f93b-dbf3-9ae5-0f36-9b4956628cab/icon350x350.jpeg',
link: 'https://itunes.apple.com/us/app/woop-app/id790247988?mt=8',
author: 'Moritz Schwörer (@mosch)',
},
{
name: 'Yoloci',
icon: 'http://a5.mzstatic.com/eu/r30/Purple7/v4/fa/e5/26/fae52635-b97c-bd53-2ade-89e2a4326745/icon175x175.jpeg',
link: 'https://itunes.apple.com/de/app/yoloci/id991323225?mt=8',
author: 'Yonduva GmbH (@PhilippKrone)',
},
{
name: 'youmeyou',
icon: 'http://is1.mzstatic.com/image/pf/us/r30/Purple7/v4/7c/42/30/7c423042-8945-7733-8af3-1523468706a8/mzl.qlecxphf.png',
link: 'https://itunes.apple.com/us/app/youmeyou/id949540333?mt=8',
author: 'youmeyou, LLC',
},
{
name: 'Ziliun',
icon: 'https://lh3.googleusercontent.com/c6ot13BVlU-xONcQi-llFmKXZCLRGbfrCv1RnctWtOELtPYMc0A52srXAfkU897QIg=w300',
link: 'https://play.google.com/store/apps/details?id=com.ziliunapp',
author: 'Sonny Lazuardi',
},
{
name: 'YazBoz',
icon: 'http://a4.mzstatic.com/us/r30/Purple6/v4/80/4f/43/804f431d-2828-05aa-2593-99cfb0475351/icon175x175.png',
link: 'https://itunes.apple.com/us/app/yazboz-batak-esli-batak-okey/id1048620855?ls=1&mt=8',
author: 'Melih Mucuk',
},
{
name: '天才段子手',
icon: 'http://pp.myapp.com/ma_icon/0/icon_12236104_1451810987/96',
linkAppStore: 'https://itunes.apple.com/us/app/tian-cai-duan-zi-shou-shen/id992312701?l=zh&ls=1&mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.geniusJokeWriter.app',
author: 'Ran Zhao&Ji Zhao'
},
{
name: '你造么',
icon: 'http://7xk1ez.com2.z0.glb.qiniucdn.com/logo-mobile-0114logo_welcom.png',
link: 'https://itunes.apple.com/us/app/ni-zao-me/id1025294933?l=zh&ls=1&mt=8',
author: 'Scott Chen(@NZAOM)'
},
{
name: 'うたよみん',
icon: 'http://a4.mzstatic.com/jp/r30/Purple69/v4/19/8f/fa/198ffafe-66a6-d682-c8d1-47faf2b0badb/icon175x175.jpeg',
linkAppStore: 'https://itunes.apple.com/jp/app/minnano-duan-ge-tou-gaokomyuniti/id675671254?mt=8',
linkPlayStore: 'https://play.google.com/store/apps/details?id=com.plasticaromantica.utayomin',
author: 'Takayuki IMAI'
},
{
name: '烘焙帮',
icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/79/85/ba/7985ba1d-a807-7c34-98f1-e9e2ed5d2cb5/icon175x175.jpeg',
linkAppStore: 'https://itunes.apple.com/cn/app/hong-bei-bang-hai-liang-hong/id1007812319?mt=8',
author: 'Hongbeibang'
},
];
var AppList = React.createClass({
render: function() {
return (
<div>
{this.props.apps.map(this._renderApp)}
</div>
)
},
_renderApp: function(app, i) {
var inner = (
<div>
<img src={app.icon} alt={app.name} />
<h3>{app.name}</h3>
{app.linkAppStore && app.linkPlayStore ? this._renderLinks(app) : null}
<p>By {app.author}</p>
{this._renderBlogPosts(app)}
{this._renderSourceLink(app)}
{this._renderVideos(app)}
</div>
);
if (app.linkAppStore && app.linkPlayStore) {
return (<div className="showcase" key={i}>{inner}</div>);
}
return (
<div className="showcase" key={i}>
<a href={app.link} target="_blank">
{inner}
</a>
</div>
);
},
_renderBlogPosts: function(app) {
if (!app.blogs) {
return;
}
if (app.blogs.length === 1) {
return (
<p><a href={app.blogs[0]} target="_blank">Blog post</a></p>
);
} else if (app.blogs.length > 1) {
return (
<p>Blog posts: {app.blogs.map(this._renderBlogPost)}</p>
);
}
},
_renderBlogPost: function(url, i) {
return (
<a href={url} target="_blank">
{i + 1}
</a>
);
},
_renderSourceLink: function(app) {
if (!app.source) {
return;
}
return (
<p><a href={app.source} target="_blank">Source</a></p>
);
},
_renderVideos: function(app) {
if (!app.videos) {
return;
}
if (app.videos.length === 1) {
return (
<p><a href={app.videos[0]} target="_blank">Video</a></p>
);
} else if (app.videos.length > 1) {
return (
<p>Videos: {app.videos.map(this._renderVideo)}</p>
);
}
},
_renderVideo: function(url, i) {
return (
<a href={url} target="_blank">
{i + 1}
</a>
);
},
_renderLinks: function(app) {
return (
<p>
<a href={app.linkAppStore} target="_blank">iOS</a> -
<a href={app.linkPlayStore} target="_blank">Android</a>
</p>
);
},
});
var showcase = React.createClass({
render: function() {
return (
<Site section="showcase" title="Showcase">
<section className="content wrap documentationContent nosidebar showcaseSection">
<div className="inner-content showcaseHeader">
<h1 style={{textAlign: 'center'}}>Apps using React Native</h1>
<div className="subHeader"></div>
<p>The following is a list of some of the public apps using <strong>React Native</strong> and are published on the Apple App Store or the Google Play Store. Not all are implemented 100% in React Native -- many are hybrid native/React Native. Can you tell which parts are which? :)</p>
<p>Want to add your app? Found an app that no longer works or no longer uses React Native? Please submit a pull request on <a href="https://github.com/facebook/react-native">GitHub</a> to update this page!</p>
</div>
<div className="inner-content showcaseHeader">
<h1 style={{textAlign: 'center'}}>Featured Apps</h1>
<div className="subHeader"></div>
<p>These are some of the most well-crafted React Native apps that we have come across.<br/>Be sure to check them out to get a feel for what React Native is capable of!</p>
</div>
<div className="inner-content">
<AppList apps={featured} />
</div>
<div className="inner-content showcaseHeader">
<h1 style={{textAlign: 'center'}}>All Apps</h1>
<p>Not all apps can be featured, otherwise we would have to create some other category like "super featured" and that's just silly. But that doesn't mean you shouldn't check these apps out!</p>
</div>
<div className="inner-content">
<AppList apps={apps} />
</div>
</section>
</Site>
);
}
});
module.exports = showcase;
| Added Mobabuild for Android
Summary:Thanks for submitting a pull request! Please provide enough information so that others can review your pull request:
(You can skip this if you're fixing a typo or adding an app to the Showcase.)
Explain the **motivation** for making this change. What existing problem does the pull request solve?
Example: When "Adding a function to do X", explain why it is necessary to have a way to do X.
**Test plan (required)**
Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes UI.
Make sure tests pass on both Travis and Circle CI.
**Code formatting**
Look around. Match the style of the rest of the codebase. See also the simple [style guide](https://github.com/facebook/react-native/blob/master/CONTRIBUTING.md#style-guide).
Closes https://github.com/facebook/react-native/pull/6497
Differential Revision: D3063800
fb-gh-sync-id: b91d99e4fcac2278aadd4fd17c38995df42720a2
shipit-source-id: b91d99e4fcac2278aadd4fd17c38995df42720a2
| website/src/react-native/showcase.js | Added Mobabuild for Android | <ide><path>ebsite/src/react-native/showcase.js
<ide> {
<ide> name: 'Mobabuild',
<ide> icon: 'http://mobabuild.co/images/applogo.png',
<del> link: 'http://mobabuild.co',
<add> linkAppStore: 'https://itunes.apple.com/tr/app/mobabuild-builds-for-league/id1059193502?l=tr&mt=8',
<add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.sercanov.mobabuild',
<ide> author: 'Sercan Demircan ( @sercanov )',
<ide> },
<ide> { |
|
JavaScript | mit | 42e547a4273255f40fb24e18f73879532c8ee549 | 0 | valerii-zinchenko/inheritance-diagram | var Class = require('class-wrapper').Class;
var d3 = require('d3-selection');
/**
* Rendering engine
*
* It renders the positioned nodes and bind them with arrows.
*
* @param {Object} [nodeProperties] - see [setNodeProperties]{@link Rendering#setProperties}
*/
var Rendering = Class(function(nodeProperties) {
if (nodeProperties) {
this.setNodeProperties(nodeProperties);
}
}, /** @lends Rendering.prototype */ {
nodeProperties: {
dimensions: {
width: 80,
height: 30
},
spacing: {
horizontal: 10,
vertical: 10
},
text: {
dx: 10,
dy: 20
}
},
/**
* Scaling factors of X and Y coordiantes
*
* @type {Object}
* @property {Number} x - Scale factor for X coordinates
* @property {Number} y - Scale factor for Y coordinates
*/
_scale: {
x: 100,
y: 50
},
/**
* Reset the node properies
*
* @param {Object} [properties] - Properties. Any of already defined properties can be redefined and new one can be added. Only property names which value is undefined will be skipped and warnong message will be displayed in the console.
*/
setNodeProprties: function(properties) {
for (var property in properties) {
let value = properties[property];
if (typeof value === 'undefined') {
console.warn(`Rendering.setProperties(): property ${property} is skipped because it's value is undefined`);
continue;
}
this.nodeProperties[property] = properties[property];
}
// Calculate the scaling factors for the real (rendered) coordinate system
// --------------------------------------------------
var props = this.nodeProperties;
this._scale.x = props.dimensions.width + 2 * props.spacing.horizontal;
this._scale.y = props.dimensions.height + 2 * props.spacing.vertical;
// --------------------------------------------------
},
/**
* Set nodes, which will be rendered
*
* @param {GraphNode[]} nodes - Set of nodes
*/
render: function(nodes) {
var minX = Infinity;
var maxX = -Infinity;
var minY = Infinity;
var maxY = -Infinity;
// Create the base contained elements for the diagram
// --------------------------------------------------
var domContainer = d3.select('body');
var domSvg = domContainer.append('svg');
var domDiagram = domSvg.append('g')
// --------------------------------------------------
// Render the nodes and find the real diagram boundaries
// --------------------------------------------------
nodes.forEach(node => {
var domNode = this.renderNode(node, domDiagram);
//node's X and Y coordinates are rescaled in the method renderNode
if (minX > node.x) {
minX = node.x;
}
if (maxX < node.x) {
maxX = node.x;
}
if (minY > node.y) {
minY = node.y;
}
if (maxY < node.y) {
maxY = node.y;
}
});
// --------------------------------------------------
// TODO Render connection lines
// --------------------------------------------------
// --------------------------------------------------
// Setup the properties for the diagram containers
// --------------------------------------------------
var props = this.nodeProperties;
domSvg
.attr('width', (maxX - minX) + props.dimensions.width + props.spacing.horizontal)
.attr('height', (maxY - minY) + props.dimensions.height + props.spacing.vertical)
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr('xmlns:xlink', 'http://www.w3.org/1999/xlink')
.attr('version', '1.1');
domDiagram.attr('transform', `translate(${-minx}, ${-minY}`);
// --------------------------------------------------
return domDiagram;
},
/**
* Render a node
*
* @param {GraphNode} node - Node which will be rendered
* @param {D3Selection} domContainer - DOM comntainer where the rendered node will be placed.
*/
renderNode: function(node, domContainer) {
var props = this.nodeProperties;
var domNode;
// Reposition node by taking into the account the real element dimensaions
// --------------------------------------------------
node.x = node.x * this._scale.x + props.spacing.horizontal;
node.y = node.y * this._scale.y + props.spacing.vertical;
// --------------------------------------------------
// Create a group for the all elements related to the node: rectangle, link, text
// --------------------------------------------------
domNode = domContainer.append('g')
.attr('class', node.type)
.attr('transform', `translate(${node.x}, ${node.y})`);
// --------------------------------------------------
// App link element if possible and make that element as the main container of rectangle and text
// --------------------------------------------------
if (node.link) {
domNode = domNode.append('a')
.attr('xlink:href', node.link);
}
// --------------------------------------------------
// Create rectangle element in the main container
// --------------------------------------------------
var domBorder = domNode.append('rect')
.attr('width', props.dimensions.width)
.attr('height', props.dimensions.height);
// --------------------------------------------------
// Add text (node name) into the main container
// --------------------------------------------------
var domText = domNode.appen('text');
for (var attr in props.text) {
domText.attr(attr, props.text[attr]);
}
domText.text(node.name);
// --------------------------------------------------
return domG;
},
renderConnectionLine: function(nodeA, nodeB) {
}
});
| src/rendering.js | var Class = require('class-wrapper').Class;
var GraphNode = require('./src/GraphNode');
var d3 = require('d3-selection');
/**
* Rendering engine
*
* It renders the positioned nodes and bind them with arrows.
*
* @param {Object} [properties] - Properties. Any of already defined properties can be redefined and new one can be added. Only property names which are already defined for methods or if the value is undefined, then such properties will be skipped and warnong message will be displayed in the console.
*/
var Rendering = Class(function(properties) {
if (properties) {
this.setProperties(properties);
}
}, /** @lends Rendering.prototype */ {
cssFile: '',
nodeDimensions: {
width: 80,
height: 30
},
spacing: {
horizontal: 10,
vertical: 10
},
text: {
dx: 10,
dy: 20,
'text-anchor': 'middle'
},
_scale: {
x: 100,
y: 50
},
/**
* Reset the properies
*
* @param {Object} [properties] - Properties. Any of already defined properties can be redefined and new one can be added. Only property names which are already defined for methods or if the value is undefined, then such properties will be skipped and warnong message will be displayed in the console.
*/
setProprties: function(properties) {
Object.keys(properties).forEarch(property => {
if (typeof this[property] === 'function') {
console.warn(`Rendering(): property ${property} is skipped because this name is already reserved for a method`);
return;
}
var value = properties[property];
if (typeof value === 'undefined') {
console.warn(`Rendering(): property ${property} is skipped because it's value is undefined`);
return;
}
this[property] = properties[property];
});
this._scale.x = this.nodeDimensions.width + 2 * this.spacing.horizontal;
this._scale.y = this.nodeDimensions.height + 2 * this.spacing.vertical;
},
/**
* Set nodes, which will be rendered
*
* @param {GraphNode[]} nodes - Set of nodes
*/
render: function(nodes) {
var maxX = 0;
var maxY = 0;
var domContainer = d3.select('body');
var domSvg = domContainer.append('svg');
nodes.forEach(node => {
var domNode = this.renderNode(node, domSvg);
//node's X and Y coordinates are rescaled in the method renderNode
if (maxX < node.x) {
maxX = node.x;
}
if (maxY < node.y) {
maxY = node.y;
}
});
domSvg.attr('width', maxX + this.nodeDimensions.width + this.spacing.horizontal);
domSvg.attr('height', maxY + this.nodeDimensions.height + this.spacing.vertical);
return domContainer;
},
renderNode: function(node, domContainer) {
node.x = (node.x + 0.5) * this._scale.x
node.y = (node.y + 0.5) * this._scale.y
var domG = domContainer.append('g')
.attr('class', node.type)
.attr('transform', `translate(${node.x}, ${node.y})`);
var domA = domG.append('a')
.attr('xlink:href', node.link);
var domBorder = domA.append('rect')
.attr('width', this.nodeDimensions.width)
.attr('height', this.nodeDimensions.height);
var domText = domA.appen('text');
for (var attr in this.text) {
domText.attr(attr, this.text[attr]);
}
domText.text(node.name);
return domG;
},
renderConnectionLine: function(nodeA, nodeB) {
}
});
| init: define the main algorithms for rendering sub-routine
Rendering of connecting lines is not ready.
| src/rendering.js | init: define the main algorithms for rendering sub-routine | <ide><path>rc/rendering.js
<ide> var Class = require('class-wrapper').Class;
<del>var GraphNode = require('./src/GraphNode');
<ide> var d3 = require('d3-selection');
<ide>
<ide> /**
<ide> *
<ide> * It renders the positioned nodes and bind them with arrows.
<ide> *
<del> * @param {Object} [properties] - Properties. Any of already defined properties can be redefined and new one can be added. Only property names which are already defined for methods or if the value is undefined, then such properties will be skipped and warnong message will be displayed in the console.
<add> * @param {Object} [nodeProperties] - see [setNodeProperties]{@link Rendering#setProperties}
<ide> */
<del>var Rendering = Class(function(properties) {
<del> if (properties) {
<del> this.setProperties(properties);
<add>var Rendering = Class(function(nodeProperties) {
<add> if (nodeProperties) {
<add> this.setNodeProperties(nodeProperties);
<ide> }
<ide> }, /** @lends Rendering.prototype */ {
<del> cssFile: '',
<del> nodeDimensions: {
<del> width: 80,
<del> height: 30
<add> nodeProperties: {
<add> dimensions: {
<add> width: 80,
<add> height: 30
<add> },
<add> spacing: {
<add> horizontal: 10,
<add> vertical: 10
<add> },
<add> text: {
<add> dx: 10,
<add> dy: 20
<add> }
<ide> },
<del> spacing: {
<del> horizontal: 10,
<del> vertical: 10
<del> },
<del> text: {
<del> dx: 10,
<del> dy: 20,
<del> 'text-anchor': 'middle'
<del> },
<add>
<add> /**
<add> * Scaling factors of X and Y coordiantes
<add> *
<add> * @type {Object}
<add> * @property {Number} x - Scale factor for X coordinates
<add> * @property {Number} y - Scale factor for Y coordinates
<add> */
<ide> _scale: {
<ide> x: 100,
<ide> y: 50
<ide> },
<ide>
<ide> /**
<del> * Reset the properies
<add> * Reset the node properies
<ide> *
<del> * @param {Object} [properties] - Properties. Any of already defined properties can be redefined and new one can be added. Only property names which are already defined for methods or if the value is undefined, then such properties will be skipped and warnong message will be displayed in the console.
<add> * @param {Object} [properties] - Properties. Any of already defined properties can be redefined and new one can be added. Only property names which value is undefined will be skipped and warnong message will be displayed in the console.
<ide> */
<del> setProprties: function(properties) {
<del> Object.keys(properties).forEarch(property => {
<del> if (typeof this[property] === 'function') {
<del> console.warn(`Rendering(): property ${property} is skipped because this name is already reserved for a method`);
<del> return;
<add> setNodeProprties: function(properties) {
<add> for (var property in properties) {
<add> let value = properties[property];
<add> if (typeof value === 'undefined') {
<add> console.warn(`Rendering.setProperties(): property ${property} is skipped because it's value is undefined`);
<add> continue;
<ide> }
<ide>
<del> var value = properties[property];
<del> if (typeof value === 'undefined') {
<del> console.warn(`Rendering(): property ${property} is skipped because it's value is undefined`);
<del> return;
<del> }
<add> this.nodeProperties[property] = properties[property];
<add> }
<ide>
<del> this[property] = properties[property];
<del> });
<del>
<del> this._scale.x = this.nodeDimensions.width + 2 * this.spacing.horizontal;
<del> this._scale.y = this.nodeDimensions.height + 2 * this.spacing.vertical;
<add> // Calculate the scaling factors for the real (rendered) coordinate system
<add> // --------------------------------------------------
<add> var props = this.nodeProperties;
<add> this._scale.x = props.dimensions.width + 2 * props.spacing.horizontal;
<add> this._scale.y = props.dimensions.height + 2 * props.spacing.vertical;
<add> // --------------------------------------------------
<ide> },
<ide>
<ide> /**
<ide> * @param {GraphNode[]} nodes - Set of nodes
<ide> */
<ide> render: function(nodes) {
<del> var maxX = 0;
<del> var maxY = 0;
<add> var minX = Infinity;
<add> var maxX = -Infinity;
<add> var minY = Infinity;
<add> var maxY = -Infinity;
<add>
<add> // Create the base contained elements for the diagram
<add> // --------------------------------------------------
<ide> var domContainer = d3.select('body');
<add> var domSvg = domContainer.append('svg');
<add> var domDiagram = domSvg.append('g')
<add> // --------------------------------------------------
<ide>
<del> var domSvg = domContainer.append('svg');
<del>
<add> // Render the nodes and find the real diagram boundaries
<add> // --------------------------------------------------
<ide> nodes.forEach(node => {
<del> var domNode = this.renderNode(node, domSvg);
<add> var domNode = this.renderNode(node, domDiagram);
<ide>
<ide> //node's X and Y coordinates are rescaled in the method renderNode
<add> if (minX > node.x) {
<add> minX = node.x;
<add> }
<ide> if (maxX < node.x) {
<ide> maxX = node.x;
<add> }
<add> if (minY > node.y) {
<add> minY = node.y;
<ide> }
<ide> if (maxY < node.y) {
<ide> maxY = node.y;
<ide> }
<ide> });
<add> // --------------------------------------------------
<ide>
<del> domSvg.attr('width', maxX + this.nodeDimensions.width + this.spacing.horizontal);
<del> domSvg.attr('height', maxY + this.nodeDimensions.height + this.spacing.vertical);
<add> // TODO Render connection lines
<add> // --------------------------------------------------
<add> // --------------------------------------------------
<ide>
<del> return domContainer;
<add> // Setup the properties for the diagram containers
<add> // --------------------------------------------------
<add> var props = this.nodeProperties;
<add> domSvg
<add> .attr('width', (maxX - minX) + props.dimensions.width + props.spacing.horizontal)
<add> .attr('height', (maxY - minY) + props.dimensions.height + props.spacing.vertical)
<add> .attr('xmlns', 'http://www.w3.org/2000/svg')
<add> .attr('xmlns:xlink', 'http://www.w3.org/1999/xlink')
<add> .attr('version', '1.1');
<add>
<add> domDiagram.attr('transform', `translate(${-minx}, ${-minY}`);
<add> // --------------------------------------------------
<add>
<add> return domDiagram;
<ide> },
<ide>
<add> /**
<add> * Render a node
<add> *
<add> * @param {GraphNode} node - Node which will be rendered
<add> * @param {D3Selection} domContainer - DOM comntainer where the rendered node will be placed.
<add> */
<ide> renderNode: function(node, domContainer) {
<del> node.x = (node.x + 0.5) * this._scale.x
<del> node.y = (node.y + 0.5) * this._scale.y
<add> var props = this.nodeProperties;
<add> var domNode;
<ide>
<del> var domG = domContainer.append('g')
<add> // Reposition node by taking into the account the real element dimensaions
<add> // --------------------------------------------------
<add> node.x = node.x * this._scale.x + props.spacing.horizontal;
<add> node.y = node.y * this._scale.y + props.spacing.vertical;
<add> // --------------------------------------------------
<add>
<add> // Create a group for the all elements related to the node: rectangle, link, text
<add> // --------------------------------------------------
<add> domNode = domContainer.append('g')
<ide> .attr('class', node.type)
<ide> .attr('transform', `translate(${node.x}, ${node.y})`);
<add> // --------------------------------------------------
<ide>
<del> var domA = domG.append('a')
<del> .attr('xlink:href', node.link);
<add> // App link element if possible and make that element as the main container of rectangle and text
<add> // --------------------------------------------------
<add> if (node.link) {
<add> domNode = domNode.append('a')
<add> .attr('xlink:href', node.link);
<add> }
<add> // --------------------------------------------------
<ide>
<del> var domBorder = domA.append('rect')
<del> .attr('width', this.nodeDimensions.width)
<del> .attr('height', this.nodeDimensions.height);
<add> // Create rectangle element in the main container
<add> // --------------------------------------------------
<add> var domBorder = domNode.append('rect')
<add> .attr('width', props.dimensions.width)
<add> .attr('height', props.dimensions.height);
<add> // --------------------------------------------------
<ide>
<del> var domText = domA.appen('text');
<del> for (var attr in this.text) {
<del> domText.attr(attr, this.text[attr]);
<add> // Add text (node name) into the main container
<add> // --------------------------------------------------
<add> var domText = domNode.appen('text');
<add> for (var attr in props.text) {
<add> domText.attr(attr, props.text[attr]);
<ide> }
<ide> domText.text(node.name);
<add> // --------------------------------------------------
<ide>
<ide> return domG;
<ide> }, |
|
JavaScript | agpl-3.0 | 79a64395ea50eb5203d5b53e18ba10a9d73540f5 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | c0d3a9a4-2e62-11e5-9284-b827eb9e62be | helloWorld.js | c0ce1e08-2e62-11e5-9284-b827eb9e62be | c0d3a9a4-2e62-11e5-9284-b827eb9e62be | helloWorld.js | c0d3a9a4-2e62-11e5-9284-b827eb9e62be | <ide><path>elloWorld.js
<del>c0ce1e08-2e62-11e5-9284-b827eb9e62be
<add>c0d3a9a4-2e62-11e5-9284-b827eb9e62be |
|
Java | bsd-3-clause | fee2116b1e512996a6b75a74bbf4a15af47eed90 | 0 | ox-it/oxpoints-legacy-servlet,ox-it/oxpoints-legacy-servlet,ox-it/oxpoints-legacy-servlet | /**
* Copyright 2009 University of Oxford
*
* Written by Arno Mittelbach for the Erewhon Project
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package uk.ac.ox.oucs.erewhon.oxpq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.gaboto.EntityDoesNotExistException;
import net.sf.gaboto.ResourceDoesNotExistException;
import net.sf.gaboto.node.GabotoEntity;
import net.sf.gaboto.node.pool.EntityPool;
import net.sf.gaboto.node.pool.EntityPoolConfiguration;
import net.sf.gaboto.query.GabotoQuery;
import net.sf.gaboto.query.UnsupportedQueryFormatException;
import net.sf.gaboto.transformation.EntityPoolTransformer;
import net.sf.gaboto.transformation.GeoJSONPoolTransfomer;
import net.sf.gaboto.transformation.JSONPoolTransformer;
import net.sf.gaboto.transformation.KMLPoolTransformer;
import net.sf.gaboto.transformation.RDFPoolTransformerFactory;
import net.sf.gaboto.vocabulary.OxPointsVocab;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
/**
* A servlet to interrogate the OxPoints data.
*
* Try invoking with
* http://127.0.0.1:8080/oxp/OxPointsQueryServlet/type/College.kml
*
* Slashes are like dots in a method invocation.
*
* Format is a special case.
*
* Parameters are used for qualifiers which do not effect the number of entities
* in the pool.
*
*/
public class OxPointsQueryServlet extends OxPointsServlet {
private static final long serialVersionUID = 4155078999145248554L;
private static String gpsbabelVersion = null;
public void init() {
super.init();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
try {
System.err.println("about to estblish outputPool");
outputPool(request, response);
System.err.println("No Error here");
} catch (ResourceNotFoundException e) {
try {
response.sendError(404, e.getMessage());
} catch (IOException e1) {
error(request, response, new AnticipatedException("Problem reporting error: " + e.getMessage(), e1, 500));
}
} catch (EntityDoesNotExistException e) {
try {
response.sendError(404, e.getMessage());
} catch (IOException e1) {
error(request, response, new AnticipatedException("Problem reporting error: " + e.getMessage(),e1, 500));
}
} catch (AnticipatedException e) {
error(request, response, e);
}
}
void outputPool(HttpServletRequest request, HttpServletResponse response) throws ResourceNotFoundException {
Query query = Query.fromRequest(request);
switch (query.getReturnType()) {
case META_TIMESTAMP:
try {
response.getWriter().write(new Long(startTime.getTimeInMillis()).toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
return;
case META_NEXT_ID:
try {
response.getWriter().write(new Long(snapshot.getGaboto().getCurrentHighestId() + 1).toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
return;
case META_TYPES:
output(snapshot.getGaboto().getConfig().getGabotoOntologyLookup().getRegisteredEntityClassesAsClassNames(), query, response);
return;
case ALL:
output(EntityPool.createFrom(snapshot), query, response);
return;
case INDIVIDUAL:
System.err.println("Still here1");
EntityPool pool = new EntityPool(gaboto, snapshot);
System.err.println("Still here2");
establishParticipantUri(query);
System.err.println("Still here3");
System.err.println("We have " + snapshot.size() + " entities in snapshot before loadEntity");
pool.addEntity(snapshot.loadEntity(query.getUri()));
System.err.println("Still here4");
output(pool, query, response);
System.err.println("Still here5");
return;
case TYPE_COLLECTION:
output(loadPoolWithEntitiesOfType(query.getType()), query, response);
return;
case PROPERTY_ANY: // value null
output(loadPoolWithEntitiesOfProperty(query.getRequestedProperty(), query.getRequestedPropertyValue()), query,
response);
return;
case PROPERTY_SUBJECT:
EntityPool subjectPool = null;
if (requiresResource(query.getRequestedProperty())) {
establishParticipantUri(query);
if (query.getUri() == null)
throw new ResourceNotFoundException("Resource not found with coding " + query.getParticipantCoding() +
" and value " + query.getParticipantCode());
GabotoEntity object = snapshot.loadEntity(query.getUri());
EntityPool creationPool = EntityPool.createFrom(snapshot);
System.err.println("CreationPool size " + creationPool.size());
object.setCreatedFromPool(creationPool);
subjectPool = loadPoolWithActiveParticipants(object, query.getRequestedProperty());
} else {
subjectPool = loadPoolWithEntitiesOfProperty(query.getRequestedProperty(), query.getRequestedPropertyValue());
}
output(subjectPool, query, response);
return;
case PROPERTY_OBJECT:
establishParticipantUri(query);
if (query.getUri() == null)
throw new ResourceNotFoundException("Resource not found with coding " + query.getParticipantCoding() +
" and value " + query.getParticipantCode());
GabotoEntity subject = snapshot.loadEntity(query.getUri());
EntityPool objectPool = loadPoolWithPassiveParticipants(subject, query.getRequestedProperty());
output(objectPool, query, response);
return;
case NOT_FILTERED_TYPE_COLLECTION:
EntityPool p = loadPoolWithEntitiesOfType(query.getType());
EntityPool p2 = loadPoolWithEntitiesOfType(query.getType());
for (GabotoEntity e : p.getEntities())
if (e.getPropertyValue(query.getNotProperty(), false, false) != null)
p2.removeEntity(e);
output(p2, query,
response);
return;
default:
throw new RuntimeException("Fell through case with value " + query.getReturnType());
}
}
private EntityPool loadPoolWithEntitiesOfProperty(Property prop, String value) {
System.err.println("loadPoolWithEntitiesOfProperty" + prop + ":" + value);
if (prop == null)
throw new NullPointerException();
EntityPool pool = null;
if (value == null) {
pool = snapshot.loadEntitiesWithProperty(prop);
} else {
String values[] = value.split("[|]");
for (String v : values) {
if (requiresResource(prop)) {
Resource r = getResource(v);
System.err.println("About to load " + prop + " with value " + r);
pool = becomeOrAdd(pool, snapshot.loadEntitiesWithProperty(prop, r));
} else {
pool = becomeOrAdd(pool, snapshot.loadEntitiesWithProperty(prop, v));
}
}
}
return pool;
}
@SuppressWarnings("unchecked")
private EntityPool loadPoolWithActiveParticipants(GabotoEntity passiveParticipant, Property prop) {
if (prop == null)
throw new NullPointerException();
EntityPool pool = new EntityPool(gaboto, snapshot);
System.err.println("loadPoolWithActiveParticipants" + passiveParticipant.getUri() + " prop " + prop + " which ");
Set<Entry<String, Object>> passiveProperties = passiveParticipant.getAllPassiveProperties().entrySet();
for (Entry<String, Object> entry : passiveProperties) {
if (entry.getKey().equals(prop.getURI())) {
if (entry.getValue() != null) {
if (entry.getValue() instanceof HashSet) {
HashSet<Object> them = (HashSet<Object>)entry.getValue();
for (Object e : them) {
if (e instanceof GabotoEntity) {
System.err.println("Adding set member :" + e);
pool.add((GabotoEntity)e);
}
}
} else if (entry.getValue() instanceof GabotoEntity) {
System.err.println("Adding individual :" + entry.getKey());
pool.add((GabotoEntity)entry.getValue());
} else {
System.err.println("Ignoring:" + entry.getKey());
}
} else {
System.err.println("Ignoring:" + entry.getKey());
}
} else {
System.err.println("Ignoring:" + entry.getKey());
}
}
return pool;
}
private void establishParticipantUri(Query query) throws ResourceNotFoundException {
if (query.needsCodeLookup()) {
System.err.println("need");
Property coding = Query.getPropertyFromAbreviation(query.getParticipantCoding());
System.err.println("establishUri" + query.getParticipantCode());
EntityPool objectPool = snapshot.loadEntitiesWithProperty(coding, query.getParticipantCode());
boolean found = false;
for (GabotoEntity objectKey: objectPool) {
if (found)
throw new RuntimeException("Found two:" + objectKey);
query.setParticipantUri(objectKey.getUri());
found = true;
}
}
if (query.getParticipantUri() == null)
throw new ResourceNotFoundException("No resource found with coding " + query.getParticipantCoding() +
" and value " + query.getParticipantCode());
}
@SuppressWarnings("unchecked")
private EntityPool loadPoolWithPassiveParticipants(GabotoEntity activeParticipant, Property prop) {
if (prop == null)
throw new NullPointerException();
EntityPool pool = new EntityPool(gaboto, snapshot);
System.err.println("loadPoolWithPassiveParticipants" + activeParticipant.getUri() + " prop " + prop + " which ");
Set<Entry<String, Object>> directProperties = activeParticipant.getAllDirectProperties().entrySet();
for (Entry<String, Object> entry : directProperties) {
if (entry.getKey().equals(prop.getURI())) {
if (entry.getValue() != null) {
if (entry.getValue() instanceof HashSet) {
HashSet<Object> them = (HashSet<Object>)entry.getValue();
for (Object e : them) {
if (e instanceof GabotoEntity) {
pool.add((GabotoEntity)e);
}
}
} else if (entry.getValue() instanceof GabotoEntity) {
pool.add((GabotoEntity)entry.getValue());
} else {
System.err.println("Ignoring:" + entry.getKey());
}
} else {
System.err.println("Ignoring:" + entry.getKey());
}
} else {
System.err.println("Ignoring:" + entry.getKey());
}
}
return pool;
}
private EntityPool becomeOrAdd(EntityPool pool, EntityPool poolToAdd) {
System.err.println("BecomeOrAdd" + pool);
if (poolToAdd == null)
throw new NullPointerException();
if (pool == null) {
return poolToAdd;
} else {
for (GabotoEntity e : poolToAdd.getEntities()) {
pool.addEntity(e);
}
return pool;
}
}
private Resource getResource(String v) {
String vUri = v;
if (!vUri.startsWith(config.getNSData()))
vUri = config.getNSData() + v;
try {
return snapshot.getResource(vUri);
} catch (ResourceDoesNotExistException e) {
throw new RuntimeException(e);
}
}
private boolean requiresResource(Property property) {
if (property.getLocalName().endsWith("subsetOf")) {
return true;
} else if (property.getLocalName().endsWith("physicallyContainedWithin")) {
return true;
} else if (property.getLocalName().endsWith("hasPrimaryPlace")) {
return true;
} else if (property.getLocalName().endsWith("occupies")) {
return true;
} else if (property.getLocalName().endsWith("associatedWith")) {
return true;
}
return false;
}
private EntityPool loadPoolWithEntitiesOfType(String type) {
System.err.println("Type:" + type);
String types[] = type.split("[|]");
EntityPoolConfiguration conf = new EntityPoolConfiguration(snapshot);
for (String t : types) {
if (!snapshot.getGaboto().getConfig().getGabotoOntologyLookup().isValidName(t))
throw new IllegalArgumentException("Found no URI matching type " + t);
String typeURI = OxPointsVocab.NS + t;
conf.addAcceptedType(typeURI);
}
return EntityPool.createFrom(conf);
}
private void output(Collection<String> them, Query query, HttpServletResponse response) {
try {
if (query.getFormat().equals("txt")) {
boolean doneOne = false;
for (String member : them) {
if (doneOne)
response.getWriter().write("|");
response.getWriter().write(member);
doneOne = true;
}
response.getWriter().write("\n");
} else if (query.getFormat().equals("csv")) {
boolean doneOne = false;
for (String member : them) {
if (doneOne)
response.getWriter().write(",");
response.getWriter().write(member);
doneOne = true;
}
response.getWriter().write("\n");
} else if (query.getFormat().equals("js")) {
boolean doneOne = false;
response.getWriter().write("var oxpointsTypes = [");
for (String member : them) {
if (doneOne)
response.getWriter().write(",");
response.getWriter().write("'");
response.getWriter().write(member);
response.getWriter().write("'");
doneOne = true;
}
response.getWriter().write("];\n");
} else if (query.getFormat().equals("xml")) {
response.getWriter().write("<c>");
for (String member : them) {
response.getWriter().write("<i>");
response.getWriter().write(member);
response.getWriter().write("</i>");
}
response.getWriter().write("</c>");
response.getWriter().write("\n");
} else
throw new AnticipatedException("Unexpected format " + query.getFormat(), 400);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void output(EntityPool pool, Query query, HttpServletResponse response) {
System.err.println("Pool has " + pool.getSize() + " elements");
String output = "";
if (query.getFormat().equals("kml")) {
output = createKml(pool, query);
response.setContentType("application/vnd.google-earth.kml+xml");
} else if (query.getFormat().equals("json") || query.getFormat().equals("js")) {
JSONPoolTransformer transformer = new JSONPoolTransformer();
transformer.setNesting(query.getJsonDepth());
output = transformer.transform(pool);
if (query.getFormat().equals("js")) {
output = query.getJsCallback() + "(" + output + ");";
}
response.setContentType("text/javascript");
} else if (query.getFormat().equals("gjson")) {
GeoJSONPoolTransfomer transformer = new GeoJSONPoolTransfomer();
if (query.getArc() != null) {
transformer.addEntityFolderType(query.getFolderClassURI(), query.getArcProperty().getURI());
}
if (query.getOrderBy() != null) {
transformer.setOrderBy(query.getOrderByProperty().getURI());
}
transformer.setDisplayParentName(query.getDisplayParentName());
output += transformer.transform(pool);
if (query.getJsCallback() != null)
output = query.getJsCallback() + "(" + output + ");";
response.setContentType("text/javascript");
} else if (query.getFormat().equals("xml")) {
EntityPoolTransformer transformer;
try {
transformer = RDFPoolTransformerFactory.getRDFPoolTransformer(GabotoQuery.FORMAT_RDF_XML_ABBREV);
output = transformer.transform(pool);
} catch (UnsupportedQueryFormatException e) {
throw new IllegalArgumentException(e);
}
response.setContentType("application/rdf+xml");
} else if (query.getFormat().equals("txt")) {
try {
for (GabotoEntity entity: pool.getEntities()) {
response.getWriter().write(entity.toString() + "\n");
for (Entry<String, Object> entry : entity.getAllDirectProperties().entrySet()) {
if (entry.getValue() != null)
response.getWriter().write(" " + entry.getKey() + " : " + entry.getValue() + "\n");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
response.setContentType("text/plain");
} else {
output = runGPSBabel(createKml(pool, query), "kml", query.getFormat());
if (output.equals(""))
throw new RuntimeException("No output created by GPSBabel");
}
// System.err.println("output:" + output + ":");
try {
response.getWriter().write(output);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String createKml(EntityPool pool, Query query) {
String output;
KMLPoolTransformer transformer = new KMLPoolTransformer();
if (query.getArc() != null) {
transformer.addEntityFolderType(query.getFolderClassURI(), query.getArcProperty().getURI());
}
if (query.getOrderBy() != null) {
transformer.setOrderBy(query.getOrderByProperty().getURI());
}
transformer.setDisplayParentName(query.getDisplayParentName());
output = transformer.transform(pool);
return output;
}
/**
* @param input
* A String, normally kml
* @param formatIn
* format name, other than kml
* @param formatOut
* what you want out
* @return the reformatted String
*/
public static String runGPSBabel(String input, String formatIn, String formatOut) {
// '/usr/bin/gpsbabel -i kml -o ' . $format . ' -f ' . $In . ' -F ' . $Out;
if (formatIn == null)
formatIn = "kml";
if (formatOut == null)
throw new IllegalArgumentException("Missing output format for GPSBabel");
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
String output = "";
String command = "/usr/bin/gpsbabel -i " + formatIn + " -o " + formatOut + " -f - -F -";
System.err.println("GPSBabel command:" + command);
Process process;
try {
process = Runtime.getRuntime().exec(command, null, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
stdin = process.getOutputStream();
stdout = process.getInputStream();
stderr = process.getErrorStream();
try {
stdin.write(input.getBytes());
stdin.flush();
stdin.close();
} catch (IOException e) {
// clean up if any output in stderr
BufferedReader errBufferedReader = new BufferedReader(new InputStreamReader(stderr));
String stderrString = "";
String stderrLine = null;
try {
while ((stderrLine = errBufferedReader.readLine()) != null) {
System.err.println("[Stderr Ex] " + stderrLine);
stderrString += stderrLine;
}
errBufferedReader.close();
} catch (IOException e2) {
throw new RuntimeException("Command " + command + " stderr reader failed:" + e2);
}
throw new RuntimeException("Command " + command + " gave error:\n" + stderrString);
}
BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
String line;
try {
while ((line = brCleanUp.readLine()) != null) {
System.out.println("[Stdout] " + line);
output += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
// clean up if any output in stderr
brCleanUp = new BufferedReader(new InputStreamReader(stderr));
String stderrString = "";
try {
while ((line = brCleanUp.readLine()) != null) {
System.err.println("[Stderr] " + line);
stderrString += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!stderrString.equals(""))
throw new RuntimeException("Command " + command + " gave error:\n" + stderrString);
} finally {
process.destroy();
}
return output;
}
public static String getGPSBabelVersion() {
if (gpsbabelVersion != null )
return gpsbabelVersion;
// '/usr/bin/gpsbabel -V
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
String output = "";
String command = "/usr/bin/gpsbabel -V";
System.err.println("GPSBabel command:" + command);
Process process;
try {
process = Runtime.getRuntime().exec(command, null, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
stdin = process.getOutputStream();
stdout = process.getInputStream();
stderr = process.getErrorStream();
stdin.flush();
stdin.close();
BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
String line;
try {
while ((line = brCleanUp.readLine()) != null) {
System.out.println("[Stdout] " + line);
output += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
// clean up if any output in stderr
brCleanUp = new BufferedReader(new InputStreamReader(stderr));
String stderrString = "";
try {
while ((line = brCleanUp.readLine()) != null) {
System.err.println("[Stderr] " + line);
stderrString += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!stderrString.equals(""))
throw new RuntimeException("Command " + command + " gave error:\n" + stderrString);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
process.destroy();
}
//GPSBabel Version 1.3.6
gpsbabelVersion = output.substring("GPSBabel Version ".length());
return gpsbabelVersion;
}
}
| src/main/java/uk/ac/ox/oucs/erewhon/oxpq/OxPointsQueryServlet.java | /**
* Copyright 2009 University of Oxford
*
* Written by Arno Mittelbach for the Erewhon Project
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package uk.ac.ox.oucs.erewhon.oxpq;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.gaboto.EntityDoesNotExistException;
import net.sf.gaboto.ResourceDoesNotExistException;
import net.sf.gaboto.node.GabotoEntity;
import net.sf.gaboto.node.pool.EntityPool;
import net.sf.gaboto.node.pool.EntityPoolConfiguration;
import net.sf.gaboto.query.GabotoQuery;
import net.sf.gaboto.query.UnsupportedQueryFormatException;
import net.sf.gaboto.transformation.EntityPoolTransformer;
import net.sf.gaboto.transformation.GeoJSONPoolTransfomer;
import net.sf.gaboto.transformation.JSONPoolTransformer;
import net.sf.gaboto.transformation.KMLPoolTransformer;
import net.sf.gaboto.transformation.RDFPoolTransformerFactory;
import net.sf.gaboto.vocabulary.OxPointsVocab;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
/**
* A servlet to interrogate the OxPoints data.
*
* Try invoking with
* http://127.0.0.1:8080/oxp/OxPointsQueryServlet/type/College.kml
*
* Slashes are like dots in a method invocation.
*
* Format is a special case.
*
* Parameters are used for qualifiers which do not effect the number of entities
* in the pool.
*
*/
public class OxPointsQueryServlet extends OxPointsServlet {
private static final long serialVersionUID = 4155078999145248554L;
private static String gpsbabelVersion = null;
public void init() {
super.init();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
System.err.println("Still here");
Enumeration<String> them = getServletConfig().getInitParameterNames();
while (them.hasMoreElements()) {
String it = them.nextElement();
System.err.println(it + "=" + getServletConfig().getInitParameter(it));
}
response.setCharacterEncoding("UTF-8");
try {
System.err.println("about to estblish outputPool");
outputPool(request, response);
System.err.println("No Error here");
} catch (ResourceNotFoundException e) {
try {
response.sendError(404, e.getMessage());
} catch (IOException e1) {
error(request, response, new AnticipatedException("Problem reporting error: " + e.getMessage(), e1, 500));
}
} catch (EntityDoesNotExistException e) {
try {
response.sendError(404, e.getMessage());
} catch (IOException e1) {
error(request, response, new AnticipatedException("Problem reporting error: " + e.getMessage(),e1, 500));
}
} catch (AnticipatedException e) {
error(request, response, e);
}
}
void outputPool(HttpServletRequest request, HttpServletResponse response) throws ResourceNotFoundException {
Query query = Query.fromRequest(request);
switch (query.getReturnType()) {
case META_TIMESTAMP:
try {
response.getWriter().write(new Long(startTime.getTimeInMillis()).toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
return;
case META_NEXT_ID:
try {
response.getWriter().write(new Long(snapshot.getGaboto().getCurrentHighestId() + 1).toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
return;
case META_TYPES:
output(snapshot.getGaboto().getConfig().getGabotoOntologyLookup().getRegisteredEntityClassesAsClassNames(), query, response);
return;
case ALL:
output(EntityPool.createFrom(snapshot), query, response);
return;
case INDIVIDUAL:
System.err.println("Still here1");
EntityPool pool = new EntityPool(gaboto, snapshot);
System.err.println("Still here2");
establishParticipantUri(query);
System.err.println("Still here3");
System.err.println("We have " + snapshot.size() + " entities in snapshot before loadEntity");
pool.addEntity(snapshot.loadEntity(query.getUri()));
System.err.println("Still here4");
output(pool, query, response);
System.err.println("Still here5");
return;
case TYPE_COLLECTION:
output(loadPoolWithEntitiesOfType(query.getType()), query, response);
return;
case PROPERTY_ANY: // value null
output(loadPoolWithEntitiesOfProperty(query.getRequestedProperty(), query.getRequestedPropertyValue()), query,
response);
return;
case PROPERTY_SUBJECT:
EntityPool subjectPool = null;
if (requiresResource(query.getRequestedProperty())) {
establishParticipantUri(query);
if (query.getUri() == null)
throw new ResourceNotFoundException("Resource not found with coding " + query.getParticipantCoding() +
" and value " + query.getParticipantCode());
GabotoEntity object = snapshot.loadEntity(query.getUri());
EntityPool creationPool = EntityPool.createFrom(snapshot);
System.err.println("CreationPool size " + creationPool.size());
object.setCreatedFromPool(creationPool);
subjectPool = loadPoolWithActiveParticipants(object, query.getRequestedProperty());
} else {
subjectPool = loadPoolWithEntitiesOfProperty(query.getRequestedProperty(), query.getRequestedPropertyValue());
}
output(subjectPool, query, response);
return;
case PROPERTY_OBJECT:
establishParticipantUri(query);
if (query.getUri() == null)
throw new ResourceNotFoundException("Resource not found with coding " + query.getParticipantCoding() +
" and value " + query.getParticipantCode());
GabotoEntity subject = snapshot.loadEntity(query.getUri());
EntityPool objectPool = loadPoolWithPassiveParticipants(subject, query.getRequestedProperty());
output(objectPool, query, response);
return;
case NOT_FILTERED_TYPE_COLLECTION:
EntityPool p = loadPoolWithEntitiesOfType(query.getType());
EntityPool p2 = loadPoolWithEntitiesOfType(query.getType());
for (GabotoEntity e : p.getEntities())
if (e.getPropertyValue(query.getNotProperty(), false, false) != null)
p2.removeEntity(e);
output(p2, query,
response);
return;
default:
throw new RuntimeException("Fell through case with value " + query.getReturnType());
}
}
private EntityPool loadPoolWithEntitiesOfProperty(Property prop, String value) {
System.err.println("loadPoolWithEntitiesOfProperty" + prop + ":" + value);
if (prop == null)
throw new NullPointerException();
EntityPool pool = null;
if (value == null) {
pool = snapshot.loadEntitiesWithProperty(prop);
} else {
String values[] = value.split("[|]");
for (String v : values) {
if (requiresResource(prop)) {
Resource r = getResource(v);
System.err.println("About to load " + prop + " with value " + r);
pool = becomeOrAdd(pool, snapshot.loadEntitiesWithProperty(prop, r));
} else {
pool = becomeOrAdd(pool, snapshot.loadEntitiesWithProperty(prop, v));
}
}
}
return pool;
}
@SuppressWarnings("unchecked")
private EntityPool loadPoolWithActiveParticipants(GabotoEntity passiveParticipant, Property prop) {
if (prop == null)
throw new NullPointerException();
EntityPool pool = new EntityPool(gaboto, snapshot);
System.err.println("loadPoolWithActiveParticipants" + passiveParticipant.getUri() + " prop " + prop + " which ");
Set<Entry<String, Object>> passiveProperties = passiveParticipant.getAllPassiveProperties().entrySet();
for (Entry<String, Object> entry : passiveProperties) {
if (entry.getKey().equals(prop.getURI())) {
if (entry.getValue() != null) {
if (entry.getValue() instanceof HashSet) {
HashSet<Object> them = (HashSet<Object>)entry.getValue();
for (Object e : them) {
if (e instanceof GabotoEntity) {
System.err.println("Adding set member :" + e);
pool.add((GabotoEntity)e);
}
}
} else if (entry.getValue() instanceof GabotoEntity) {
System.err.println("Adding individual :" + entry.getKey());
pool.add((GabotoEntity)entry.getValue());
} else {
System.err.println("Ignoring:" + entry.getKey());
}
} else {
System.err.println("Ignoring:" + entry.getKey());
}
} else {
System.err.println("Ignoring:" + entry.getKey());
}
}
return pool;
}
private void establishParticipantUri(Query query) throws ResourceNotFoundException {
if (query.needsCodeLookup()) {
System.err.println("need");
Property coding = Query.getPropertyFromAbreviation(query.getParticipantCoding());
System.err.println("establishUri" + query.getParticipantCode());
EntityPool objectPool = snapshot.loadEntitiesWithProperty(coding, query.getParticipantCode());
boolean found = false;
for (GabotoEntity objectKey: objectPool) {
if (found)
throw new RuntimeException("Found two:" + objectKey);
query.setParticipantUri(objectKey.getUri());
found = true;
}
}
if (query.getParticipantUri() == null)
throw new ResourceNotFoundException("No resource found with coding " + query.getParticipantCoding() +
" and value " + query.getParticipantCode());
}
@SuppressWarnings("unchecked")
private EntityPool loadPoolWithPassiveParticipants(GabotoEntity activeParticipant, Property prop) {
if (prop == null)
throw new NullPointerException();
EntityPool pool = new EntityPool(gaboto, snapshot);
System.err.println("loadPoolWithPassiveParticipants" + activeParticipant.getUri() + " prop " + prop + " which ");
Set<Entry<String, Object>> directProperties = activeParticipant.getAllDirectProperties().entrySet();
for (Entry<String, Object> entry : directProperties) {
if (entry.getKey().equals(prop.getURI())) {
if (entry.getValue() != null) {
if (entry.getValue() instanceof HashSet) {
HashSet<Object> them = (HashSet<Object>)entry.getValue();
for (Object e : them) {
if (e instanceof GabotoEntity) {
pool.add((GabotoEntity)e);
}
}
} else if (entry.getValue() instanceof GabotoEntity) {
pool.add((GabotoEntity)entry.getValue());
} else {
System.err.println("Ignoring:" + entry.getKey());
}
} else {
System.err.println("Ignoring:" + entry.getKey());
}
} else {
System.err.println("Ignoring:" + entry.getKey());
}
}
return pool;
}
private EntityPool becomeOrAdd(EntityPool pool, EntityPool poolToAdd) {
System.err.println("BecomeOrAdd" + pool);
if (poolToAdd == null)
throw new NullPointerException();
if (pool == null) {
return poolToAdd;
} else {
for (GabotoEntity e : poolToAdd.getEntities()) {
pool.addEntity(e);
}
return pool;
}
}
private Resource getResource(String v) {
String vUri = v;
if (!vUri.startsWith(config.getNSData()))
vUri = config.getNSData() + v;
try {
return snapshot.getResource(vUri);
} catch (ResourceDoesNotExistException e) {
throw new RuntimeException(e);
}
}
private boolean requiresResource(Property property) {
if (property.getLocalName().endsWith("subsetOf")) {
return true;
} else if (property.getLocalName().endsWith("physicallyContainedWithin")) {
return true;
} else if (property.getLocalName().endsWith("hasPrimaryPlace")) {
return true;
} else if (property.getLocalName().endsWith("occupies")) {
return true;
} else if (property.getLocalName().endsWith("associatedWith")) {
return true;
}
return false;
}
private EntityPool loadPoolWithEntitiesOfType(String type) {
System.err.println("Type:" + type);
String types[] = type.split("[|]");
EntityPoolConfiguration conf = new EntityPoolConfiguration(snapshot);
for (String t : types) {
if (!snapshot.getGaboto().getConfig().getGabotoOntologyLookup().isValidName(t))
throw new IllegalArgumentException("Found no URI matching type " + t);
String typeURI = OxPointsVocab.NS + t;
conf.addAcceptedType(typeURI);
}
return EntityPool.createFrom(conf);
}
private void output(Collection<String> them, Query query, HttpServletResponse response) {
try {
if (query.getFormat().equals("txt")) {
boolean doneOne = false;
for (String member : them) {
if (doneOne)
response.getWriter().write("|");
response.getWriter().write(member);
doneOne = true;
}
response.getWriter().write("\n");
} else if (query.getFormat().equals("csv")) {
boolean doneOne = false;
for (String member : them) {
if (doneOne)
response.getWriter().write(",");
response.getWriter().write(member);
doneOne = true;
}
response.getWriter().write("\n");
} else if (query.getFormat().equals("js")) {
boolean doneOne = false;
response.getWriter().write("var oxpointsTypes = [");
for (String member : them) {
if (doneOne)
response.getWriter().write(",");
response.getWriter().write("'");
response.getWriter().write(member);
response.getWriter().write("'");
doneOne = true;
}
response.getWriter().write("];\n");
} else if (query.getFormat().equals("xml")) {
response.getWriter().write("<c>");
for (String member : them) {
response.getWriter().write("<i>");
response.getWriter().write(member);
response.getWriter().write("</i>");
}
response.getWriter().write("</c>");
response.getWriter().write("\n");
} else
throw new AnticipatedException("Unexpected format " + query.getFormat(), 400);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void output(EntityPool pool, Query query, HttpServletResponse response) {
System.err.println("Pool has " + pool.getSize() + " elements");
String output = "";
if (query.getFormat().equals("kml")) {
output = createKml(pool, query);
response.setContentType("application/vnd.google-earth.kml+xml");
} else if (query.getFormat().equals("json") || query.getFormat().equals("js")) {
JSONPoolTransformer transformer = new JSONPoolTransformer();
transformer.setNesting(query.getJsonDepth());
output = transformer.transform(pool);
if (query.getFormat().equals("js")) {
output = query.getJsCallback() + "(" + output + ");";
}
response.setContentType("text/javascript");
} else if (query.getFormat().equals("gjson")) {
GeoJSONPoolTransfomer transformer = new GeoJSONPoolTransfomer();
if (query.getArc() != null) {
transformer.addEntityFolderType(query.getFolderClassURI(), query.getArcProperty().getURI());
}
if (query.getOrderBy() != null) {
transformer.setOrderBy(query.getOrderByProperty().getURI());
}
transformer.setDisplayParentName(query.getDisplayParentName());
output += transformer.transform(pool);
if (query.getJsCallback() != null)
output = query.getJsCallback() + "(" + output + ");";
response.setContentType("text/javascript");
} else if (query.getFormat().equals("xml")) {
EntityPoolTransformer transformer;
try {
transformer = RDFPoolTransformerFactory.getRDFPoolTransformer(GabotoQuery.FORMAT_RDF_XML_ABBREV);
output = transformer.transform(pool);
} catch (UnsupportedQueryFormatException e) {
throw new IllegalArgumentException(e);
}
response.setContentType("application/rdf+xml");
} else if (query.getFormat().equals("txt")) {
try {
for (GabotoEntity entity: pool.getEntities()) {
response.getWriter().write(entity.toString() + "\n");
for (Entry<String, Object> entry : entity.getAllDirectProperties().entrySet()) {
if (entry.getValue() != null)
response.getWriter().write(" " + entry.getKey() + " : " + entry.getValue() + "\n");
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
response.setContentType("text/plain");
} else {
output = runGPSBabel(createKml(pool, query), "kml", query.getFormat());
if (output.equals(""))
throw new RuntimeException("No output created by GPSBabel");
}
// System.err.println("output:" + output + ":");
try {
response.getWriter().write(output);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String createKml(EntityPool pool, Query query) {
String output;
KMLPoolTransformer transformer = new KMLPoolTransformer();
if (query.getArc() != null) {
transformer.addEntityFolderType(query.getFolderClassURI(), query.getArcProperty().getURI());
}
if (query.getOrderBy() != null) {
transformer.setOrderBy(query.getOrderByProperty().getURI());
}
transformer.setDisplayParentName(query.getDisplayParentName());
output = transformer.transform(pool);
return output;
}
/**
* @param input
* A String, normally kml
* @param formatIn
* format name, other than kml
* @param formatOut
* what you want out
* @return the reformatted String
*/
public static String runGPSBabel(String input, String formatIn, String formatOut) {
// '/usr/bin/gpsbabel -i kml -o ' . $format . ' -f ' . $In . ' -F ' . $Out;
if (formatIn == null)
formatIn = "kml";
if (formatOut == null)
throw new IllegalArgumentException("Missing output format for GPSBabel");
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
String output = "";
String command = "/usr/bin/gpsbabel -i " + formatIn + " -o " + formatOut + " -f - -F -";
System.err.println("GPSBabel command:" + command);
Process process;
try {
process = Runtime.getRuntime().exec(command, null, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
stdin = process.getOutputStream();
stdout = process.getInputStream();
stderr = process.getErrorStream();
try {
stdin.write(input.getBytes());
stdin.flush();
stdin.close();
} catch (IOException e) {
// clean up if any output in stderr
BufferedReader errBufferedReader = new BufferedReader(new InputStreamReader(stderr));
String stderrString = "";
String stderrLine = null;
try {
while ((stderrLine = errBufferedReader.readLine()) != null) {
System.err.println("[Stderr Ex] " + stderrLine);
stderrString += stderrLine;
}
errBufferedReader.close();
} catch (IOException e2) {
throw new RuntimeException("Command " + command + " stderr reader failed:" + e2);
}
throw new RuntimeException("Command " + command + " gave error:\n" + stderrString);
}
BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
String line;
try {
while ((line = brCleanUp.readLine()) != null) {
System.out.println("[Stdout] " + line);
output += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
// clean up if any output in stderr
brCleanUp = new BufferedReader(new InputStreamReader(stderr));
String stderrString = "";
try {
while ((line = brCleanUp.readLine()) != null) {
System.err.println("[Stderr] " + line);
stderrString += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!stderrString.equals(""))
throw new RuntimeException("Command " + command + " gave error:\n" + stderrString);
} finally {
process.destroy();
}
return output;
}
public static String getGPSBabelVersion() {
if (gpsbabelVersion != null )
return gpsbabelVersion;
// '/usr/bin/gpsbabel -V
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
String output = "";
String command = "/usr/bin/gpsbabel -V";
System.err.println("GPSBabel command:" + command);
Process process;
try {
process = Runtime.getRuntime().exec(command, null, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
stdin = process.getOutputStream();
stdout = process.getInputStream();
stderr = process.getErrorStream();
stdin.flush();
stdin.close();
BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
String line;
try {
while ((line = brCleanUp.readLine()) != null) {
System.out.println("[Stdout] " + line);
output += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
// clean up if any output in stderr
brCleanUp = new BufferedReader(new InputStreamReader(stderr));
String stderrString = "";
try {
while ((line = brCleanUp.readLine()) != null) {
System.err.println("[Stderr] " + line);
stderrString += line;
}
brCleanUp.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!stderrString.equals(""))
throw new RuntimeException("Command " + command + " gave error:\n" + stderrString);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
process.destroy();
}
//GPSBabel Version 1.3.6
gpsbabelVersion = output.substring("GPSBabel Version ".length());
return gpsbabelVersion;
}
}
| Remove debug
git-svn-id: d9f7cc7daa8f282b2d96bd72a85d1209eff67c0c@1296 98330f3f-1342-47a8-b5c6-0a1dd6e8dbeb
| src/main/java/uk/ac/ox/oucs/erewhon/oxpq/OxPointsQueryServlet.java | Remove debug | <ide><path>rc/main/java/uk/ac/ox/oucs/erewhon/oxpq/OxPointsQueryServlet.java
<ide> import java.io.InputStreamReader;
<ide> import java.io.OutputStream;
<ide> import java.util.Collection;
<del>import java.util.Enumeration;
<ide> import java.util.HashSet;
<ide> import java.util.Set;
<ide> import java.util.Map.Entry;
<ide>
<ide> @Override
<ide> public void doGet(HttpServletRequest request, HttpServletResponse response) {
<del> System.err.println("Still here");
<del> Enumeration<String> them = getServletConfig().getInitParameterNames();
<del> while (them.hasMoreElements()) {
<del> String it = them.nextElement();
<del> System.err.println(it + "=" + getServletConfig().getInitParameter(it));
<del> }
<ide>
<ide> response.setCharacterEncoding("UTF-8");
<ide> try { |
|
JavaScript | mit | 78f446dc043b9c934258251a2134d1eb89fd7935 | 0 | emyjacob/Emy-JS | /********************************************************
* Author: Jacob Nelson *
* Email Id: [email protected] *
* Blog: http://jnelson.in *
* Help: http://javascript.jnelson.in/category/emy-js *
********************************************************/
Array.prototype.sizeOf = function(){ return this.length; }
Array.prototype.min = function(){ return Math.min.apply({},this) }
Array.prototype.max = function(){ return Math.max.apply({},this) }
Array.prototype.sum = function(){
for(var i=0,total=0;i<this.length;total+=this[i++]);
return total;
}
Array.prototype.product = function(){
for(var i=0,prod=1;i<this.length;prod*=this[i++]);
return prod;
}
Array.prototype.average = function(){ return this.sum() / this.length; }
Array.prototype.avg = function(){ return this.average(); }
Array.prototype.shuffle = function(){
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
}
Array.prototype.rsort = function(){ return this.sort().reverse(); }
Array.prototype.first = function(){ return this[0]; }
Array.prototype.last = function(){ return this[this.length-1]; }
Array.prototype.end = function(){ return this.last(); }
Array.prototype.clear = function(){ this.length = 0; }
Array.prototype.empty = function(){ this.clear(); }
Array.prototype.search = function(obj){ return (this.indexOf(obj) != -1) ? this.indexOf(obj): -1; }
Array.prototype.find = function(obj){return this.search(obj);}
Array.prototype.findAll = function(obj){
var match_index = new Array();
for(i=0;i<this.sizeOf();i++){
if(this[i] === obj)
match_index.push(i);
}
return match_index;
}
Array.prototype.present = function(obj){return (this.indexOf(obj) != -1);}
Array.prototype.compare = function(array2){
if(this.sizeOf() != array2.sizeOf(array2))
return false;
for(i=0;i<this.length;i++){
if(this[i] !== array2[i])
return false;
}
return true;
}
Array.prototype.equal = function(array2){return this.compare(array2);}
Array.prototype.unique = function(){
var uniq_array = new Array();
for(i=0;i<this.sizeOf();i++){
if(uniq_array.search(this[i]) == -1)
uniq_array.push(this[i])
}
return uniq_array;
}
Array.prototype.diff = function(array2){
var diff_array = new Array();
for(i=0;i<this.length;i++){
if(!array2.present(this[i]))
diff_array.push(this[i]);
}
return diff_array;
}
Array.prototype.from = function(index, length){
if(index > this.length)
return -1;
else{
if(typeof length == 'undefined') length = this.length;
length = Math.abs(length)+index;
return this.slice(index, length);
}
}
Array.prototype.flatten = function(){
var flattened = this.reduce(function(a,b) {
return a.concat(b);
});
return flattened;
}
Array.prototype.restOf = function(){ return this.exclude(Array.prototype.slice.call(arguments)) }
Array.prototype.omit = function(){ return this.exclude(Array.prototype.slice.call(arguments)) }
Array.prototype.without = function(){ return this.exclude(Array.prototype.slice.call(arguments)) }
Array.prototype.exclude = function(){
var exclude_elements = Array.prototype.slice.call(arguments);
exclude_elements = exclude_elements.flatten();
var counter = 0;
while(counter<exclude_elements.length){
var ee_index = -1;
ee_index = this.search(exclude_elements[counter]);
if(ee_index == -1)
counter++;
else
this.splice(ee_index, 1);
}
return this;
}
Object.prototype.range = function(from, to, step){
if(typeof from != typeof to) return -1;
if(typeof step == "undefined") step = 1;
step = Math.abs(step);
var range_array = new Array();
if(typeof from == 'number'){
if(from > to){
for(i=from;i>=to;i-=step)
range_array.push(i);
}
else{
for(i=from;i<=to;i+=step)
range_array.push(i);
}
}
else if(typeof from == 'string'){
var lower = /[a-z]/;
var upper = /[A-Z]/;
fromAscCode = from.charCodeAt(0);
toAscCode = to.charCodeAt(0);
if((from.match(lower) && to.match(lower)) || (from.match(upper) && to.match(upper))){
if(fromAscCode < toAscCode){
for(i=fromAscCode;i<=toAscCode;i++)
range_array.push(String.fromCharCode(i));
}
else{
for(i=fromAscCode;i>=toAscCode;i--)
range_array.push(String.fromCharCode(i));
}
}
else
return -1;
}
return range_array;
}
Array.prototype.fill = function(fillWith, startIndex, num){
var fillArray = new Array();
fillArray = this;
count = fillArray.sizeOf();
if(typeof fillWith == 'undefined') return -1;
if(typeof startIndex == 'undefined') startIndex = 0;
else if(startIndex > count)startIndex = count;
if(typeof num == 'undefined') return -1;
for(i=startIndex;i<(startIndex+num);i++){
fillArray[i] = fillWith;
}
return fillArray;
}
Array.prototype.add = function(array2){
var added = new Array();
iterate_count = this.sizeOf();
if(array2.sizeOf() > iterate_count){
iterate_count = array2.sizeOf();
this.fill(0, this.sizeOf(), iterate_count) ;
}
else
array2.fill(0, array2.sizeOf(), iterate_count);
for(i=0;i<iterate_count;i++){
added.push(this[i]+array2[i]);
}
return added;
}
Array.prototype.plus = function(array2){ return this.add(array2); }
Array.prototype.subtract = function(array2){
var subtracted = new Array();
iterate_count = this.sizeOf();
if(array2.sizeOf() > iterate_count){
iterate_count = array2.sizeOf();
this.fill(0, this.sizeOf(), iterate_count) ;
}
else
array2.fill(0, array2.sizeOf(), iterate_count);
for(i=0;i<iterate_count;i++){
subtracted.push(this[i]-array2[i]);
}
return subtracted;
}
Array.prototype.minus = function(array2){ return this.subtract(array2); }
Array.prototype.negate = function(){
var b = new Array(0);
return b.minus(this);
} | emy.js | /************************************************
* Author: Jacob Nelson *
* Email Id: [email protected] *
* Blog: http://jnelson.in *
************************************************/
Array.prototype.sizeOf = function(){ return this.length; }
Array.prototype.min = function(){ return Math.min.apply({},this) }
Array.prototype.max = function(){ return Math.max.apply({},this) }
Array.prototype.sum = function(){
for(var i=0,total=0;i<this.length;total+=this[i++]);
return total;
}
Array.prototype.product = function(){
for(var i=0,prod=1;i<this.length;prod*=this[i++]);
return prod;
}
Array.prototype.average = function(){ return this.sum() / this.length; }
Array.prototype.shuffle = function(){
for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
}
Array.prototype.rsort = function(){ return this.sort().reverse(); }
Array.prototype.first = function(){ return this[0]; }
Array.prototype.last = function(){ return this[this.length-1]; }
Array.prototype.end = function(){ return this.last(); }
Array.prototype.clear = function(){ this.length = 0; }
Array.prototype.empty = function(){ this.clear(); }
Array.prototype.search = function(obj){ return (this.indexOf(obj) != -1) ? this.indexOf(obj): -1; }
Array.prototype.find = function(obj){return this.search(obj);}
Array.prototype.findAll = function(obj){
var match_index = new Array();
for(i=0;i<this.sizeOf();i++){
if(this[i] === obj)
match_index.push(i);
}
return match_index;
}
Array.prototype.present = function(obj){return (this.indexOf(obj) != -1);}
Array.prototype.compare = function(array2){
if(this.sizeOf() != array2.sizeOf(array2))
return false;
for(i=0;i<this.length;i++){
if(this[i] !== array2[i])
return false;
}
return true;
}
Array.prototype.unique = function(){
var uniq_array = new Array();
for(i=0;i<this.sizeOf();i++){
if(uniq_array.search(this[i]) == -1)
uniq_array.push(this[i])
}
return uniq_array;
}
Array.prototype.diff = function(array2){
var diff_array = new Array();
for(i=0;i<this.length;i++){
if(!array2.present(this[i]))
diff_array.push(this[i]);
}
return diff_array;
}
Array.prototype.from = function(index, length){
if(index > this.length)
return -1;
else{
if(typeof length == 'undefined') length = this.length;
length = Math.abs(length)+index;
return this.slice(index, length);
}
}
Array.prototype.flatten = function(){
var flattened = this.reduce(function(a,b) {
return a.concat(b);
});
return flattened;
}
Array.prototype.restOf = function(){ return this.exclude(Array.prototype.slice.call(arguments)) }
Array.prototype.omit = function(){ return this.exclude(Array.prototype.slice.call(arguments)) }
Array.prototype.without = function(){ return this.exclude(Array.prototype.slice.call(arguments)) }
Array.prototype.exclude = function(){
var exclude_elements = Array.prototype.slice.call(arguments);
exclude_elements = exclude_elements.flatten();
var counter = 0;
while(counter<exclude_elements.length){
var ee_index = -1;
ee_index = this.search(exclude_elements[counter]);
if(ee_index == -1)
counter++;
else
this.splice(ee_index, 1);
}
return this;
}
Object.prototype.range = function(from, to, step){
if(typeof from != typeof to) return -1;
if(typeof step == "undefined") step = 1;
step = Math.abs(step);
var range_array = new Array();
if(typeof from == 'number'){
if(from > to){
for(i=from;i>=to;i-=step)
range_array.push(i);
}
else{
for(i=from;i<=to;i+=step)
range_array.push(i);
}
}
else if(typeof from == 'string'){
var lower = /[a-z]/;
var upper = /[A-Z]/;
fromAscCode = from.charCodeAt(0);
toAscCode = to.charCodeAt(0);
if((from.match(lower) && to.match(lower)) || (from.match(upper) && to.match(upper))){
if(fromAscCode < toAscCode){
for(i=fromAscCode;i<=toAscCode;i++)
range_array.push(String.fromCharCode(i));
}
else{
for(i=fromAscCode;i>=toAscCode;i--)
range_array.push(String.fromCharCode(i));
}
}
else
return -1;
}
return range_array;
} | Emy.js Version 0.1.3
Adding new functionalities fill(), add(), plus()[alias of add()], subtract(), minus()[alias of subtract], negate()
| emy.js | Emy.js Version 0.1.3 Adding new functionalities fill(), add(), plus()[alias of add()], subtract(), minus()[alias of subtract], negate() | <ide><path>my.js
<del>/************************************************
<del>* Author: Jacob Nelson *
<del>* Email Id: [email protected] *
<del>* Blog: http://jnelson.in *
<del>************************************************/
<add>/********************************************************
<add>* Author: Jacob Nelson *
<add>* Email Id: [email protected] *
<add>* Blog: http://jnelson.in *
<add>* Help: http://javascript.jnelson.in/category/emy-js *
<add>********************************************************/
<ide> Array.prototype.sizeOf = function(){ return this.length; }
<ide> Array.prototype.min = function(){ return Math.min.apply({},this) }
<ide> Array.prototype.max = function(){ return Math.max.apply({},this) }
<ide> return prod;
<ide> }
<ide> Array.prototype.average = function(){ return this.sum() / this.length; }
<add>Array.prototype.avg = function(){ return this.average(); }
<ide> Array.prototype.shuffle = function(){
<ide> for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
<ide> return this;
<ide> }
<ide> return true;
<ide> }
<add>Array.prototype.equal = function(array2){return this.compare(array2);}
<ide> Array.prototype.unique = function(){
<ide> var uniq_array = new Array();
<ide> for(i=0;i<this.sizeOf();i++){
<ide> var flattened = this.reduce(function(a,b) {
<ide> return a.concat(b);
<ide> });
<add>
<ide> return flattened;
<ide> }
<ide> Array.prototype.restOf = function(){ return this.exclude(Array.prototype.slice.call(arguments)) }
<ide> }
<ide> return range_array;
<ide> }
<add>Array.prototype.fill = function(fillWith, startIndex, num){
<add> var fillArray = new Array();
<add> fillArray = this;
<add> count = fillArray.sizeOf();
<add> if(typeof fillWith == 'undefined') return -1;
<add> if(typeof startIndex == 'undefined') startIndex = 0;
<add> else if(startIndex > count)startIndex = count;
<add> if(typeof num == 'undefined') return -1;
<add>
<add> for(i=startIndex;i<(startIndex+num);i++){
<add> fillArray[i] = fillWith;
<add> }
<add> return fillArray;
<add>}
<add>Array.prototype.add = function(array2){
<add> var added = new Array();
<add> iterate_count = this.sizeOf();
<add> if(array2.sizeOf() > iterate_count){
<add> iterate_count = array2.sizeOf();
<add> this.fill(0, this.sizeOf(), iterate_count) ;
<add> }
<add> else
<add> array2.fill(0, array2.sizeOf(), iterate_count);
<add> for(i=0;i<iterate_count;i++){
<add> added.push(this[i]+array2[i]);
<add> }
<add> return added;
<add>}
<add>Array.prototype.plus = function(array2){ return this.add(array2); }
<add>Array.prototype.subtract = function(array2){
<add> var subtracted = new Array();
<add> iterate_count = this.sizeOf();
<add> if(array2.sizeOf() > iterate_count){
<add> iterate_count = array2.sizeOf();
<add> this.fill(0, this.sizeOf(), iterate_count) ;
<add> }
<add> else
<add> array2.fill(0, array2.sizeOf(), iterate_count);
<add> for(i=0;i<iterate_count;i++){
<add> subtracted.push(this[i]-array2[i]);
<add> }
<add> return subtracted;
<add>}
<add>Array.prototype.minus = function(array2){ return this.subtract(array2); }
<add>Array.prototype.negate = function(){
<add> var b = new Array(0);
<add> return b.minus(this);
<add>} |
|
Java | mit | a43caaa55214f84ebf631df757b026e3cb345ee4 | 0 | sake/bouncycastle-java | package org.bouncycastle.crypto.encodings;
import java.math.BigInteger;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RSAKeyParameters;
/**
* ISO 9796-1 padding. Note in the light of recent results you should
* only use this with RSA (rather than the "simpler" Rabin keys) and you
* should never use it with anything other than a hash (ie. even if the
* message is small don't sign the message, sign it's hash) or some "random"
* value. See your favorite search engine for details.
*/
public class ISO9796d1Encoding
implements AsymmetricBlockCipher
{
private static final BigInteger SIXTEEN = BigInteger.valueOf(16L);
private static final BigInteger SIX = BigInteger.valueOf(6L);
private static byte[] shadows = { 0xe, 0x3, 0x5, 0x8, 0x9, 0x4, 0x2, 0xf,
0x0, 0xd, 0xb, 0x6, 0x7, 0xa, 0xc, 0x1 };
private static byte[] inverse = { 0x8, 0xf, 0x6, 0x1, 0x5, 0x2, 0xb, 0xc,
0x3, 0x4, 0xd, 0xa, 0xe, 0x9, 0x0, 0x7 };
private AsymmetricBlockCipher engine;
private boolean forEncryption;
private int bitSize;
private int padBits = 0;
private BigInteger modulus;
public ISO9796d1Encoding(
AsymmetricBlockCipher cipher)
{
this.engine = cipher;
}
public AsymmetricBlockCipher getUnderlyingCipher()
{
return engine;
}
public void init(
boolean forEncryption,
CipherParameters param)
{
RSAKeyParameters kParam = null;
if (param instanceof ParametersWithRandom)
{
ParametersWithRandom rParam = (ParametersWithRandom)param;
kParam = (RSAKeyParameters)rParam.getParameters();
}
else
{
kParam = (RSAKeyParameters)param;
}
engine.init(forEncryption, param);
modulus = kParam.getModulus();
bitSize = modulus.bitLength();
this.forEncryption = forEncryption;
}
/**
* return the input block size. The largest message we can process
* is (key_size_in_bits + 3)/16, which in our world comes to
* key_size_in_bytes / 2.
*/
public int getInputBlockSize()
{
int baseBlockSize = engine.getInputBlockSize();
if (forEncryption)
{
return (baseBlockSize + 1) / 2;
}
else
{
return baseBlockSize;
}
}
/**
* return the maximum possible size for the output.
*/
public int getOutputBlockSize()
{
int baseBlockSize = engine.getOutputBlockSize();
if (forEncryption)
{
return baseBlockSize;
}
else
{
return (baseBlockSize + 1) / 2;
}
}
/**
* set the number of bits in the next message to be treated as
* pad bits.
*/
public void setPadBits(
int padBits)
{
if (padBits > 7)
{
throw new IllegalArgumentException("padBits > 7");
}
this.padBits = padBits;
}
/**
* retrieve the number of pad bits in the last decoded message.
*/
public int getPadBits()
{
return padBits;
}
public byte[] processBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
if (forEncryption)
{
return encodeBlock(in, inOff, inLen);
}
else
{
return decodeBlock(in, inOff, inLen);
}
}
private byte[] encodeBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
byte[] block = new byte[(bitSize + 7) / 8];
int r = padBits + 1;
int z = inLen;
int t = (bitSize + 13) / 16;
for (int i = 0; i < t; i += z)
{
if (i > t - z)
{
System.arraycopy(in, inOff + inLen - (t - i),
block, block.length - t, t - i);
}
else
{
System.arraycopy(in, inOff, block, block.length - (i + z), z);
}
}
for (int i = block.length - 2 * t; i != block.length; i += 2)
{
byte val = block[block.length - t + i / 2];
block[i] = (byte)((shadows[(val & 0xff) >>> 4] << 4)
| shadows[val & 0x0f]);
block[i + 1] = val;
}
block[block.length - 2 * z] ^= r;
block[block.length - 1] = (byte)((block[block.length - 1] << 4) | 0x06);
int maxBit = (8 - (bitSize - 1) % 8);
int offSet = 0;
if (maxBit != 8)
{
block[0] &= 0xff >>> maxBit;
block[0] |= 0x80 >>> maxBit;
}
else
{
block[0] = 0x00;
block[1] |= 0x80;
offSet = 1;
}
return engine.processBlock(block, offSet, block.length - offSet);
}
/**
* @exception InvalidCipherTextException if the decrypted block is not a valid ISO 9796 bit string
*/
private byte[] decodeBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
byte[] block = engine.processBlock(in, inOff, inLen);
int r = 1;
int t = (bitSize + 13) / 16;
BigInteger iS = new BigInteger(1, block);
BigInteger iR;
if (iS.mod(SIXTEEN).equals(SIX))
{
iR = iS;
}
else if ((modulus.subtract(iS)).mod(SIXTEEN).equals(SIX))
{
iR = modulus.subtract(iS);
}
else
{
throw new InvalidCipherTextException("resulting integer iS or (modulus - iS) is not congruent to 6 mod 16");
}
block = convertOutputDecryptOnly(iR);
if ((block[block.length - 1] & 0x0f) != 0x6 )
{
throw new InvalidCipherTextException("invalid forcing byte in block");
}
block[block.length - 1] = (byte)(((block[block.length - 1] & 0xff) >>> 4) | ((inverse[(block[block.length - 2] & 0xff) >> 4]) << 4));
block[0] = (byte)((shadows[(block[1] & 0xff) >>> 4] << 4)
| shadows[block[1] & 0x0f]);
boolean boundaryFound = false;
int boundary = 0;
for (int i = block.length - 1; i >= block.length - 2 * t; i -= 2)
{
int val = ((shadows[(block[i] & 0xff) >>> 4] << 4)
| shadows[block[i] & 0x0f]);
if (((block[i - 1] ^ val) & 0xff) != 0)
{
if (!boundaryFound)
{
boundaryFound = true;
r = (block[i - 1] ^ val) & 0xff;
boundary = i - 1;
}
else
{
throw new InvalidCipherTextException("invalid tsums in block");
}
}
}
block[boundary] = 0;
byte[] nblock = new byte[(block.length - boundary) / 2];
for (int i = 0; i < nblock.length; i++)
{
nblock[i] = block[2 * i + boundary + 1];
}
padBits = r - 1;
return nblock;
}
private static byte[] convertOutputDecryptOnly(BigInteger result)
{
byte[] output = result.toByteArray();
if (output[0] == 0) // have ended up with an extra zero byte, copy down.
{
byte[] tmp = new byte[output.length - 1];
System.arraycopy(output, 1, tmp, 0, tmp.length);
return tmp;
}
return output;
}
}
| src/org/bouncycastle/crypto/encodings/ISO9796d1Encoding.java | package org.bouncycastle.crypto.encodings;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RSAKeyParameters;
/**
* ISO 9796-1 padding. Note in the light of recent results you should
* only use this with RSA (rather than the "simpler" Rabin keys) and you
* should never use it with anything other than a hash (ie. even if the
* message is small don't sign the message, sign it's hash) or some "random"
* value. See your favorite search engine for details.
*/
public class ISO9796d1Encoding
implements AsymmetricBlockCipher
{
private static byte[] shadows = { 0xe, 0x3, 0x5, 0x8, 0x9, 0x4, 0x2, 0xf,
0x0, 0xd, 0xb, 0x6, 0x7, 0xa, 0xc, 0x1 };
private static byte[] inverse = { 0x8, 0xf, 0x6, 0x1, 0x5, 0x2, 0xb, 0xc,
0x3, 0x4, 0xd, 0xa, 0xe, 0x9, 0x0, 0x7 };
private AsymmetricBlockCipher engine;
private boolean forEncryption;
private int bitSize;
private int padBits = 0;
public ISO9796d1Encoding(
AsymmetricBlockCipher cipher)
{
this.engine = cipher;
}
public AsymmetricBlockCipher getUnderlyingCipher()
{
return engine;
}
public void init(
boolean forEncryption,
CipherParameters param)
{
RSAKeyParameters kParam = null;
if (param instanceof ParametersWithRandom)
{
ParametersWithRandom rParam = (ParametersWithRandom)param;
kParam = (RSAKeyParameters)rParam.getParameters();
}
else
{
kParam = (RSAKeyParameters)param;
}
engine.init(forEncryption, param);
bitSize = kParam.getModulus().bitLength();
this.forEncryption = forEncryption;
}
/**
* return the input block size. The largest message we can process
* is (key_size_in_bits + 3)/16, which in our world comes to
* key_size_in_bytes / 2.
*/
public int getInputBlockSize()
{
int baseBlockSize = engine.getInputBlockSize();
if (forEncryption)
{
return (baseBlockSize + 1) / 2;
}
else
{
return baseBlockSize;
}
}
/**
* return the maximum possible size for the output.
*/
public int getOutputBlockSize()
{
int baseBlockSize = engine.getOutputBlockSize();
if (forEncryption)
{
return baseBlockSize;
}
else
{
return (baseBlockSize + 1) / 2;
}
}
/**
* set the number of bits in the next message to be treated as
* pad bits.
*/
public void setPadBits(
int padBits)
{
if (padBits > 7)
{
throw new IllegalArgumentException("padBits > 7");
}
this.padBits = padBits;
}
/**
* retrieve the number of pad bits in the last decoded message.
*/
public int getPadBits()
{
return padBits;
}
public byte[] processBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
if (forEncryption)
{
return encodeBlock(in, inOff, inLen);
}
else
{
return decodeBlock(in, inOff, inLen);
}
}
private byte[] encodeBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
byte[] block = new byte[(bitSize + 7) / 8];
int r = padBits + 1;
int z = inLen;
int t = (bitSize + 13) / 16;
for (int i = 0; i < t; i += z)
{
if (i > t - z)
{
System.arraycopy(in, inOff + inLen - (t - i),
block, block.length - t, t - i);
}
else
{
System.arraycopy(in, inOff, block, block.length - (i + z), z);
}
}
for (int i = block.length - 2 * t; i != block.length; i += 2)
{
byte val = block[block.length - t + i / 2];
block[i] = (byte)((shadows[(val & 0xff) >>> 4] << 4)
| shadows[val & 0x0f]);
block[i + 1] = val;
}
block[block.length - 2 * z] ^= r;
block[block.length - 1] = (byte)((block[block.length - 1] << 4) | 0x06);
int maxBit = (8 - (bitSize - 1) % 8);
int offSet = 0;
if (maxBit != 8)
{
block[0] &= 0xff >>> maxBit;
block[0] |= 0x80 >>> maxBit;
}
else
{
block[0] = 0x00;
block[1] |= 0x80;
offSet = 1;
}
return engine.processBlock(block, offSet, block.length - offSet);
}
/**
* @exception InvalidCipherTextException if the decrypted block is not a valid ISO 9796 bit string
*/
private byte[] decodeBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
byte[] block = engine.processBlock(in, inOff, inLen);
int r = 1;
int t = (bitSize + 13) / 16;
if ((block[block.length - 1] & 0x0f) != 0x6)
{
throw new InvalidCipherTextException("invalid forcing byte in block");
}
block[block.length - 1] = (byte)(((block[block.length - 1] & 0xff) >>> 4) | ((inverse[(block[block.length - 2] & 0xff) >> 4]) << 4));
block[0] = (byte)((shadows[(block[1] & 0xff) >>> 4] << 4)
| shadows[block[1] & 0x0f]);
boolean boundaryFound = false;
int boundary = 0;
for (int i = block.length - 1; i >= block.length - 2 * t; i -= 2)
{
int val = ((shadows[(block[i] & 0xff) >>> 4] << 4)
| shadows[block[i] & 0x0f]);
if (((block[i - 1] ^ val) & 0xff) != 0)
{
if (!boundaryFound)
{
boundaryFound = true;
r = (block[i - 1] ^ val) & 0xff;
boundary = i - 1;
}
else
{
throw new InvalidCipherTextException("invalid tsums in block");
}
}
}
block[boundary] = 0;
byte[] nblock = new byte[(block.length - boundary) / 2];
for (int i = 0; i < nblock.length; i++)
{
nblock[i] = block[2 * i + boundary + 1];
}
padBits = r - 1;
return nblock;
}
}
| BJA-280 ISO-9796-1 padding fix.
| src/org/bouncycastle/crypto/encodings/ISO9796d1Encoding.java | BJA-280 ISO-9796-1 padding fix. | <ide><path>rc/org/bouncycastle/crypto/encodings/ISO9796d1Encoding.java
<ide> package org.bouncycastle.crypto.encodings;
<add>
<add>import java.math.BigInteger;
<ide>
<ide> import org.bouncycastle.crypto.AsymmetricBlockCipher;
<ide> import org.bouncycastle.crypto.CipherParameters;
<ide> /**
<ide> * ISO 9796-1 padding. Note in the light of recent results you should
<ide> * only use this with RSA (rather than the "simpler" Rabin keys) and you
<del> * should never use it with anything other than a hash (ie. even if the
<add> * should never use it with anything other than a hash (ie. even if the
<ide> * message is small don't sign the message, sign it's hash) or some "random"
<ide> * value. See your favorite search engine for details.
<ide> */
<ide> public class ISO9796d1Encoding
<ide> implements AsymmetricBlockCipher
<ide> {
<add> private static final BigInteger SIXTEEN = BigInteger.valueOf(16L);
<add> private static final BigInteger SIX = BigInteger.valueOf(6L);
<add>
<ide> private static byte[] shadows = { 0xe, 0x3, 0x5, 0x8, 0x9, 0x4, 0x2, 0xf,
<ide> 0x0, 0xd, 0xb, 0x6, 0x7, 0xa, 0xc, 0x1 };
<ide> private static byte[] inverse = { 0x8, 0xf, 0x6, 0x1, 0x5, 0x2, 0xb, 0xc,
<ide> private boolean forEncryption;
<ide> private int bitSize;
<ide> private int padBits = 0;
<add> private BigInteger modulus;
<ide>
<ide> public ISO9796d1Encoding(
<ide> AsymmetricBlockCipher cipher)
<ide> {
<ide> this.engine = cipher;
<del> }
<add> }
<ide>
<ide> public AsymmetricBlockCipher getUnderlyingCipher()
<ide> {
<ide>
<ide> engine.init(forEncryption, param);
<ide>
<del> bitSize = kParam.getModulus().bitLength();
<add> modulus = kParam.getModulus();
<add> bitSize = modulus.bitLength();
<ide>
<ide> this.forEncryption = forEncryption;
<ide> }
<ide>
<ide> /**
<ide> * return the input block size. The largest message we can process
<del> * is (key_size_in_bits + 3)/16, which in our world comes to
<add> * is (key_size_in_bits + 3)/16, which in our world comes to
<ide> * key_size_in_bytes / 2.
<ide> */
<ide> public int getInputBlockSize()
<ide> }
<ide>
<ide> /**
<del> * set the number of bits in the next message to be treated as
<add> * set the number of bits in the next message to be treated as
<ide> * pad bits.
<ide> */
<ide> public void setPadBits(
<ide> for (int i = block.length - 2 * t; i != block.length; i += 2)
<ide> {
<ide> byte val = block[block.length - t + i / 2];
<del>
<add>
<ide> block[i] = (byte)((shadows[(val & 0xff) >>> 4] << 4)
<ide> | shadows[val & 0x0f]);
<ide> block[i + 1] = val;
<ide> int r = 1;
<ide> int t = (bitSize + 13) / 16;
<ide>
<del> if ((block[block.length - 1] & 0x0f) != 0x6)
<add> BigInteger iS = new BigInteger(1, block);
<add> BigInteger iR;
<add> if (iS.mod(SIXTEEN).equals(SIX))
<add> {
<add> iR = iS;
<add> }
<add> else if ((modulus.subtract(iS)).mod(SIXTEEN).equals(SIX))
<add> {
<add> iR = modulus.subtract(iS);
<add> }
<add> else
<add> {
<add> throw new InvalidCipherTextException("resulting integer iS or (modulus - iS) is not congruent to 6 mod 16");
<add> }
<add>
<add> block = convertOutputDecryptOnly(iR);
<add>
<add> if ((block[block.length - 1] & 0x0f) != 0x6 )
<ide> {
<ide> throw new InvalidCipherTextException("invalid forcing byte in block");
<ide> }
<ide>
<ide> boolean boundaryFound = false;
<ide> int boundary = 0;
<del>
<add>
<ide> for (int i = block.length - 1; i >= block.length - 2 * t; i -= 2)
<ide> {
<ide> int val = ((shadows[(block[i] & 0xff) >>> 4] << 4)
<ide> | shadows[block[i] & 0x0f]);
<del>
<add>
<ide> if (((block[i - 1] ^ val) & 0xff) != 0)
<ide> {
<ide> if (!boundaryFound)
<ide>
<ide> return nblock;
<ide> }
<add>
<add> private static byte[] convertOutputDecryptOnly(BigInteger result)
<add> {
<add> byte[] output = result.toByteArray();
<add> if (output[0] == 0) // have ended up with an extra zero byte, copy down.
<add> {
<add> byte[] tmp = new byte[output.length - 1];
<add> System.arraycopy(output, 1, tmp, 0, tmp.length);
<add> return tmp;
<add> }
<add> return output;
<add> }
<ide> } |
|
Java | apache-2.0 | a8048298261289faf3ae1b07870f05cca1b58193 | 0 | ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop | package it.unibz.inf.ontop.pivotalrepr.impl;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import it.unibz.inf.ontop.model.*;
import it.unibz.inf.ontop.owlrefplatform.core.basicoperations.ImmutableSubstitutionImpl;
import it.unibz.inf.ontop.owlrefplatform.core.basicoperations.Var2VarSubstitutionImpl;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.unibz.inf.ontop.pivotalrepr.*;
import static it.unibz.inf.ontop.owlrefplatform.core.basicoperations.ImmutableUnificationTools.computeMGUS;
import static it.unibz.inf.ontop.pivotalrepr.SubstitutionResults.LocalAction.DECLARE_AS_EMPTY;
import static it.unibz.inf.ontop.pivotalrepr.SubstitutionResults.LocalAction.REPLACE_BY_CHILD;
import static it.unibz.inf.ontop.pivotalrepr.impl.ConstructionNodeTools.computeNewProjectedVariables;
import static it.unibz.inf.ontop.pivotalrepr.impl.ConstructionNodeTools.extractRelevantDescendingSubstitution;
public class ConstructionNodeImpl extends QueryNodeImpl implements ConstructionNode {
/**
* TODO: find a better name
*/
private static class NewSubstitutionPair {
public final ImmutableSubstitution<ImmutableTerm> bindings;
public final ImmutableSubstitution<? extends ImmutableTerm> propagatedSubstitution;
private NewSubstitutionPair(ImmutableSubstitution<ImmutableTerm> bindings,
ImmutableSubstitution<? extends ImmutableTerm> propagatedSubstitution) {
this.bindings = bindings;
this.propagatedSubstitution = propagatedSubstitution;
}
}
private static Logger LOGGER = LoggerFactory.getLogger(ConstructionNodeImpl.class);
private static int CONVERGENCE_BOUND = 5;
private final Optional<ImmutableQueryModifiers> optionalModifiers;
private final ImmutableSet<Variable> projectedVariables;
private final ImmutableSubstitution<ImmutableTerm> substitution;
private static final String CONSTRUCTION_NODE_STR = "CONSTRUCT";
public ConstructionNodeImpl(ImmutableSet<Variable> projectedVariables, ImmutableSubstitution<ImmutableTerm> substitution,
Optional<ImmutableQueryModifiers> optionalQueryModifiers) {
this.projectedVariables = projectedVariables;
this.substitution = substitution;
this.optionalModifiers = optionalQueryModifiers;
}
/**
* Without modifiers nor substitution.
*/
public ConstructionNodeImpl(ImmutableSet<Variable> projectedVariables) {
this.projectedVariables = projectedVariables;
this.substitution = new ImmutableSubstitutionImpl<>(ImmutableMap.<Variable, ImmutableTerm>of());
this.optionalModifiers = Optional.empty();
}
@Override
public ImmutableSet<Variable> getProjectedVariables() {
return projectedVariables;
}
@Override
public ImmutableSubstitution<ImmutableTerm> getSubstitution() {
return substitution;
}
@Override
public Optional<ImmutableQueryModifiers> getOptionalModifiers() {
return optionalModifiers;
}
/**
* Immutable fields, can be shared.
*/
@Override
public ConstructionNode clone() {
return new ConstructionNodeImpl(projectedVariables, substitution, optionalModifiers);
}
@Override
public ConstructionNode acceptNodeTransformer(HomogeneousQueryNodeTransformer transformer)
throws QueryNodeTransformationException {
return transformer.transform(this);
}
@Override
public NodeTransformationProposal acceptNodeTransformer(HeterogeneousQueryNodeTransformer transformer) {
return transformer.transform(this);
}
@Override
public ImmutableSet<Variable> getVariables() {
ImmutableSet.Builder<Variable> collectedVariableBuilder = ImmutableSet.builder();
collectedVariableBuilder.addAll(projectedVariables);
ImmutableMap<Variable, ImmutableTerm> substitutionMap = substitution.getImmutableMap();
collectedVariableBuilder.addAll(substitutionMap.keySet());
for (ImmutableTerm term : substitutionMap.values()) {
if (term instanceof Variable) {
collectedVariableBuilder.add((Variable)term);
}
else if (term instanceof ImmutableFunctionalTerm) {
collectedVariableBuilder.addAll(((ImmutableFunctionalTerm)term).getVariables());
}
}
return collectedVariableBuilder.build();
}
@Override
public ImmutableSubstitution<ImmutableTerm> getDirectBindingSubstitution() {
if (substitution.isEmpty())
return substitution;
// Non-final
ImmutableSubstitution<ImmutableTerm> previousSubstitution;
// Non-final
ImmutableSubstitution<ImmutableTerm> newSubstitution = substitution;
int i = 0;
do {
previousSubstitution = newSubstitution;
newSubstitution = newSubstitution.composeWith(substitution);
i++;
} while ((i < CONVERGENCE_BOUND) && (!previousSubstitution.equals(newSubstitution)));
if (i == CONVERGENCE_BOUND) {
LOGGER.warn(substitution + " has not converged after " + CONVERGENCE_BOUND + " recursions over itself");
}
return newSubstitution;
}
/**
* Creates a new ConstructionNode with a new substitution.
* This substitution is obtained by composition and then cleaned (only defines the projected variables)
*
* Stops the propagation.
*/
@Override
public SubstitutionResults<ConstructionNode> applyAscendingSubstitution(
ImmutableSubstitution<? extends ImmutableTerm> substitutionToApply,
QueryNode childNode, IntermediateQuery query) {
ImmutableSubstitution<ImmutableTerm> localSubstitution = getSubstitution();
ImmutableSet<Variable> boundVariables = localSubstitution.getImmutableMap().keySet();
if (substitutionToApply.getImmutableMap().keySet().stream().anyMatch(boundVariables::contains)) {
throw new IllegalArgumentException("An ascending substitution MUST NOT include variables bound by " +
"the substitution of the current construction node");
}
ImmutableSubstitution<ImmutableTerm> compositeSubstitution = substitutionToApply.composeWith(localSubstitution);
/**
* Cleans the composite substitution by removing non-projected variables
*/
ImmutableMap.Builder<Variable, ImmutableTerm> newSubstitutionMapBuilder = ImmutableMap.builder();
compositeSubstitution.getImmutableMap().entrySet().stream()
.filter(e -> projectedVariables.contains(e.getKey()))
.forEach(newSubstitutionMapBuilder::put);
ImmutableSubstitutionImpl<ImmutableTerm> newSubstitution = new ImmutableSubstitutionImpl<>(
newSubstitutionMapBuilder.build());
ConstructionNode newConstructionNode = new ConstructionNodeImpl(projectedVariables,
newSubstitution, getOptionalModifiers());
/**
* Stops to propagate the substitution
*/
return new SubstitutionResultsImpl<>(newConstructionNode);
}
/**
* TODO: explain
*/
@Override
public SubstitutionResults<ConstructionNode> applyDescendingSubstitution(
ImmutableSubstitution<? extends ImmutableTerm> descendingSubstitution, IntermediateQuery query) {
ImmutableSubstitution<ImmutableTerm> relevantSubstitution = extractRelevantDescendingSubstitution(
descendingSubstitution, projectedVariables);
ImmutableSet<Variable> newProjectedVariables = computeNewProjectedVariables(relevantSubstitution,
getProjectedVariables());
/**
* TODO: avoid using an exception
*/
NewSubstitutionPair newSubstitutions;
try {
newSubstitutions = traverseConstructionNode(relevantSubstitution, substitution, projectedVariables,
newProjectedVariables);
} catch (QueryNodeSubstitutionException e) {
return new SubstitutionResultsImpl<>(DECLARE_AS_EMPTY);
}
ImmutableSubstitution<? extends ImmutableTerm> substitutionToPropagate = newSubstitutions.propagatedSubstitution;
Optional<ImmutableQueryModifiers> newOptionalModifiers = updateOptionalModifiers(optionalModifiers,
descendingSubstitution, substitutionToPropagate);
/**
* The construction node is not be needed anymore
*
* Currently, the root construction node is still required.
*/
if (newSubstitutions.bindings.isEmpty() && !newOptionalModifiers.isPresent()
&& query.getRootConstructionNode() != this) {
return new SubstitutionResultsImpl<>(REPLACE_BY_CHILD, Optional.of(substitutionToPropagate));
}
/**
* New construction node
*/
else {
ConstructionNode newConstructionNode = new ConstructionNodeImpl(newProjectedVariables,
newSubstitutions.bindings, newOptionalModifiers);
return new SubstitutionResultsImpl<>(newConstructionNode, substitutionToPropagate);
}
}
@Override
public boolean isSyntacticallyEquivalentTo(QueryNode node) {
return Optional.of(node)
.filter(n -> n instanceof ConstructionNode)
.map(n -> (ConstructionNode) n)
.filter(n -> n.getProjectedVariables().equals(projectedVariables))
.filter(n -> n.getSubstitution().equals(substitution))
.isPresent();
}
@Override
public void acceptVisitor(QueryNodeVisitor visitor) {
visitor.visit(this);
}
@Override
public String toString() {
// TODO: display the query modifiers
return CONSTRUCTION_NODE_STR + " " + projectedVariables + " " + "[" + substitution + "]" ;
}
/**
*
* TODO: explain
*
*/
private NewSubstitutionPair traverseConstructionNode(
ImmutableSubstitution<? extends ImmutableTerm> tau,
ImmutableSubstitution<? extends ImmutableTerm> formerTheta,
ImmutableSet<Variable> formerV, ImmutableSet<Variable> newV) throws QueryNodeSubstitutionException {
Var2VarSubstitution tauR = tau.getVar2VarFragment();
// Non-variable term
ImmutableSubstitution<NonVariableTerm> tauO = extractTauO(tau);
Var2VarSubstitution tauEq = extractTauEq(tauR);
ImmutableSubstitution<? extends ImmutableTerm> tauC = tauO.unionHeterogeneous(tauEq)
.orElseThrow(() -> new IllegalStateException("Bug: dom(tauG) must be disjoint with dom(tauEq)"));
ImmutableSubstitution<ImmutableTerm> eta = computeMGUS(formerTheta, tauC)
.orElseThrow(() -> new QueryNodeSubstitutionException("The descending substitution " + tau
+ " is incompatible with " + this));
ImmutableSubstitution<ImmutableTerm> etaB = extractEtaB(eta, formerV, newV, tauC);
ImmutableSubstitution<ImmutableTerm> newTheta = tauR.applyToSubstitution(etaB)
.orElseThrow(() -> new IllegalStateException("Bug: tauR does not rename etaB safely as excepted"));
ImmutableSubstitution<? extends ImmutableTerm> delta = computeDelta(formerTheta, newTheta, eta, tauR, tauEq);
return new NewSubstitutionPair(newTheta, delta);
}
private static ImmutableSubstitution<NonVariableTerm> extractTauO(ImmutableSubstitution<? extends ImmutableTerm> tau) {
ImmutableMap<Variable, NonVariableTerm> newMap = tau.getImmutableMap().entrySet().stream()
.filter(e -> e.getValue() instanceof NonVariableTerm)
.map(e -> (Map.Entry<Variable, NonVariableTerm>) e)
.collect(ImmutableCollectors.toMap());
return new ImmutableSubstitutionImpl<>(newMap);
}
/**
* TODO: explain
*/
private static Var2VarSubstitution extractTauEq(Var2VarSubstitution tauR) {
int domainVariableCount = tauR.getDomain().size();
if (domainVariableCount <= 1) {
return new Var2VarSubstitutionImpl(ImmutableMap.of());
}
ImmutableMultimap<Variable, Variable> inverseMultimap = tauR.getImmutableMap().entrySet().stream()
// Inverse
.map(e -> (Map.Entry<Variable, Variable>) new AbstractMap.SimpleImmutableEntry<>(e.getValue(), e.getKey()))
.collect(ImmutableCollectors.toMultimap());
ImmutableMap<Variable, Variable> newMap = inverseMultimap.asMap().values().stream()
// TODO: explain
.filter(vars -> vars.size() >= 1)
//
.flatMap(vars -> {
List<Variable> sortedVariables = vars.stream()
.sorted()
.collect(Collectors.toList());
Variable largerVariable = sortedVariables.get(sortedVariables.size() - 1);
return sortedVariables.stream()
.limit(sortedVariables.size() - 1)
.map(v -> (Map.Entry<Variable, Variable>) new AbstractMap.SimpleEntry<>(v, largerVariable));
})
.collect(ImmutableCollectors.toMap());
return new Var2VarSubstitutionImpl(newMap);
}
private static ImmutableSubstitution<ImmutableTerm> extractEtaB(ImmutableSubstitution<ImmutableTerm> eta,
ImmutableSet<Variable> formerV,
ImmutableSet<Variable> newV,
ImmutableSubstitution<? extends ImmutableTerm> tauC) {
ImmutableSet<Variable> tauCDomain = tauC.getDomain();
ImmutableMap<Variable, ImmutableTerm> newMap = eta.getImmutableMap().entrySet().stream()
.filter(e -> formerV.contains(e.getKey()) || newV.contains(e.getKey()))
.filter(e -> !tauCDomain.contains(e.getKey()))
.collect(ImmutableCollectors.toMap());
return new ImmutableSubstitutionImpl<>(newMap);
}
private static ImmutableSubstitution<? extends ImmutableTerm> computeDelta(
ImmutableSubstitution<? extends ImmutableTerm> formerTheta,
ImmutableSubstitution<? extends ImmutableTerm> newTheta,
ImmutableSubstitution<ImmutableTerm> eta, Var2VarSubstitution tauR,
Var2VarSubstitution tauEq) {
ImmutableSet<Map.Entry<Variable, Variable>> tauEqEntries = tauEq.getImmutableMap().entrySet();
ImmutableSet<Variable> formerThetaDomain = formerTheta.getDomain();
ImmutableMap<Variable, ImmutableTerm> newMap = Stream.concat(
eta.getImmutableMap().entrySet().stream(),
tauR.getImmutableMap().entrySet().stream())
.filter(e -> !tauEqEntries.contains(e))
.filter(e -> !formerThetaDomain.contains(e.getKey()))
.map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), newTheta.apply(e.getValue())))
.distinct()
.collect(ImmutableCollectors.toMap());
return new ImmutableSubstitutionImpl<>(newMap);
}
/**
* TODO: explain
*/
private static Optional<ImmutableQueryModifiers> updateOptionalModifiers(
Optional<ImmutableQueryModifiers> optionalModifiers,
ImmutableSubstitution<? extends ImmutableTerm> substitution1,
ImmutableSubstitution<? extends ImmutableTerm> substitution2) {
if (!optionalModifiers.isPresent()) {
return Optional.empty();
}
ImmutableQueryModifiers previousModifiers = optionalModifiers.get();
ImmutableList.Builder<OrderCondition> conditionBuilder = ImmutableList.builder();
for (OrderCondition condition : previousModifiers.getSortConditions()) {
ImmutableTerm newTerm = substitution2.apply(substitution1.apply(condition.getVariable()));
/**
* If after applying the substitution the term is still a variable,
* "updates" the OrderCondition.
*
* Otherwise, forgets it.
*/
if (newTerm instanceof Variable) {
conditionBuilder.add(condition.newVariable((Variable) newTerm));
}
}
return previousModifiers.newSortConditions(conditionBuilder.build());
}
}
| reformulation-core/src/main/java/it/unibz/inf/ontop/pivotalrepr/impl/ConstructionNodeImpl.java | package it.unibz.inf.ontop.pivotalrepr.impl;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import it.unibz.inf.ontop.model.*;
import it.unibz.inf.ontop.owlrefplatform.core.basicoperations.ImmutableSubstitutionImpl;
import it.unibz.inf.ontop.owlrefplatform.core.basicoperations.Var2VarSubstitutionImpl;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.unibz.inf.ontop.pivotalrepr.*;
import static it.unibz.inf.ontop.owlrefplatform.core.basicoperations.ImmutableUnificationTools.computeMGUS;
import static it.unibz.inf.ontop.pivotalrepr.SubstitutionResults.LocalAction.DECLARE_AS_EMPTY;
import static it.unibz.inf.ontop.pivotalrepr.SubstitutionResults.LocalAction.REPLACE_BY_CHILD;
import static it.unibz.inf.ontop.pivotalrepr.impl.ConstructionNodeTools.computeNewProjectedVariables;
import static it.unibz.inf.ontop.pivotalrepr.impl.ConstructionNodeTools.extractRelevantDescendingSubstitution;
public class ConstructionNodeImpl extends QueryNodeImpl implements ConstructionNode {
/**
* TODO: find a better name
*/
private static class NewSubstitutionPair {
public final ImmutableSubstitution<ImmutableTerm> bindings;
public final ImmutableSubstitution<? extends ImmutableTerm> propagatedSubstitution;
private NewSubstitutionPair(ImmutableSubstitution<ImmutableTerm> bindings,
ImmutableSubstitution<? extends ImmutableTerm> propagatedSubstitution) {
this.bindings = bindings;
this.propagatedSubstitution = propagatedSubstitution;
}
}
private static Logger LOGGER = LoggerFactory.getLogger(ConstructionNodeImpl.class);
private static int CONVERGENCE_BOUND = 5;
private final Optional<ImmutableQueryModifiers> optionalModifiers;
private final ImmutableSet<Variable> projectedVariables;
private final ImmutableSubstitution<ImmutableTerm> substitution;
private static final String CONSTRUCTION_NODE_STR = "CONSTRUCT";
public ConstructionNodeImpl(ImmutableSet<Variable> projectedVariables, ImmutableSubstitution<ImmutableTerm> substitution,
Optional<ImmutableQueryModifiers> optionalQueryModifiers) {
this.projectedVariables = projectedVariables;
this.substitution = substitution;
this.optionalModifiers = optionalQueryModifiers;
}
/**
* Without modifiers nor substitution.
*/
public ConstructionNodeImpl(ImmutableSet<Variable> projectedVariables) {
this.projectedVariables = projectedVariables;
this.substitution = new ImmutableSubstitutionImpl<>(ImmutableMap.<Variable, ImmutableTerm>of());
this.optionalModifiers = Optional.empty();
}
@Override
public ImmutableSet<Variable> getProjectedVariables() {
return projectedVariables;
}
@Override
public ImmutableSubstitution<ImmutableTerm> getSubstitution() {
return substitution;
}
@Override
public Optional<ImmutableQueryModifiers> getOptionalModifiers() {
return optionalModifiers;
}
/**
* Immutable fields, can be shared.
*/
@Override
public ConstructionNode clone() {
return new ConstructionNodeImpl(projectedVariables, substitution, optionalModifiers);
}
@Override
public ConstructionNode acceptNodeTransformer(HomogeneousQueryNodeTransformer transformer)
throws QueryNodeTransformationException {
return transformer.transform(this);
}
@Override
public NodeTransformationProposal acceptNodeTransformer(HeterogeneousQueryNodeTransformer transformer) {
return transformer.transform(this);
}
@Override
public ImmutableSet<Variable> getVariables() {
ImmutableSet.Builder<Variable> collectedVariableBuilder = ImmutableSet.builder();
collectedVariableBuilder.addAll(projectedVariables);
ImmutableMap<Variable, ImmutableTerm> substitutionMap = substitution.getImmutableMap();
collectedVariableBuilder.addAll(substitutionMap.keySet());
for (ImmutableTerm term : substitutionMap.values()) {
if (term instanceof Variable) {
collectedVariableBuilder.add((Variable)term);
}
else if (term instanceof ImmutableFunctionalTerm) {
collectedVariableBuilder.addAll(((ImmutableFunctionalTerm)term).getVariables());
}
}
return collectedVariableBuilder.build();
}
@Override
public ImmutableSubstitution<ImmutableTerm> getDirectBindingSubstitution() {
if (substitution.isEmpty())
return substitution;
// Non-final
ImmutableSubstitution<ImmutableTerm> previousSubstitution;
// Non-final
ImmutableSubstitution<ImmutableTerm> newSubstitution = substitution;
int i = 0;
do {
previousSubstitution = newSubstitution;
newSubstitution = newSubstitution.composeWith(substitution);
i++;
} while ((i < CONVERGENCE_BOUND) && (!previousSubstitution.equals(newSubstitution)));
if (i == CONVERGENCE_BOUND) {
LOGGER.warn(substitution + " has not converged after " + CONVERGENCE_BOUND + " recursions over itself");
}
return newSubstitution;
}
/**
* Creates a new ConstructionNode with a new substitution.
* This substitution is obtained by composition and then cleaned (only defines the projected variables)
*
* Stops the propagation.
*/
@Override
public SubstitutionResults<ConstructionNode> applyAscendingSubstitution(
ImmutableSubstitution<? extends ImmutableTerm> substitutionToApply,
QueryNode childNode, IntermediateQuery query) {
ImmutableSubstitution<ImmutableTerm> localSubstitution = getSubstitution();
ImmutableSet<Variable> boundVariables = localSubstitution.getImmutableMap().keySet();
if (substitutionToApply.getImmutableMap().keySet().stream().anyMatch(boundVariables::contains)) {
throw new IllegalArgumentException("An ascending substitution MUST NOT include variables bound by " +
"the substitution of the current construction node");
}
ImmutableSubstitution<ImmutableTerm> compositeSubstitution = substitutionToApply.composeWith(localSubstitution);
/**
* Cleans the composite substitution by removing non-projected variables
*/
ImmutableMap.Builder<Variable, ImmutableTerm> newSubstitutionMapBuilder = ImmutableMap.builder();
compositeSubstitution.getImmutableMap().entrySet().stream()
.filter(e -> projectedVariables.contains(e.getKey()))
.forEach(newSubstitutionMapBuilder::put);
ImmutableSubstitutionImpl<ImmutableTerm> newSubstitution = new ImmutableSubstitutionImpl<>(
newSubstitutionMapBuilder.build());
ConstructionNode newConstructionNode = new ConstructionNodeImpl(projectedVariables,
newSubstitution, getOptionalModifiers());
/**
* Stops to propagate the substitution
*/
return new SubstitutionResultsImpl<>(newConstructionNode);
}
/**
* TODO: explain
*/
@Override
public SubstitutionResults<ConstructionNode> applyDescendingSubstitution(
ImmutableSubstitution<? extends ImmutableTerm> descendingSubstitution, IntermediateQuery query) {
ImmutableSubstitution<ImmutableTerm> relevantSubstitution = extractRelevantDescendingSubstitution(
descendingSubstitution, projectedVariables);
ImmutableSet<Variable> newProjectedVariables = computeNewProjectedVariables(relevantSubstitution,
getProjectedVariables());
/**
* TODO: avoid using an exception
*/
NewSubstitutionPair newSubstitutions;
try {
newSubstitutions = traverseConstructionNode(relevantSubstitution, substitution, projectedVariables,
newProjectedVariables);
} catch (QueryNodeSubstitutionException e) {
return new SubstitutionResultsImpl<>(DECLARE_AS_EMPTY);
}
ImmutableSubstitution<? extends ImmutableTerm> substitutionToPropagate = newSubstitutions.propagatedSubstitution;
Optional<ImmutableQueryModifiers> newOptionalModifiers = updateOptionalModifiers(optionalModifiers,
descendingSubstitution, substitutionToPropagate);
/**
* The construction node is not be needed anymore
*
* Currently, the root construction node is still required.
*/
if (newSubstitutions.bindings.isEmpty() && !newOptionalModifiers.isPresent()
&& query.getRootConstructionNode() != this) {
return new SubstitutionResultsImpl<>(REPLACE_BY_CHILD, Optional.of(substitutionToPropagate));
}
/**
* New construction node
*/
else {
ConstructionNode newConstructionNode = new ConstructionNodeImpl(newProjectedVariables,
newSubstitutions.bindings, newOptionalModifiers);
return new SubstitutionResultsImpl<>(newConstructionNode, substitutionToPropagate);
}
}
@Override
public boolean isSyntacticallyEquivalentTo(QueryNode node) {
return Optional.of(node)
.filter(n -> n instanceof ConstructionNode)
.map(n -> (ConstructionNode) n)
.filter(n -> n.getProjectedVariables().equals(projectedVariables))
.filter(n -> n.getSubstitution().equals(substitution))
.isPresent();
}
@Override
public void acceptVisitor(QueryNodeVisitor visitor) {
visitor.visit(this);
}
@Override
public String toString() {
// TODO: display the query modifiers
return CONSTRUCTION_NODE_STR + " " + projectedVariables + " " + "[" + substitution + "]" ;
}
/**
*
* TODO: explain
*
*/
private NewSubstitutionPair traverseConstructionNode(
ImmutableSubstitution<? extends ImmutableTerm> tau,
ImmutableSubstitution<? extends ImmutableTerm> formerTheta,
ImmutableSet<Variable> formerV, ImmutableSet<Variable> newV) throws QueryNodeSubstitutionException {
Var2VarSubstitution tauR = tau.getVar2VarFragment();
// Non-variable term
ImmutableSubstitution<NonVariableTerm> tauO = extractTauO(tau);
Var2VarSubstitution tauEq = extractTauEq(tauR);
ImmutableSubstitution<? extends ImmutableTerm> tauC = tauO.unionHeterogeneous(tauEq)
.orElseThrow(() -> new IllegalStateException("Bug: dom(tauG) must be disjoint with dom(tauEq)"));
ImmutableSubstitution<ImmutableTerm> eta = computeMGUS(formerTheta, tauC)
.orElseThrow(() -> new QueryNodeSubstitutionException("The descending substitution " + tau
+ " is incompatible with " + this));
ImmutableSubstitution<ImmutableTerm> etaB = extractEtaB(eta, formerV, newV, tauC);
ImmutableSubstitution<ImmutableTerm> newTheta = tauR.applyToSubstitution(etaB)
.orElseThrow(() -> new IllegalStateException("Bug: tauR does not rename etaB safely as excepted"));
ImmutableSubstitution<? extends ImmutableTerm> delta = computeDelta(formerTheta, newTheta, eta, tauR, tauEq);
return new NewSubstitutionPair(newTheta, delta);
}
private static ImmutableSubstitution<NonVariableTerm> extractTauO(ImmutableSubstitution<? extends ImmutableTerm> tau) {
ImmutableMap<Variable, NonVariableTerm> newMap = tau.getImmutableMap().entrySet().stream()
.filter(e -> e.getValue() instanceof NonVariableTerm)
.map(e -> (Map.Entry<Variable, NonVariableTerm>) e)
.collect(ImmutableCollectors.toMap());
return new ImmutableSubstitutionImpl<>(newMap);
}
/**
* TODO: explain
*/
private static Var2VarSubstitution extractTauEq(Var2VarSubstitution tauR) {
int domainVariableCount = tauR.getDomain().size();
if (domainVariableCount <= 1) {
return new Var2VarSubstitutionImpl(ImmutableMap.of());
}
ImmutableMultimap<Variable, Variable> inverseMultimap = tauR.getImmutableMap().entrySet().stream()
// Inverse
.map(e -> (Map.Entry<Variable, Variable>) new AbstractMap.SimpleImmutableEntry<>(e.getValue(), e.getKey()))
.collect(ImmutableCollectors.toMultimap());
ImmutableMap<Variable, Variable> newMap = inverseMultimap.asMap().values().stream()
// TODO: explain
.filter(vars -> vars.size() >= 1)
//
.flatMap(vars -> {
List<Variable> sortedVariables = vars.stream()
.sorted()
.collect(Collectors.toList());
Variable largerVariable = sortedVariables.get(sortedVariables.size() - 1);
return sortedVariables.stream()
.limit(sortedVariables.size() - 1)
.map(v -> (Map.Entry<Variable, Variable>) new AbstractMap.SimpleEntry<>(v, largerVariable));
})
.collect(ImmutableCollectors.toMap());
return new Var2VarSubstitutionImpl(newMap);
}
private static ImmutableSubstitution<ImmutableTerm> extractEtaB(ImmutableSubstitution<ImmutableTerm> eta,
ImmutableSet<Variable> formerV,
ImmutableSet<Variable> newV,
ImmutableSubstitution<? extends ImmutableTerm> tauC) {
ImmutableSet<Variable> tauCDomain = tauC.getDomain();
ImmutableMap<Variable, ImmutableTerm> newMap = eta.getImmutableMap().entrySet().stream()
.filter(e -> formerV.contains(e.getKey()) || newV.contains(e.getKey()))
.filter(e -> !tauCDomain.contains(e.getKey()))
.collect(ImmutableCollectors.toMap());
return new ImmutableSubstitutionImpl<>(newMap);
}
private static ImmutableSubstitution<? extends ImmutableTerm> computeDelta(
ImmutableSubstitution<? extends ImmutableTerm> formerTheta,
ImmutableSubstitution<? extends ImmutableTerm> newTheta,
ImmutableSubstitution<ImmutableTerm> eta, Var2VarSubstitution tauR,
Var2VarSubstitution tauEq) {
ImmutableSet<Map.Entry<Variable, Variable>> tauEqEntries = tauEq.getImmutableMap().entrySet();
ImmutableSet<Variable> formerThetaDomain = formerTheta.getDomain();
ImmutableMap<Variable, ImmutableTerm> newMap = Stream.concat(
eta.getImmutableMap().entrySet().stream(),
tauR.getImmutableMap().entrySet().stream())
.filter(e -> !tauEqEntries.contains(e))
.filter(e -> !formerThetaDomain.contains(e.getKey()))
.map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), newTheta.apply(e.getValue())))
.collect(ImmutableCollectors.toMap());
return new ImmutableSubstitutionImpl<>(newMap);
}
/**
* TODO: explain
*/
private static Optional<ImmutableQueryModifiers> updateOptionalModifiers(
Optional<ImmutableQueryModifiers> optionalModifiers,
ImmutableSubstitution<? extends ImmutableTerm> substitution1,
ImmutableSubstitution<? extends ImmutableTerm> substitution2) {
if (!optionalModifiers.isPresent()) {
return Optional.empty();
}
ImmutableQueryModifiers previousModifiers = optionalModifiers.get();
ImmutableList.Builder<OrderCondition> conditionBuilder = ImmutableList.builder();
for (OrderCondition condition : previousModifiers.getSortConditions()) {
ImmutableTerm newTerm = substitution2.apply(substitution1.apply(condition.getVariable()));
/**
* If after applying the substitution the term is still a variable,
* "updates" the OrderCondition.
*
* Otherwise, forgets it.
*/
if (newTerm instanceof Variable) {
conditionBuilder.add(condition.newVariable((Variable) newTerm));
}
}
return previousModifiers.newSortConditions(conditionBuilder.build());
}
}
| Bugfix: removes duplicate map entries when computing delta.
| reformulation-core/src/main/java/it/unibz/inf/ontop/pivotalrepr/impl/ConstructionNodeImpl.java | Bugfix: removes duplicate map entries when computing delta. | <ide><path>eformulation-core/src/main/java/it/unibz/inf/ontop/pivotalrepr/impl/ConstructionNodeImpl.java
<ide> .filter(e -> !tauEqEntries.contains(e))
<ide> .filter(e -> !formerThetaDomain.contains(e.getKey()))
<ide> .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), newTheta.apply(e.getValue())))
<add> .distinct()
<ide> .collect(ImmutableCollectors.toMap());
<ide>
<ide> return new ImmutableSubstitutionImpl<>(newMap); |
|
Java | apache-2.0 | f91dde672e3ebd4527c75d749059dff0fa5c9f9b | 0 | robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gstevey/gradle,gstevey/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle | /*
* Copyright 2012 the original author or authors.
*
* 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.
*/
package org.gradle.api.artifacts;
import org.gradle.api.Incubating;
import org.gradle.api.artifacts.component.ComponentSelector;
/**
* Provides details about a dependency when it is resolved.
* Provides means to manipulate dependency metadata when it is resolved.
*
* @param <T> Component selector type.
* @since 1.4
*/
@Incubating
public interface DependencyResolveDetails<T extends ComponentSelector> {
/**
* The component selector, before it is resolved.
* The requested component selector does not change even if there are multiple dependency resolve rules
* that manipulate the dependency metadata.
*
* @since 2.4
*/
T getSelector();
/**
* The module, before it is resolved.
* The requested module does not change even if there are multiple dependency resolve rules
* that manipulate the dependency metadata.
*
* @deprecated Use {@link #getSelector()} instead.
*/
@Deprecated
ModuleVersionSelector getRequested();
/**
* Allows to override the version when the dependency {@link #getRequested()} is resolved.
* Can be used to select a version that is different than requested.
* Forcing modules via {@link org.gradle.api.artifacts.ResolutionStrategy#force(Object...)} uses this capability.
* <p>
* If you need to change not only the version but also group or name please use the {@link #useTarget(Object)} method.
*
* @param version to use when resolving this dependency, cannot be null.
* It is valid to configure the same version as requested.
*
* @deprecated Use {@link #useTarget(Object)} instead.
*/
@Deprecated
void useVersion(String version);
/**
* This method can be used to change the dependency before it is resolved,
* e.g. change group, name or version (or all three of them).
* In many cases users are interested in changing the version.
* For such scenario you can use the {@link #useVersion(String)} method.
*
* @param notation the notation that gets parsed into an instance of {@link ComponentSelector}.
* You can pass:
* <ul>
* <li>Strings like <code>"org.gradle:gradle-core:1.4"</code></li>
* <li>Maps like <code>[group: 'org.gradle', name: 'gradle-core', version: '1.4']</code></li>
* <li>instances of <code>ComponentSelector</code></li>
* <li>{@link org.gradle.api.Project} instances with <code>project(":path")</code></li>
* </ul>
*
* @since 1.5
*/
void useTarget(Object notation);
}
| subprojects/core/src/main/groovy/org/gradle/api/artifacts/DependencyResolveDetails.java | /*
* Copyright 2012 the original author or authors.
*
* 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.
*/
package org.gradle.api.artifacts;
import org.gradle.api.Incubating;
import org.gradle.api.artifacts.component.ComponentSelector;
/**
* Provides details about a dependency when it is resolved.
* Provides means to manipulate dependency metadata when it is resolved.
*
* @param <T> Component selector type.
* @since 1.4
*/
@Incubating
public interface DependencyResolveDetails<T extends ComponentSelector> {
/**
* The component selector, before it is resolved.
* The requested component selector does not change even if there are multiple dependency resolve rules
* that manipulate the dependency metadata.
*
* @since 2.4
*/
T getSelector();
/**
* The module, before it is resolved.
* The requested module does not change even if there are multiple dependency resolve rules
* that manipulate the dependency metadata.
*
* @deprecated Use {@link #getSelector()} instead.
*/
@Deprecated
ModuleVersionSelector getRequested();
/**
* Allows to override the version when the dependency {@link #getRequested()} is resolved.
* Can be used to select a version that is different than requested.
* Forcing modules via {@link org.gradle.api.artifacts.ResolutionStrategy#force(Object...)} uses this capability.
* <p>
* If you need to change not only the version but also group or name please use the {@link #useTarget(Object)} method.
*
* @param version to use when resolving this dependency, cannot be null.
* It is valid to configure the same version as requested.
*
* @deprecated Use {@link #useTarget(Object)} instead.
*/
@Deprecated
void useVersion(String version);
/**
* This method can be used to change the dependency before it is resolved,
* e.g. change group, name or version (or all three of them).
* In many cases users are interested in changing the version.
* For such scenario you can use the {@link #useVersion(String)} method.
*
* @param notation the notation that gets parsed into an instance of {@link ComponentSelector}.
* You can pass:
* <ul>
* <li>Strings like <code>"org.gradle:gradle-core:1.4"</code></li>
* <li>Maps like <code>[group: 'org.gradle', name: 'gradle-core', version: '1.4']</code></li>
* <li>instances of <code>ModuleVersionSelector</code></li>
* <li>{@link org.gradle.api.Project} instances with <code>project(":path")</code></li>
* </ul>
*
* @since 1.5
*/
void useTarget(Object notation);
}
| Fix documentation
| subprojects/core/src/main/groovy/org/gradle/api/artifacts/DependencyResolveDetails.java | Fix documentation | <ide><path>ubprojects/core/src/main/groovy/org/gradle/api/artifacts/DependencyResolveDetails.java
<ide> * <ul>
<ide> * <li>Strings like <code>"org.gradle:gradle-core:1.4"</code></li>
<ide> * <li>Maps like <code>[group: 'org.gradle', name: 'gradle-core', version: '1.4']</code></li>
<del> * <li>instances of <code>ModuleVersionSelector</code></li>
<add> * <li>instances of <code>ComponentSelector</code></li>
<ide> * <li>{@link org.gradle.api.Project} instances with <code>project(":path")</code></li>
<ide> * </ul>
<ide> * |
|
Java | bsd-3-clause | eed8b1bb37afcba7cc36723955c5f5083df912ac | 0 | mosauter/Battleship | package de.htwg.battleship.aview.gui;
import static de.htwg.battleship.util.StatCollection.heightLenght;
import static de.htwg.battleship.util.StatCollection.createMap;
import static de.htwg.battleship.util.StatCollection.fillMap;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import de.htwg.battleship.controller.IMasterController;
import de.htwg.battleship.model.IPlayer;
import de.htwg.battleship.model.IShip;
import de.htwg.battleship.observer.IObserver;
/**
* Graphical User Interface for the Game
*
* @version 1.00
* @since 2014-12-20
*/
@SuppressWarnings("serial")
public final class GUI extends JFrame implements IObserver {
/**
* Constant that indicates how long the JPopupDialogs should be shown before
* they close automatically.
*/
private static final long displayTime = 1000L;
/**
* width/height for the description labels
*/
private final int descriptionWidthHeight = 40;
/**
* width of the mainframe
*/
private final int frameWidth = 1000;
/**
* JButton to start or later to restart the Game.
*/
private final JButton start = new JButton("Start Game");
/**
* JButton to exit the whole game right at the beginning or at the end.
*/
private final JButton exit = new JButton("Exit");
/**
* JButton to show the Gamefield of player1 after the Game
*/
private final JButton endPlayer1 = new JButton();
/**
* JButton to show the Gamefield of player2 after the Game
*/
private final JButton endPlayer2 = new JButton();
/**
* Button to place a ship in horizontal direction
*/
private final JButton hor = new JButton("horizontal");
/**
* Button to place a ship in vertical direction
*/
private final JButton ver = new JButton("vertical");
/**
* JButton[][] for the Field. Button named with: 'x + " " + y'
*/
private final JButton[][] buttonField
= new JButton[heightLenght][heightLenght];
/**
* default Background for mainframe
*/
private final ImageIcon background = new ImageIcon(getClass().getResource("background.jpg"));
/**
* default background for the menuframe
*/
private final ImageIcon backgroundMenu = new ImageIcon(getClass().getResource("background_menu.jpg"));
/**
* default ImageIcon for non-hitted fields
*/
private final ImageIcon wave = new ImageIcon(getClass().getResource("wave.jpg"));
/**
* ImageIcon for missed shots
*/
private final ImageIcon miss = new ImageIcon(getClass().getResource("miss.jpg"));
/**
* ImageIcon for ship placed fields
*/
private final ImageIcon ship = new ImageIcon(getClass().getResource("ship.jpg"));
/**
* ImageIcon for hitted fields with ship
*/
private final ImageIcon hit = new ImageIcon(getClass().getResource("ship_hit.jpg"));
/**
* ImageIcon for JLabels with invisible background
*/
private final ImageIcon invisible = new ImageIcon(getClass().getResource("invisible.png"));
/**
* Dimension for Buttons in the JLabel east
*/
private final Dimension eastButtons = new Dimension(90, 30);
/**
* default Font
*/
private final Font font = new Font("Helvetica", Font.BOLD, 12);
/**
* Border for selected Field
*/
private final LineBorder selected = new LineBorder(Color.RED, 4);
/**
* To save the MasterController for all of the several UIs.
*/
private final IMasterController master;
/**
* Container which contains all object of the mainframe
*/
private final Container container;
/**
* JLabel for the center of the mainframe
*/
private JLabel center;
/**
* JLabel for the east side of the mainframe.
*/
private JLabel east;
/**
* JLabel for the x-Axis description
*/
private JLabel xAxis;
/**
* JLabel for the y-Axis description
*/
private JLabel yAxis;
/**
* JLabel to send out instructions
*/
private JLabel ausgabe;
/**
* JButton where the Ship should be placed.
*/
private JButton shipPlacePosition;
/**
* JDialog which has to be saved that the program can dispose them after its
* not in use anymore.
*/
private JDialog notifyframe;
/**
* JTextField where the player should input his name.
*/
private JTextField player;
/**
* JFrame for the menu
*/
private JFrame menuFrame;
/**
* Container which includes the menu components
*/
private Container startContainer;
/**
* Public Contructor to create a GUI.
*
* @param master MasterController which is the same for all UI
*/
public GUI(final IMasterController master) {
master.addObserver(this);
this.master = master;
//Initialize mainFrame
this.setTitle("Battleship");
this.setIconImage(new ImageIcon(getClass().getResource("frame_icon.jpg")).getImage());
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.container = new JLabel(background);
this.add(container);
//Initialize Menu
this.menuFrame();
//start Game
this.newGame();
}
/**
* Method build the menuframe
*/
private void menuFrame() {
this.menuFrame = new JFrame("Battleship");
this.menuFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//build Buttons
this.start.setBounds(new Rectangle(300, 240, 200, 50));
this.exit.setBounds(new Rectangle(300, 310, 200, 50));
this.start.setIcon(new ImageIcon(getClass().getResource("menubutton_1.jpg")));
this.start.setRolloverIcon(new ImageIcon(getClass().getResource("menubutton_1_mouseover.jpg")));
this.start.setBorder(null);
this.exit.setIcon(new ImageIcon(getClass().getResource("menubutton_2.jpg")));
this.exit.setRolloverIcon(new ImageIcon(getClass().getResource("menubutton_2_mouseover.jpg")));
this.exit.setBorder(null);
this.start.addActionListener(new MenuListener());
this.exit.addActionListener(new MenuListener());
//Container setup
this.startContainer = new JLabel(backgroundMenu);
this.startContainer.setLayout(null);
this.startContainer.add(start);
this.startContainer.add(exit);
//Frame setup
this.menuFrame.add(startContainer);
this.menuFrame.setSize(800, 500);
this.menuFrame.setResizable(false);
this.menuFrame.setLocationRelativeTo(null);
this.menuFrame.setIconImage(new ImageIcon(getClass().getResource("frame_icon.jpg")).getImage());
this.menuFrame.setVisible(true);
}
/**
* Method to initialize the GUI for the fields.
*/
public void newGame() {
//new Layout
container.setLayout(new BorderLayout(0, 0));
//panel for the left description
JLabel left = new JLabel();
left.setPreferredSize(new Dimension(descriptionWidthHeight, 520));
left.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
yAxis = new JLabel();
yAxis.setPreferredSize(new Dimension(descriptionWidthHeight, 493));
yAxis.setLayout(new GridLayout(heightLenght, 1));
yAxis.setVerticalTextPosition(SwingConstants.CENTER);
left.add(yAxis);
container.add(left, BorderLayout.WEST);
//panel for top description
JLabel top = new JLabel();
top.setPreferredSize(new Dimension(frameWidth, descriptionWidthHeight));
top.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
xAxis = new JLabel();
xAxis.setLayout(new GridLayout(1, heightLenght));
xAxis.setPreferredSize(new Dimension(860, descriptionWidthHeight));
//panel for the place in the higher left corner
JLabel leftHigherCorner = new JLabel();
leftHigherCorner.setPreferredSize(new Dimension(descriptionWidthHeight,descriptionWidthHeight));
// adding components
top.add(leftHigherCorner);
top.add(xAxis);
container.add(top, BorderLayout.NORTH);
//build gameField
center = new JLabel();
buildGameField();
container.add(center, BorderLayout.CENTER);
//bottom
JLabel bottom = new JLabel();
bottom.setPreferredSize(new Dimension(frameWidth, 50));
bottom.setLayout(new GridLayout(1, 3));
ausgabe = new JLabel();
ausgabe.setHorizontalTextPosition(SwingConstants.CENTER);
ausgabe.setVerticalTextPosition(SwingConstants.CENTER);
ausgabe.setPreferredSize(new Dimension(frameWidth, 50));
ausgabe.setHorizontalAlignment(SwingConstants.CENTER);
ausgabe.setFont(this.font);
ausgabe.setForeground(Color.WHITE);
ausgabe.setIcon(new ImageIcon(getClass().getResource("invisible_ausgabe.png")));
bottom.add(ausgabe);
this.setSize(frameWidth, 610);
this.setLocationRelativeTo(null);
container.add(bottom, BorderLayout.SOUTH);
//right
east = new JLabel();
east.setPreferredSize(new Dimension(100, 1));
east.setLayout(new FlowLayout(FlowLayout.LEFT));
container.add(east, BorderLayout.EAST);
}
/**
* Utility-Method to Build the main Gamefield
*/
private void buildGameField() {
GridLayout gl = new GridLayout(heightLenght, heightLenght);
center.setLayout(gl);
for (int y = 0; y < heightLenght; y++) {
JLabel xLabel = new JLabel();
JLabel yLabel = new JLabel();
xLabel.setHorizontalTextPosition(SwingConstants.CENTER);
xLabel.setVerticalTextPosition(SwingConstants.CENTER);
yLabel.setHorizontalTextPosition(SwingConstants.CENTER);
yLabel.setVerticalTextPosition(SwingConstants.CENTER);
xLabel.setForeground(Color.WHITE);
yLabel.setForeground(Color.WHITE);
xLabel.setText("" + (y + 1));
yLabel.setText("" + (char)('A' + y));
yAxis.add(yLabel);
xAxis.add(xLabel);
for (int x = 0; x < heightLenght; x++) {
String name = x + " " + y;
this.buttonField[x][y] = new JButton();
this.buttonField[x][y].setName(name);
this.buttonField[x][y].setIcon(wave);
center.add(buttonField[x][y]);
}
}
}
/**
* Utility-Method to create a JDialog where the user should insert his name.
*
* @param playernumber
*/
private void getPlayername(final int playernumber) {
PlayerListener pl = new PlayerListener();
JLabel icon = new JLabel(background);
icon.setBounds(new Rectangle(0, 0, 300, 150));
JLabel text = new JLabel(invisible);
text.setHorizontalTextPosition(SwingConstants.CENTER);
text.setForeground(Color.WHITE);
text.setText("please insert playername " + playernumber);
text.setBounds(new Rectangle(25, 5, 250, 30));
player = new JTextField();
player.setBorder(new LineBorder(Color.BLACK, 1));
player.setFont(this.font);
player.setBounds(new Rectangle(25, 40, 250, 30));
JButton submit = new JButton("OK");
submit.setIcon(new ImageIcon(getClass().getResource("playername_button.jpg")));
submit.setRolloverIcon(new ImageIcon(getClass().getResource("playername_button_mouseover.jpg")));
submit.setBorder(null);
submit.setBounds(new Rectangle(75, 80, 150, 30));
submit.addActionListener(pl);
notifyframe = new JDialog();
notifyframe.add(icon);
notifyframe.setModal(true);
notifyframe.setSize(300, 150);
icon.setLayout(null);
icon.add(text);
icon.add(player);
icon.add(submit);
notifyframe.setResizable(false);
notifyframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
notifyframe.setLocationRelativeTo(getParent());
notifyframe.getRootPane().setDefaultButton(submit);
notifyframe.setVisible(true);
}
/**
* Utility-Method to add the 'place'-Button and a ComboBox to the main
* frame.
*/
private void placeShip() {
this.setVisible(false);
east.remove(hor);
east.remove(ver);
hor.addActionListener(new PlaceListener());
ver.addActionListener(new PlaceListener());
resetPlaceButton();
this.ver.setPreferredSize(eastButtons);
this.ver.setIcon(new ImageIcon(getClass().getResource("vertical.jpg")));
this.ver.setRolloverIcon(new ImageIcon(getClass().getResource("vertical_mouseover.jpg")));
this.ver.setBorder(null);
this.hor.setPreferredSize(eastButtons);
this.hor.setIcon(new ImageIcon(getClass().getResource("horizontal.jpg")));
this.hor.setRolloverIcon(new ImageIcon(getClass().getResource("horizontal_mouseover.jpg")));
this.hor.setBorder(null);
east.add(hor);
east.add(ver);
this.setVisible(true);
}
/**
* Utility-Method to update the image-icons of the gamefield buttons
*
* @param player current player
* @param hideShip boolean
*/
private void updateGameField(IPlayer player, boolean hideShips) {
IShip[] shipList = player.getOwnBoard().getShipList();
Map<Integer, Set<Integer>> map = createMap();
fillMap(shipList, map, player.getOwnBoard().getShips());
for (int y = 0; y < heightLenght; y++) {
for (int x = 0; x < heightLenght; x++) {
boolean isShip = false;
this.buttonField[x][y].setBorder(new JButton().getBorder());
for (Integer value : map.get(y)) {
if (value == x) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(hit);
} else {
if (hideShips) {
this.buttonField[x][y].setIcon(wave);
} else {
this.buttonField[x][y].setIcon(ship);
}
}
isShip = true;
}
}
if (!isShip) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(miss);
} else {
this.buttonField[x][y].setIcon(wave);
}
}
}
}
}
/**
* Utility-Method to reset the selected button in the place states.
*/
private void resetPlaceButton() {
if (shipPlacePosition != null) {
shipPlacePosition.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
/**
* Utility-Method to show the Gamefield after the Game
*/
private void endGame() {
this.setVisible(false);
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
}
}
this.endPlayer1.setPreferredSize(eastButtons);
this.endPlayer2.setPreferredSize(eastButtons);
this.endPlayer1.setBorder(null);
this.endPlayer2.setBorder(null);
this.endPlayer1.setIcon(new ImageIcon(getClass().getResource("end_playername.jpg")));
this.endPlayer2.setIcon(new ImageIcon(getClass().getResource("end_playername.jpg")));
this.endPlayer1.setRolloverIcon(new ImageIcon(getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer2.setRolloverIcon(new ImageIcon(getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer1.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setText(master.getPlayer1().getName());
this.endPlayer2.setText(master.getPlayer2().getName());
this.endPlayer1.setFont(this.font);
this.endPlayer2.setFont(this.font);
this.endPlayer1.setForeground(Color.WHITE);
this.endPlayer2.setForeground(Color.WHITE);
this.endPlayer1.addActionListener(new WinListener());
this.endPlayer2.addActionListener(new WinListener());
JButton finish = new JButton();
finish.setBorder(null);
finish.setPreferredSize(eastButtons);
finish.setIcon(new ImageIcon(getClass().getResource("finish.jpg")));
finish.setRolloverIcon(new ImageIcon(getClass().getResource("finish_mouseover.jpg")));
finish.addActionListener(new WinListener());
east.add(this.endPlayer1);
east.add(this.endPlayer2);
east.add(finish);
this.setVisible(true);
}
/**
* Utility-Method to set the mainframe invisible
*/
private void setInvisible() {
this.setVisible(false);
}
@Override
public void update() {
switch (master.getCurrentState()) {
case START:
break;
case GETNAME1:
menuFrame.dispose();
getPlayername(1);
break;
case GETNAME2:
notifyframe.dispose();
getPlayername(2);
break;
case PLACE1:
notifyframe.dispose();
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer1(), false);
placeShip();
ausgabe.setText(master.getPlayer1().getName()
+ " now place the ship with the length of "
+ (master.getPlayer1().getOwnBoard().getShips() + 2));
break;
case PLACE2:
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer2(), false);
placeShip();
ausgabe.setText(master.getPlayer2().getName()
+ " now place the ship with the length of "
+ (master.getPlayer2().getOwnBoard().getShips() + 2));
break;
case FINALPLACE1:
updateGameField(master.getPlayer1(), false);
resetPlaceButton();
break;
case FINALPLACE2:
updateGameField(master.getPlayer2(), false);
resetPlaceButton();
break;
case PLACEERR:
new JPopupDialog(this, "Placement error",
"Cannot place a ship there due to a collision or "
+ "the ship is out of the field!",
displayTime, false);
break;
case SHOOT1:
this.setVisible(false);
east.remove(hor);
east.remove(ver);
this.setVisible(true);
activateListener(new ShootListener());
updateGameField(master.getPlayer2(), true);
ausgabe.setText(master.getPlayer1().getName()
+ " is now at the turn to shoot");
break;
case SHOOT2:
activateListener(new ShootListener());
updateGameField(master.getPlayer1(), true);
ausgabe.setText(master.getPlayer2().getName()
+ " is now at the turn to shoot");
break;
case HIT:
new JPopupDialog(this, "Shot Result",
"Your shot was a Hit!!", displayTime, false);
break;
case MISS:
new JPopupDialog(this, "Shot Result",
"Your shot was a Miss!!", displayTime, false);
break;
case WIN1:
updateGameField(master.getPlayer2(), false);
String msg = master.getPlayer1().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
displayTime, false);
break;
case WIN2:
updateGameField(master.getPlayer1(), false);
msg = master.getPlayer2().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
displayTime, false);
break;
case END:
endGame();
break;
case WRONGINPUT:
// isn't needed in the GUI, help-state for a UI where you
// can give input at the false states
break;
default:
break;
}
}
/**
* Method to activate a new Action Listener to the JButton[][]-Matrix. uses
* the removeListener-Method
*
* @param newListener the new Listener of the button matrix
*/
private void activateListener(final ActionListener newListener) {
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
button.addActionListener(newListener);
}
}
}
/**
* Method which removes all Listener from a button.
*
* @param button specified button
*/
private void removeListener(final JButton button) {
if (button == null) {
return;
}
ActionListener[] actionList = button.getActionListeners();
for (ActionListener acLst : actionList) {
button.removeActionListener(acLst);
}
}
/**
* ActionListener for the State of the Game in which the Player has to set
* his Ships on the field. PLACE1 / PLACE2 / FINALPLACE1 / FINALPLACE2
*/
private class PlaceListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(hor) || button.equals(ver)) {
if (shipPlacePosition != null) {
String[] parts = shipPlacePosition.getName().split(" ");
if (button.equals(hor)) {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), true);
} else {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), false);
}
} else {
new JPopupDialog(null, "Placement error",
"Please choose a field to place the ship",
displayTime, false);
}
} else {
if (shipPlacePosition != null && !shipPlacePosition.equals(button)) {
switchColor(shipPlacePosition);
}
String[] parts = button.getName().split(" ");
JButton select = buttonField[Integer.valueOf(parts[0])]
[Integer.valueOf(parts[1])];
switchColor(select);
}
}
/**
* Method to switch the colour of a button.
*
* @param select specified Button
*/
private void switchColor(final JButton select) {
if (!select.getBorder().equals(selected)) {
select.setBorder(selected);
shipPlacePosition = select;
} else {
select.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
}
/**
* ActionListener for the State of the Game in which the Player has to shoot
* on the other Players board. SHOOT1 / SHOOT2
*/
private class ShootListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
String[] name = button.getName().split(" ");
int x = Integer.parseInt(name[0]);
int y = Integer.parseInt(name[1]);
master.shoot(x, y);
}
}
/**
* ActionListener for the State of the game where the game is over and the
* game starts. START / END
*/
private class MenuListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
menuFrame.setVisible(false);
JButton target = (JButton) e.getSource();
switch (target.getText()) {
case "Start Game":
master.startGame();
setVisible(true);
break;
case "Exit":
System.exit(0);
break;
case "Start a new Game":
setVisible(true);
master.startGame();
break;
default:
break;
}
}
}
/**
* ActionListener for the GETNAME 1 / 2 - States.
*/
private class PlayerListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
notifyframe.setVisible(false);
master.setPlayerName(player.getText());
notifyframe.dispose();
}
}
private class WinListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
if (button.equals(endPlayer1)) {
updateGameField(master.getPlayer2(), false);
} else if(button.equals(endPlayer2)) {
updateGameField(master.getPlayer1(), false);
} else {
setInvisible();
east.removeAll();
menuFrame.setVisible(true);
menuFrame.toBack();
}
}
}
}
| Battleship/src/main/java/de/htwg/battleship/aview/gui/GUI.java | package de.htwg.battleship.aview.gui;
import static de.htwg.battleship.util.StatCollection.heightLenght;
import static de.htwg.battleship.util.StatCollection.createMap;
import static de.htwg.battleship.util.StatCollection.fillMap;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Set;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import de.htwg.battleship.controller.IMasterController;
import de.htwg.battleship.model.IPlayer;
import de.htwg.battleship.model.IShip;
import de.htwg.battleship.observer.IObserver;
/**
* Graphical User Interface for the Game
*
* @version 1.00
* @since 2014-12-20
*/
@SuppressWarnings("serial")
public final class GUI extends JFrame implements IObserver {
/**
* Constant that indicates how long the JPopupDialogs should be shown before
* they close automatically.
*/
private static final long displaytime = 1000L;
/**
* JButton to start or later to restart the Game.
*/
private final JButton start = new JButton("Start Game");
/**
* JButton to exit the whole game right at the beginning or at the end.
*/
private final JButton exit = new JButton("Exit");
/**
* JButton to show the Gamefield of player1 after the Game
*/
private final JButton endPlayer1 = new JButton();
/**
* JButton to show the Gamefield of player2 after the Game
*/
private final JButton endPlayer2 = new JButton();
/**
* Button to place a ship in horizontal direction
*/
private final JButton hor = new JButton("horizontal");
/**
* Button to place a ship in vertical direction
*/
private final JButton ver = new JButton("vertical");
/**
* JButton[][] for the Field. Button named with: 'x + " " + y'
*/
private final JButton[][] buttonField
= new JButton[heightLenght][heightLenght];
/**
* default Background for mainframe
*/
private final ImageIcon background = new ImageIcon(getClass().getResource("background.jpg"));
/**
* default background for the menuframe
*/
private final ImageIcon backgroundMenu = new ImageIcon(getClass().getResource("background_menu.jpg"));
/**
* default ImageIcon for non-hitted fields
*/
private final ImageIcon wave = new ImageIcon(getClass().getResource("wave.jpg"));
/**
* ImageIcon for missed shots
*/
private final ImageIcon miss = new ImageIcon(getClass().getResource("miss.jpg"));
/**
* ImageIcon for ship placed fields
*/
private final ImageIcon ship = new ImageIcon(getClass().getResource("ship.jpg"));
/**
* ImageIcon for hitted fields with ship
*/
private final ImageIcon hit = new ImageIcon(getClass().getResource("ship_hit.jpg"));
/**
* ImageIcon for JLabels with invisible background
*/
private final ImageIcon invisible = new ImageIcon(getClass().getResource("invisible.png"));
/**
* Dimension for Buttons in the JLabel east
*/
private final Dimension eastButtons = new Dimension(90, 30);
/**
* default Font
*/
private final Font font = new Font("Helvetica", Font.BOLD, 12);
/**
* Border for selected Field
*/
private final LineBorder selected = new LineBorder(Color.RED, 4);
/**
* To save the MasterController for all of the several UIs.
*/
private final IMasterController master;
/**
* Container which contains all object of the mainframe
*/
private final Container container;
/**
* JLabel for the center of the mainframe
*/
private JLabel center;
/**
* JLabel for the east side of the mainframe.
*/
private JLabel east;
/**
* JLabel for the x-Axis description
*/
private JLabel xAxis;
/**
* JLabel for the y-Axis description
*/
private JLabel yAxis;
/**
* JLabel to send out instructions
*/
private JLabel ausgabe;
/**
* JButton where the Ship should be placed.
*/
private JButton shipPlacePosition;
/**
* JDialog which has to be saved that the program can dispose them after its
* not in use anymore.
*/
private JDialog notifyframe;
/**
* JTextField where the player should input his name.
*/
private JTextField player;
/**
* JFrame for the menu
*/
private JFrame menuFrame;
/**
* Container which includes the menu components
*/
private Container startContainer;
/**
* Public Contructor to create a GUI.
*
* @param master MasterController which is the same for all UI
*/
public GUI(final IMasterController master) {
master.addObserver(this);
this.master = master;
//Initialize mainFrame
this.setTitle("Battleship");
this.setIconImage(new ImageIcon(getClass().getResource("frame_icon.jpg")).getImage());
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.container = new JLabel(background);
this.add(container);
//Initialize Menu
this.menuFrame();
//start Game
this.newGame();
}
/**
* Method build the menuframe
*/
private void menuFrame() {
this.menuFrame = new JFrame("Battleship");
this.menuFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
//build Buttons
this.start.setBounds(new Rectangle(300, 240, 200, 50));
this.exit.setBounds(new Rectangle(300, 310, 200, 50));
this.start.setIcon(new ImageIcon(getClass().getResource("menubutton_1.jpg")));
this.start.setRolloverIcon(new ImageIcon(getClass().getResource("menubutton_1_mouseover.jpg")));
this.start.setBorder(null);
this.exit.setIcon(new ImageIcon(getClass().getResource("menubutton_2.jpg")));
this.exit.setRolloverIcon(new ImageIcon(getClass().getResource("menubutton_2_mouseover.jpg")));
this.exit.setBorder(null);
this.start.addActionListener(new MenuListener());
this.exit.addActionListener(new MenuListener());
//Container setup
this.startContainer = new JLabel(backgroundMenu);
this.startContainer.setLayout(null);
this.startContainer.add(start);
this.startContainer.add(exit);
//Frame setup
this.menuFrame.add(startContainer);
this.menuFrame.setSize(800, 500);
this.menuFrame.setResizable(false);
this.menuFrame.setLocationRelativeTo(null);
this.menuFrame.setIconImage(new ImageIcon(getClass().getResource("frame_icon.jpg")).getImage());
this.menuFrame.setVisible(true);
}
/**
* Method to initialize the GUI for the fields.
*/
public void newGame() {
//new Layout
container.setLayout(new BorderLayout(0, 0));
//panel for the left description
JLabel left = new JLabel();
left.setPreferredSize(new Dimension(40, 520));
left.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
yAxis = new JLabel();
yAxis.setPreferredSize(new Dimension(40, 493));
yAxis.setLayout(new GridLayout(heightLenght, 1));
yAxis.setVerticalTextPosition(SwingConstants.CENTER);
left.add(yAxis);
container.add(left, BorderLayout.WEST);
//panel for top description
JLabel top = new JLabel();
top.setPreferredSize(new Dimension(1000, 40));
top.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
xAxis = new JLabel();
xAxis.setLayout(new GridLayout(1, heightLenght));
xAxis.setPreferredSize(new Dimension(860, 40));
//panel for the place in the higher left corner
JLabel leftHigherCorner = new JLabel();
leftHigherCorner.setPreferredSize(new Dimension(40,40));
// adding components
top.add(leftHigherCorner);
top.add(xAxis);
container.add(top, BorderLayout.NORTH);
//build gameField
center = new JLabel();
buildGameField();
container.add(center, BorderLayout.CENTER);
//bottom
JLabel bottom = new JLabel();
bottom.setPreferredSize(new Dimension(1000, 50));
bottom.setLayout(new GridLayout(1, 3));
ausgabe = new JLabel();
ausgabe.setHorizontalTextPosition(SwingConstants.CENTER);
ausgabe.setVerticalTextPosition(SwingConstants.CENTER);
ausgabe.setPreferredSize(new Dimension(1000, 50));
ausgabe.setHorizontalAlignment(SwingConstants.CENTER);
ausgabe.setFont(this.font);
ausgabe.setForeground(Color.WHITE);
ausgabe.setIcon(new ImageIcon(getClass().getResource("invisible_ausgabe.png")));
bottom.add(ausgabe);
this.setSize(1000, 610);
this.setLocationRelativeTo(null);
container.add(bottom, BorderLayout.SOUTH);
//right
east = new JLabel();
east.setPreferredSize(new Dimension(100, 30));
east.setLayout(new FlowLayout(FlowLayout.LEFT));
container.add(east, BorderLayout.EAST);
}
/**
* Utility-Method to Build the main Gamefield
*/
private void buildGameField() {
GridLayout gl = new GridLayout(heightLenght, heightLenght);
center.setLayout(gl);
for (int y = 0; y < heightLenght; y++) {
JLabel xLabel = new JLabel();
JLabel yLabel = new JLabel();
xLabel.setHorizontalTextPosition(SwingConstants.CENTER);
xLabel.setVerticalTextPosition(SwingConstants.CENTER);
yLabel.setHorizontalTextPosition(SwingConstants.CENTER);
yLabel.setVerticalTextPosition(SwingConstants.CENTER);
xLabel.setForeground(Color.WHITE);
yLabel.setForeground(Color.WHITE);
xLabel.setText("" + (y + 1));
yLabel.setText("" + (char)('A' + y));
yAxis.add(yLabel);
xAxis.add(xLabel);
for (int x = 0; x < heightLenght; x++) {
String name = x + " " + y;
this.buttonField[x][y] = new JButton();
this.buttonField[x][y].setName(name);
this.buttonField[x][y].setIcon(wave);
center.add(buttonField[x][y]);
}
}
}
/**
* Utility-Method to create a JDialog where the user should insert his name.
*
* @param playernumber
*/
private void getPlayername(final int playernumber) {
PlayerListener pl = new PlayerListener();
JLabel icon = new JLabel(background);
icon.setBounds(new Rectangle(0, 0, 300, 150));
JLabel text = new JLabel(invisible);
text.setHorizontalTextPosition(SwingConstants.CENTER);
text.setForeground(Color.WHITE);
text.setText("please insert playername " + playernumber);
text.setBounds(new Rectangle(25, 5, 250, 30));
player = new JTextField();
player.setBorder(new LineBorder(Color.BLACK, 1));
player.setFont(this.font);
player.setBounds(new Rectangle(25, 40, 250, 30));
JButton submit = new JButton("OK");
submit.setIcon(new ImageIcon(getClass().getResource("playername_button.jpg")));
submit.setRolloverIcon(new ImageIcon(getClass().getResource("playername_button_mouseover.jpg")));
submit.setBorder(null);
submit.setBounds(new Rectangle(75, 80, 150, 30));
submit.addActionListener(pl);
notifyframe = new JDialog();
notifyframe.add(icon);
notifyframe.setModal(true);
notifyframe.setSize(300, 150);
icon.setLayout(null);
icon.add(text);
icon.add(player);
icon.add(submit);
notifyframe.setResizable(false);
notifyframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
notifyframe.setLocationRelativeTo(getParent());
notifyframe.getRootPane().setDefaultButton(submit);
notifyframe.setVisible(true);
}
/**
* Utility-Method to add the 'place'-Button and a ComboBox to the main
* frame.
*/
private void placeShip() {
this.setVisible(false);
east.remove(hor);
east.remove(ver);
hor.addActionListener(new PlaceListener());
ver.addActionListener(new PlaceListener());
resetPlaceButton();
this.ver.setPreferredSize(eastButtons);
this.ver.setIcon(new ImageIcon(getClass().getResource("vertical.jpg")));
this.ver.setRolloverIcon(new ImageIcon(getClass().getResource("vertical_mouseover.jpg")));
this.ver.setBorder(null);
this.hor.setPreferredSize(eastButtons);
this.hor.setIcon(new ImageIcon(getClass().getResource("horizontal.jpg")));
this.hor.setRolloverIcon(new ImageIcon(getClass().getResource("horizontal_mouseover.jpg")));
this.hor.setBorder(null);
east.add(hor);
east.add(ver);
this.setVisible(true);
}
/**
* Utility-Method to update the image-icons of the gamefield buttons
*
* @param player current player
* @param hideShip boolean
*/
private void updateGameField(IPlayer player, boolean hideShips) {
IShip[] shipList = player.getOwnBoard().getShipList();
Map<Integer, Set<Integer>> map = createMap();
fillMap(shipList, map, player.getOwnBoard().getShips());
for (int y = 0; y < heightLenght; y++) {
for (int x = 0; x < heightLenght; x++) {
boolean isShip = false;
this.buttonField[x][y].setBorder(new JButton().getBorder());
for (Integer value : map.get(y)) {
if (value == x) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(hit);
} else {
if (hideShips) {
this.buttonField[x][y].setIcon(wave);
} else {
this.buttonField[x][y].setIcon(ship);
}
}
isShip = true;
}
}
if (!isShip) {
if (player.getOwnBoard().isHit(x, y)) {
this.buttonField[x][y].setIcon(miss);
} else {
this.buttonField[x][y].setIcon(wave);
}
}
}
}
}
/**
* Utility-Method to reset the selected button in the place states.
*/
private void resetPlaceButton() {
if (shipPlacePosition != null) {
shipPlacePosition.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
/**
* Utility-Method to show the Gamefield after the Game
*/
private void endGame() {
this.setVisible(false);
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
}
}
this.endPlayer1.setPreferredSize(eastButtons);
this.endPlayer2.setPreferredSize(eastButtons);
this.endPlayer1.setBorder(null);
this.endPlayer2.setBorder(null);
this.endPlayer1.setIcon(new ImageIcon(getClass().getResource("end_playername.jpg")));
this.endPlayer2.setIcon(new ImageIcon(getClass().getResource("end_playername.jpg")));
this.endPlayer1.setRolloverIcon(new ImageIcon(getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer2.setRolloverIcon(new ImageIcon(getClass().getResource("end_playername_mouseover.jpg")));
this.endPlayer1.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setVerticalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer2.setHorizontalTextPosition(SwingConstants.CENTER);
this.endPlayer1.setText(master.getPlayer1().getName());
this.endPlayer2.setText(master.getPlayer2().getName());
this.endPlayer1.setFont(this.font);
this.endPlayer2.setFont(this.font);
this.endPlayer1.setForeground(Color.WHITE);
this.endPlayer2.setForeground(Color.WHITE);
this.endPlayer1.addActionListener(new WinListener());
this.endPlayer2.addActionListener(new WinListener());
JButton finish = new JButton();
finish.setBorder(null);
finish.setPreferredSize(eastButtons);
finish.setIcon(new ImageIcon(getClass().getResource("finish.jpg")));
finish.setRolloverIcon(new ImageIcon(getClass().getResource("finish_mouseover.jpg")));
finish.addActionListener(new WinListener());
east.add(this.endPlayer1);
east.add(this.endPlayer2);
east.add(finish);
this.setVisible(true);
}
/**
* Utility-Method to set the mainframe invisible
*/
private void setInvisible() {
this.setVisible(false);
}
@Override
public void update() {
switch (master.getCurrentState()) {
case START:
break;
case GETNAME1:
menuFrame.dispose();
getPlayername(1);
break;
case GETNAME2:
notifyframe.dispose();
getPlayername(2);
break;
case PLACE1:
notifyframe.dispose();
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer1(), false);
placeShip();
ausgabe.setText(master.getPlayer1().getName()
+ " now place the ship with the length of "
+ (master.getPlayer1().getOwnBoard().getShips() + 2));
break;
case PLACE2:
resetPlaceButton();
activateListener(new PlaceListener());
updateGameField(master.getPlayer2(), false);
placeShip();
ausgabe.setText(master.getPlayer2().getName()
+ " now place the ship with the length of "
+ (master.getPlayer2().getOwnBoard().getShips() + 2));
break;
case FINALPLACE1:
updateGameField(master.getPlayer1(), false);
resetPlaceButton();
break;
case FINALPLACE2:
updateGameField(master.getPlayer2(), false);
resetPlaceButton();
break;
case PLACEERR:
new JPopupDialog(this, "Placement error",
"Cannot place a ship there due to a collision or "
+ "the ship is out of the field!",
displaytime, false);
break;
case SHOOT1:
this.setVisible(false);
east.remove(hor);
east.remove(ver);
this.setVisible(true);
activateListener(new ShootListener());
updateGameField(master.getPlayer2(), true);
ausgabe.setText(master.getPlayer1().getName()
+ " is now at the turn to shoot");
break;
case SHOOT2:
activateListener(new ShootListener());
updateGameField(master.getPlayer1(), true);
ausgabe.setText(master.getPlayer2().getName()
+ " is now at the turn to shoot");
break;
case HIT:
new JPopupDialog(this, "Shot Result",
"Your shot was a Hit!!", displaytime, false);
break;
case MISS:
new JPopupDialog(this, "Shot Result",
"Your shot was a Miss!!", displaytime, false);
break;
case WIN1:
updateGameField(master.getPlayer2(), false);
String msg = master.getPlayer1().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
displaytime, false);
break;
case WIN2:
updateGameField(master.getPlayer1(), false);
msg = master.getPlayer2().getName() + " has won!!";
ausgabe.setText(msg);
new JPopupDialog(this, "Winner!", msg,
displaytime, false);
break;
case END:
endGame();
break;
case WRONGINPUT:
// isn't needed in the GUI, help-state for a UI where you
// can give input at the false states
break;
default:
break;
}
}
/**
* Method to activate a new Action Listener to the JButton[][]-Matrix. uses
* the removeListener-Method
*
* @param newListener the new Listener of the button matrix
*/
private void activateListener(final ActionListener newListener) {
for (JButton[] buttonArray : buttonField) {
for (JButton button : buttonArray) {
removeListener(button);
button.addActionListener(newListener);
}
}
}
/**
* Method which removes all Listener from a button.
*
* @param button specified button
*/
private void removeListener(final JButton button) {
if (button == null) {
return;
}
ActionListener[] actionList = button.getActionListeners();
for (ActionListener acLst : actionList) {
button.removeActionListener(acLst);
}
}
/**
* ActionListener for the State of the Game in which the Player has to set
* his Ships on the field. PLACE1 / PLACE2 / FINALPLACE1 / FINALPLACE2
*/
private class PlaceListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(hor) || button.equals(ver)) {
if (shipPlacePosition != null) {
String[] parts = shipPlacePosition.getName().split(" ");
if (button.equals(hor)) {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), true);
} else {
master.placeShip(Integer.valueOf(parts[0]),
Integer.valueOf(parts[1]), false);
}
} else {
new JPopupDialog(null, "Placement error",
"Please choose a field to place the ship",
displaytime, false);
}
} else {
if (shipPlacePosition != null && !shipPlacePosition.equals(button)) {
switchColor(shipPlacePosition);
}
String[] parts = button.getName().split(" ");
JButton select = buttonField[Integer.valueOf(parts[0])]
[Integer.valueOf(parts[1])];
switchColor(select);
}
}
/**
* Method to switch the colour of a button.
*
* @param select specified Button
*/
private void switchColor(final JButton select) {
if (!select.getBorder().equals(selected)) {
select.setBorder(selected);
shipPlacePosition = select;
} else {
select.setBorder(new JButton().getBorder());
shipPlacePosition = null;
}
}
}
/**
* ActionListener for the State of the Game in which the Player has to shoot
* on the other Players board. SHOOT1 / SHOOT2
*/
private class ShootListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
JButton button = (JButton) e.getSource();
String[] name = button.getName().split(" ");
int x = Integer.parseInt(name[0]);
int y = Integer.parseInt(name[1]);
master.shoot(x, y);
}
}
/**
* ActionListener for the State of the game where the game is over and the
* game starts. START / END
*/
private class MenuListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
menuFrame.setVisible(false);
JButton target = (JButton) e.getSource();
switch (target.getText()) {
case "Start Game":
master.startGame();
setVisible(true);
break;
case "Exit":
System.exit(0);
break;
case "Start a new Game":
setVisible(true);
master.startGame();
break;
default:
break;
}
}
}
/**
* ActionListener for the GETNAME 1 / 2 - States.
*/
private class PlayerListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
notifyframe.setVisible(false);
master.setPlayerName(player.getText());
notifyframe.dispose();
}
}
private class WinListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
if (button.equals(endPlayer1)) {
updateGameField(master.getPlayer2(), false);
} else if(button.equals(endPlayer2)) {
updateGameField(master.getPlayer1(), false);
} else {
setInvisible();
east.removeAll();
menuFrame.setVisible(true);
menuFrame.toBack();
}
}
}
}
| fixed magic numbers
| Battleship/src/main/java/de/htwg/battleship/aview/gui/GUI.java | fixed magic numbers | <ide><path>attleship/src/main/java/de/htwg/battleship/aview/gui/GUI.java
<ide> * Constant that indicates how long the JPopupDialogs should be shown before
<ide> * they close automatically.
<ide> */
<del> private static final long displaytime = 1000L;
<add> private static final long displayTime = 1000L;
<add>
<add> /**
<add> * width/height for the description labels
<add> */
<add> private final int descriptionWidthHeight = 40;
<add>
<add> /**
<add> * width of the mainframe
<add> */
<add> private final int frameWidth = 1000;
<ide>
<ide> /**
<ide> * JButton to start or later to restart the Game.
<ide>
<ide> //panel for the left description
<ide> JLabel left = new JLabel();
<del> left.setPreferredSize(new Dimension(40, 520));
<add> left.setPreferredSize(new Dimension(descriptionWidthHeight, 520));
<ide> left.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
<ide> yAxis = new JLabel();
<del> yAxis.setPreferredSize(new Dimension(40, 493));
<add> yAxis.setPreferredSize(new Dimension(descriptionWidthHeight, 493));
<ide> yAxis.setLayout(new GridLayout(heightLenght, 1));
<ide> yAxis.setVerticalTextPosition(SwingConstants.CENTER);
<ide> left.add(yAxis);
<ide>
<ide> //panel for top description
<ide> JLabel top = new JLabel();
<del> top.setPreferredSize(new Dimension(1000, 40));
<add> top.setPreferredSize(new Dimension(frameWidth, descriptionWidthHeight));
<ide> top.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
<ide> xAxis = new JLabel();
<ide> xAxis.setLayout(new GridLayout(1, heightLenght));
<del> xAxis.setPreferredSize(new Dimension(860, 40));
<add> xAxis.setPreferredSize(new Dimension(860, descriptionWidthHeight));
<ide> //panel for the place in the higher left corner
<ide> JLabel leftHigherCorner = new JLabel();
<del> leftHigherCorner.setPreferredSize(new Dimension(40,40));
<add> leftHigherCorner.setPreferredSize(new Dimension(descriptionWidthHeight,descriptionWidthHeight));
<ide> // adding components
<ide> top.add(leftHigherCorner);
<ide> top.add(xAxis);
<ide>
<ide> //bottom
<ide> JLabel bottom = new JLabel();
<del> bottom.setPreferredSize(new Dimension(1000, 50));
<add> bottom.setPreferredSize(new Dimension(frameWidth, 50));
<ide> bottom.setLayout(new GridLayout(1, 3));
<ide> ausgabe = new JLabel();
<ide> ausgabe.setHorizontalTextPosition(SwingConstants.CENTER);
<ide> ausgabe.setVerticalTextPosition(SwingConstants.CENTER);
<del> ausgabe.setPreferredSize(new Dimension(1000, 50));
<add> ausgabe.setPreferredSize(new Dimension(frameWidth, 50));
<ide> ausgabe.setHorizontalAlignment(SwingConstants.CENTER);
<ide> ausgabe.setFont(this.font);
<ide> ausgabe.setForeground(Color.WHITE);
<ide> ausgabe.setIcon(new ImageIcon(getClass().getResource("invisible_ausgabe.png")));
<ide> bottom.add(ausgabe);
<del> this.setSize(1000, 610);
<add> this.setSize(frameWidth, 610);
<ide> this.setLocationRelativeTo(null);
<ide> container.add(bottom, BorderLayout.SOUTH);
<ide>
<ide> //right
<ide> east = new JLabel();
<del> east.setPreferredSize(new Dimension(100, 30));
<add> east.setPreferredSize(new Dimension(100, 1));
<ide> east.setLayout(new FlowLayout(FlowLayout.LEFT));
<ide> container.add(east, BorderLayout.EAST);
<ide> }
<ide> new JPopupDialog(this, "Placement error",
<ide> "Cannot place a ship there due to a collision or "
<ide> + "the ship is out of the field!",
<del> displaytime, false);
<add> displayTime, false);
<ide> break;
<ide> case SHOOT1:
<ide> this.setVisible(false);
<ide> break;
<ide> case HIT:
<ide> new JPopupDialog(this, "Shot Result",
<del> "Your shot was a Hit!!", displaytime, false);
<add> "Your shot was a Hit!!", displayTime, false);
<ide> break;
<ide> case MISS:
<ide> new JPopupDialog(this, "Shot Result",
<del> "Your shot was a Miss!!", displaytime, false);
<add> "Your shot was a Miss!!", displayTime, false);
<ide> break;
<ide> case WIN1:
<ide> updateGameField(master.getPlayer2(), false);
<ide> String msg = master.getPlayer1().getName() + " has won!!";
<ide> ausgabe.setText(msg);
<ide> new JPopupDialog(this, "Winner!", msg,
<del> displaytime, false);
<add> displayTime, false);
<ide> break;
<ide> case WIN2:
<ide> updateGameField(master.getPlayer1(), false);
<ide> msg = master.getPlayer2().getName() + " has won!!";
<ide> ausgabe.setText(msg);
<ide> new JPopupDialog(this, "Winner!", msg,
<del> displaytime, false);
<add> displayTime, false);
<ide> break;
<ide> case END:
<ide> endGame();
<ide> } else {
<ide> new JPopupDialog(null, "Placement error",
<ide> "Please choose a field to place the ship",
<del> displaytime, false);
<add> displayTime, false);
<ide> }
<ide> } else {
<ide> if (shipPlacePosition != null && !shipPlacePosition.equals(button)) { |
|
Java | mit | b093835e70393fe23c879ecb3872f86de4b8d8b0 | 0 | korinth/apistogramma | /*
* Copyright (C) 2013 Eostre (Martin Korinth)
*
* 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.
*/
package se.eostre.apistogramma;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Environment {
String uri;
String method;
String route;
String controller;
String action;
HttpServletRequest request;
HttpServletResponse response;
Map<String, String> attributes;
Environment(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
uri = request.getServletPath().replace(".act", "");
method = request.getMethod().toLowerCase();
}
boolean resolve(Route route) {
if (route.method.isEmpty() || route.method.equals(method)) {
attributes = route.parse(uri);
if (attributes != null) {
if (route.isMatch(attributes.get("controller"), attributes.get("action"))) {
this.route = route.route;
controller = route.controller;
action = route.action;
} else {
attributes = null;
}
}
}
return attributes != null;
}
public String getAttribute(String name) {
return attributes.get(name);
}
public String getParamter(String name) {
return request.getParameter(name);
}
public String[] getParameters(String name) {
return request.getParameterValues(name);
}
public void setModel(String name, Object object) {
request.setAttribute(name, object);
}
public String getRoute() {
return route;
}
public String getUri() {
return uri;
}
public String getMethod() {
return method;
}
public HttpServletRequest getRequest() {
return request;
}
public HttpServletResponse getResponse() {
return response;
}
public void render() throws Status {
render(controller, action);
}
public void render(String action) throws Status {
render(controller, action);
}
public void render(String controller, String action) throws Status {
// TODO: if not AJAX
try {
request.getRequestDispatcher("/views/" + controller + "/" + action + ".jsp").forward(request, response);
} catch (Exception exception) {
throw new Status("Unable to render!", 500, exception);
}
}
public void redirect(String path) throws Status {
// TODO: if path.startsWith("/") add context path
try {
response.sendRedirect(path);
} catch (Exception exception) {
throw new Status("Unable to redirect!", 500, exception);
}
}
@Override
public String toString() {
return "{ uri => " + uri + ", method => " + method + ", attributes => " + attributes + "}";
}
}
| src/main/java/se/eostre/apistogramma/Environment.java | /*
* Copyright (C) 2013 Eostre (Martin Korinth)
*
* 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.
*/
package se.eostre.apistogramma;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Environment {
String uri;
String method;
String route;
String controller;
String action;
HttpServletRequest request;
HttpServletResponse response;
Map<String, String> attributes;
Environment(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
uri = request.getPathInfo();
method = request.getMethod().toLowerCase();
}
boolean resolve(Route route) {
if (route.method.isEmpty() || route.method.equals(method)) {
attributes = route.parse(uri);
if (attributes != null) {
if (route.isMatch(attributes.get("controller"), attributes.get("action"))) {
this.route = route.route;
controller = route.controller;
action = route.action;
} else {
attributes = null;
}
}
}
return attributes != null;
}
public String getAttribute(String name) {
return attributes.get(name);
}
public String getParamter(String name) {
return request.getParameter(name);
}
public String[] getParameters(String name) {
return request.getParameterValues(name);
}
public void setModel(String name, Object object) {
request.setAttribute(name, object);
}
public String getRoute() {
return route;
}
public String getUri() {
return uri;
}
public String getMethod() {
return method;
}
public HttpServletRequest getRequest() {
return request;
}
public HttpServletResponse getResponse() {
return response;
}
public void render() throws Status {
render(controller, action);
}
public void render(String action) throws Status {
render(controller, action);
}
public void render(String controller, String action) throws Status {
// TODO: if not AJAX
try {
request.getRequestDispatcher("/" + controller + "/" + action + ".jsp").forward(request, response);
} catch (Exception exception) {
throw new Status("Unable to render!", 500, exception);
}
}
public void redirect(String path) throws Status {
// TODO: if path.startsWith("/") add context path
try {
response.sendRedirect(path);
} catch (Exception exception) {
throw new Status("Unable to redirect!", 500, exception);
}
}
@Override
public String toString() {
return "{ route =>" + route + ", uri =>" + uri + ", method =>" + method + ", attributes =>" + attributes + "}";
}
}
| Now using .act as servlet mapping
| src/main/java/se/eostre/apistogramma/Environment.java | Now using .act as servlet mapping | <ide><path>rc/main/java/se/eostre/apistogramma/Environment.java
<ide> Environment(HttpServletRequest request, HttpServletResponse response) {
<ide> this.request = request;
<ide> this.response = response;
<del> uri = request.getPathInfo();
<add> uri = request.getServletPath().replace(".act", "");
<ide> method = request.getMethod().toLowerCase();
<ide> }
<ide>
<ide> public void render(String controller, String action) throws Status {
<ide> // TODO: if not AJAX
<ide> try {
<del> request.getRequestDispatcher("/" + controller + "/" + action + ".jsp").forward(request, response);
<add> request.getRequestDispatcher("/views/" + controller + "/" + action + ".jsp").forward(request, response);
<ide> } catch (Exception exception) {
<ide> throw new Status("Unable to render!", 500, exception);
<ide> }
<ide>
<ide> @Override
<ide> public String toString() {
<del> return "{ route =>" + route + ", uri =>" + uri + ", method =>" + method + ", attributes =>" + attributes + "}";
<add> return "{ uri => " + uri + ", method => " + method + ", attributes => " + attributes + "}";
<ide> }
<ide>
<ide> |
|
Java | mit | 7b52bf01da89733f2c5782c66dff89fd05d06778 | 0 | lewismcgeary/AndroidGameofLife | package io.github.lewismcgeary.androidgameoflife;
import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.GridLayout;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lewis on 17/11/15.
*/
public class LifeGridLayout extends GridLayout {
Context context;
AttributeSet attrs;
LifeCellView lifeCell;
float leftOrigin;
float topOrigin;
int cellPixelSize;
boolean bringingCellsToLife;
private GameStateCallback gameStateCallback;
int delayBeforeFabDisappears = getResources().getInteger(R.integer.delay_before_fab_disappears);
public LifeGridLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.attrs = attrs;
//this.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
}
public void setCallback(GameStateCallback callback){
gameStateCallback = callback;
}
public void initialiseLifeGridLayout(){
for (int x=0; x<getColumnCount(); x++){
for(int y=0; y<getRowCount(); y++){
lifeCell = new LifeCellView(context, attrs);
this.addView(lifeCell);
}
}
lifeCell = (LifeCellView) getChildAt(0);
final ViewTreeObserver.OnGlobalLayoutListener listener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
leftOrigin = lifeCell.getX();
topOrigin = lifeCell.getY();
cellPixelSize = lifeCell.getWidth();
}
};
lifeCell.getViewTreeObserver().addOnGlobalLayoutListener(listener);
/**lifeCell.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
leftOrigin = lifeCell.getX();
topOrigin = lifeCell.getY();
cellPixelSize = lifeCell.getWidth();
}
});*/
/**lifeCell.post(new Runnable() {
@Override
public void run() {
//after layout is drawn, use first cell as an anchor to work out any coordinates
leftOrigin = lifeCell.getX();
topOrigin = lifeCell.getY();
cellPixelSize = lifeCell.getWidth();
}
});*/
this.setOnTouchListener(new OnTouchListener() {
long touchStartTime;
long touchEventCurrentTime;
@Override
public boolean onTouch(View v, MotionEvent event) {
//if cellPixelSize is zero, grid has not been fully initialised so don't continue
//touch event
if (cellPixelSize == 0){
return false;
}
//calculate the grid position based on finger location on the screen
int xGridPosition = (int) (event.getX() - leftOrigin) / cellPixelSize;
int yGridPosition = (int) (event.getY() - topOrigin) / cellPixelSize;
//check that calculated positions are within range of grid
if (0 <= xGridPosition && xGridPosition < getColumnCount()
&& 0 <= yGridPosition && yGridPosition < getRowCount()) {
int touchedCellIndex = xGridPosition + yGridPosition * getColumnCount();
lifeCell = (LifeCellView) getChildAt(touchedCellIndex);
//each continuous touch movement will be either giving life to cells or killing them
//the first cell touched determines which action is being performed
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lifeCell.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
touchStartTime = SystemClock.elapsedRealtime();
if (lifeCell.isCellAlive()) {
lifeCell.makeCellViewDead();
bringingCellsToLife = false;
} else {
lifeCell.makeCellViewLive();
bringingCellsToLife = true;
}
return true;
case MotionEvent.ACTION_MOVE:
if (bringingCellsToLife) {
lifeCell.makeCellViewLive();
} else {
lifeCell.makeCellViewDead();
}
touchEventCurrentTime = SystemClock.elapsedRealtime();
//ensure series of short touch events don't cause button to repeatedly
//disappear and reappear, only sustained touch events trigger this
if(touchEventCurrentTime - touchStartTime > delayBeforeFabDisappears){
gameStateCallback.cellDrawingInProgress();
}
return true;
case MotionEvent.ACTION_UP:
gameStateCallback.cellDrawingFinished();
return false;
}
} else {
if(event.getAction() == MotionEvent.ACTION_UP){
gameStateCallback.cellDrawingFinished();
return false;
}
}
return true;
}
});
}
public List<GridCoordinates> getUserSetLiveCellCoordinates() {
List<GridCoordinates> userSelectedLiveCells = new ArrayList<>();
for (int i=0; i < getChildCount(); i++) {
lifeCell = (LifeCellView)getChildAt(i);
if(lifeCell.isCellAlive()){
int x = i % getColumnCount();
int y = i/getColumnCount();
userSelectedLiveCells.add(new GridCoordinates(x, y));
}
}
return userSelectedLiveCells;
}
public void setNewLiveCells(List<GridCoordinates> newLiveCells) {
List<Integer> indexOfLiveCells = new ArrayList<>();
for (int j=0; j<newLiveCells.size(); j++) {
indexOfLiveCells.add(newLiveCells.get(j).getX()+(getColumnCount()*newLiveCells.get(j).getY()));
}
for (int i=0; i < getChildCount(); i++) {
if (indexOfLiveCells.contains(i)) {
lifeCell = (LifeCellView)getChildAt(i);
lifeCell.makeCellViewLive();
} else {
lifeCell = (LifeCellView)getChildAt(i);
lifeCell.makeCellViewDead();
}
}
}
public void killAllCells(){
for(int i=0; i<getChildCount(); i++) {
lifeCell = (LifeCellView)getChildAt(i);
lifeCell.makeCellViewDead();
}
}
public void noCellsWereSelected(){
gameStateCallback.noCellsWereSelected();
}
public void cellsDiedGameOver(){
gameStateCallback.gameOver();
}
//can disable this as no scrolling needed
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
}
| app/src/main/java/io/github/lewismcgeary/androidgameoflife/LifeGridLayout.java | package io.github.lewismcgeary.androidgameoflife;
import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.GridLayout;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lewis on 17/11/15.
*/
public class LifeGridLayout extends GridLayout {
Context context;
AttributeSet attrs;
LifeCellView lifeCell;
float leftOrigin;
float topOrigin;
int cellPixelSize;
boolean bringingCellsToLife;
private GameStateCallback gameStateCallback;
int delayBeforeFabDisappears = getResources().getInteger(R.integer.delay_before_fab_disappears);
public LifeGridLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.attrs = attrs;
//this.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
}
public void setCallback(GameStateCallback callback){
gameStateCallback = callback;
}
public void initialiseLifeGridLayout(){
for (int x=0; x<getColumnCount(); x++){
for(int y=0; y<getRowCount(); y++){
lifeCell = new LifeCellView(context, attrs);
this.addView(lifeCell);
}
}
lifeCell = (LifeCellView) getChildAt(0);
final ViewTreeObserver.OnGlobalLayoutListener listener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
leftOrigin = lifeCell.getX();
topOrigin = lifeCell.getY();
cellPixelSize = lifeCell.getWidth();
}
};
lifeCell.getViewTreeObserver().addOnGlobalLayoutListener(listener);
/**lifeCell.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
leftOrigin = lifeCell.getX();
topOrigin = lifeCell.getY();
cellPixelSize = lifeCell.getWidth();
}
});*/
/**lifeCell.post(new Runnable() {
@Override
public void run() {
//after layout is drawn, use first cell as an anchor to work out any coordinates
leftOrigin = lifeCell.getX();
topOrigin = lifeCell.getY();
cellPixelSize = lifeCell.getWidth();
}
});*/
this.setOnTouchListener(new OnTouchListener() {
long touchStartTime;
long touchEventCurrentTime;
@Override
public boolean onTouch(View v, MotionEvent event) {
//calculate the grid position based on finger location on the screen
int xGridPosition = (int) (event.getX() - leftOrigin) / cellPixelSize;
int yGridPosition = (int) (event.getY() - topOrigin) / cellPixelSize;
//check that calculated positions are within range of grid
if (0 <= xGridPosition && xGridPosition < getColumnCount()
&& 0 <= yGridPosition && yGridPosition < getRowCount()) {
int touchedCellIndex = xGridPosition + yGridPosition * getColumnCount();
lifeCell = (LifeCellView) getChildAt(touchedCellIndex);
//each continuous touch movement will be either giving life to cells or killing them
//the first cell touched determines which action is being performed
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lifeCell.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
touchStartTime = SystemClock.elapsedRealtime();
if (lifeCell.isCellAlive()) {
lifeCell.makeCellViewDead();
bringingCellsToLife = false;
} else {
lifeCell.makeCellViewLive();
bringingCellsToLife = true;
}
return true;
case MotionEvent.ACTION_MOVE:
if (bringingCellsToLife) {
lifeCell.makeCellViewLive();
} else {
lifeCell.makeCellViewDead();
}
touchEventCurrentTime = SystemClock.elapsedRealtime();
//ensure series of short touch events don't cause button to repeatedly
//disappear and reappear, only sustained touch events trigger this
if(touchEventCurrentTime - touchStartTime > delayBeforeFabDisappears){
gameStateCallback.cellDrawingInProgress();
}
return true;
case MotionEvent.ACTION_UP:
gameStateCallback.cellDrawingFinished();
return false;
}
} else {
if(event.getAction() == MotionEvent.ACTION_UP){
gameStateCallback.cellDrawingFinished();
return false;
}
}
return true;
}
});
}
public List<GridCoordinates> getUserSetLiveCellCoordinates() {
List<GridCoordinates> userSelectedLiveCells = new ArrayList<>();
for (int i=0; i < getChildCount(); i++) {
lifeCell = (LifeCellView)getChildAt(i);
if(lifeCell.isCellAlive()){
int x = i % getColumnCount();
int y = i/getColumnCount();
userSelectedLiveCells.add(new GridCoordinates(x, y));
}
}
return userSelectedLiveCells;
}
public void setNewLiveCells(List<GridCoordinates> newLiveCells) {
List<Integer> indexOfLiveCells = new ArrayList<>();
for (int j=0; j<newLiveCells.size(); j++) {
indexOfLiveCells.add(newLiveCells.get(j).getX()+(getColumnCount()*newLiveCells.get(j).getY()));
}
for (int i=0; i < getChildCount(); i++) {
if (indexOfLiveCells.contains(i)) {
lifeCell = (LifeCellView)getChildAt(i);
lifeCell.makeCellViewLive();
} else {
lifeCell = (LifeCellView)getChildAt(i);
lifeCell.makeCellViewDead();
}
}
}
public void killAllCells(){
for(int i=0; i<getChildCount(); i++) {
lifeCell = (LifeCellView)getChildAt(i);
lifeCell.makeCellViewDead();
}
}
public void noCellsWereSelected(){
gameStateCallback.noCellsWereSelected();
}
public void cellsDiedGameOver(){
gameStateCallback.gameOver();
}
//can disable this as no scrolling needed
@Override
public boolean shouldDelayChildPressedState() {
return false;
}
}
| add check to grids touchlistener to make sure grid is initialised before any actions attempted
| app/src/main/java/io/github/lewismcgeary/androidgameoflife/LifeGridLayout.java | add check to grids touchlistener to make sure grid is initialised before any actions attempted | <ide><path>pp/src/main/java/io/github/lewismcgeary/androidgameoflife/LifeGridLayout.java
<ide> long touchEventCurrentTime;
<ide> @Override
<ide> public boolean onTouch(View v, MotionEvent event) {
<add> //if cellPixelSize is zero, grid has not been fully initialised so don't continue
<add> //touch event
<add> if (cellPixelSize == 0){
<add> return false;
<add> }
<ide> //calculate the grid position based on finger location on the screen
<ide> int xGridPosition = (int) (event.getX() - leftOrigin) / cellPixelSize;
<ide> int yGridPosition = (int) (event.getY() - topOrigin) / cellPixelSize; |
|
JavaScript | mit | a1228c9f2b262079f4e597358626c49009de7aaf | 0 | nicroto/viktor,nicroto/viktor,eriser/viktor,nicroto/viktor,eriser/viktor,eriser/viktor | 'use strict';
module.exports = {
DEFAULT_PITCH_SETTINGS: {
bend: 0
},
DEFAULT_REVERB_SETTINGS: {
level: 0
},
TUNA_REVERB_DEFAULT_SETTINGS: {
highCut: 22050,
lowCut: 20,
dryLevel: 1,
wetLevel: 0,
level: 1,
impulse: "impulses/impulse_rev.wav",
bypass: 0
}
}; | src/app/daw/engine/const.js | 'use strict';
module.exports = {
DEFAULT_PITCH_SETTINGS: {
bend: 0
},
DEFAULT_REVERB_SETTINGS: {
level: 0
},
TUNA_REVERB_DEFAULT_SETTINGS: {
highCut: 22050,
lowCut: 20,
dryLevel: 1,
wetLevel: 0,
level: 1,
impulse: "/impulses/impulse_rev.wav",
bypass: 0
}
}; | Fix: path to tuna impulses shouldn't start from root.
| src/app/daw/engine/const.js | Fix: path to tuna impulses shouldn't start from root. | <ide><path>rc/app/daw/engine/const.js
<ide> dryLevel: 1,
<ide> wetLevel: 0,
<ide> level: 1,
<del> impulse: "/impulses/impulse_rev.wav",
<add> impulse: "impulses/impulse_rev.wav",
<ide> bypass: 0
<ide> }
<ide> |
|
Java | apache-2.0 | d60e0e45a57a56e1dad6ae9e80aaa7d9f67ddd3c | 0 | eamonnmcmanus/javapoet,ThirdProject/android_external_square_javawriter,studyfordream/javapoet,auke-/javawriter,leorric/javawriter,sitexa/javapoet,leorric/javawriter,sitexa/javapoet,DirtyUnicorns/android_external_square_javawriter,gk5885/javawriter,ks94/javapoet,DirtyUnicorns/android_external_square_javawriter,rajatguptarg/javapoet,ben-manes/javapoet,byterom/android_external_square_javawriter,auke-/javawriter,ponsonio/javapoet,ThirdProject/android_external_square_javawriter,DanielSerdyukov/javapoet,PAC-ROM/android_external_square_javawriter,ben-manes/javapoet,studyfordream/javapoet,square/javawriter,rajatguptarg/javapoet,sormuras/javapoet,mumer92/javapoet,square/kotlinpoet,sormuras/javapoet,DanielSerdyukov/javapoet,eamonnmcmanus/javapoet,ponsonio/javapoet,mumer92/javapoet,square/javapoet,square/kotlinpoet,ks94/javapoet,byterom/android_external_square_javawriter,kenzierocks/javapoet,kenzierocks/javapoet,APaloski/javapoet,gk5885/javawriter,PAC-ROM/android_external_square_javawriter,APaloski/javapoet | // Copyright 2013 Square, Inc.
package com.squareup.java;
import com.example.Binding;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
public final class JavaWriterTest {
private final StringWriter stringWriter = new StringWriter();
private final JavaWriter javaWriter = new JavaWriter(stringWriter);
@Test public void typeDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void enumDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "enum", Modifier.PUBLIC);
javaWriter.emitEnumValue("BAR");
javaWriter.emitEnumValue("BAZ");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public enum Foo {\n"
+ " BAR,\n"
+ " BAZ,\n"
+ "}\n");
}
@Test public void fieldDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.emitField("java.lang.String", "string", Modifier.PRIVATE | Modifier.STATIC);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " private static String string;\n"
+ "}\n");
}
@Test public void fieldDeclarationWithInitialValue() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.emitField("java.lang.String", "string", 0, "\"bar\" + \"baz\"");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " String string = \"bar\" + \"baz\";\n"
+ "}\n");
}
@Test public void abstractMethodDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("java.lang.String", "foo", Modifier.ABSTRACT | Modifier.PUBLIC,
"java.lang.Object", "object", "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public abstract String foo(Object object, String s);\n"
+ "}\n");
}
@Test public void nonAbstractMethodDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " }\n"
+ "}\n");
}
@Test public void constructorDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod(null, "com.squareup.Foo", Modifier.PUBLIC, "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public Foo(String s) {\n"
+ " }\n"
+ "}\n");
}
@Test public void statement() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " int j = s.length() + 13;\n"
+ " }\n"
+ "}\n");
}
@Test public void statementPrecededByComment() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.emitEndOfLineComment("foo");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " // foo\n"
+ " int j = s.length() + 13;\n"
+ " }\n"
+ "}\n");
}
@Test public void multiLineStatement() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Triangle", "class", 0);
javaWriter.beginMethod("double", "pythagorean", 0, "int", "a", "int", "b");
javaWriter.emitStatement("int cSquared = a * a\n+ b * b");
javaWriter.emitStatement("return Math.sqrt(cSquared)");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Triangle {\n"
+ " double pythagorean(int a, int b) {\n"
+ " int cSquared = a * a\n"
+ " + b * b;\n"
+ " return Math.sqrt(cSquared);\n"
+ " }\n"
+ "}\n");
}
@Test public void addImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("java.util.ArrayList");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.emitField("java.util.ArrayList", "list", 0, "new java.util.ArrayList()");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import java.util.ArrayList;\n"
+ "public final class Foo {\n"
+ " ArrayList list = new java.util.ArrayList();\n"
+ "}\n");
}
@Test public void addStaticImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports("java.lang.System.getProperty");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.emitField("String", "bar", 0, "getProperty(\"bar\")");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import static java.lang.System.getProperty;\n"
+ "public final class Foo {\n"
+ " String bar = getProperty(\"bar\");\n"
+ "}\n");
}
@Test public void addStaticWildcardImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports("java.lang.System.*");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.emitField("String", "bar", 0, "getProperty(\"bar\")");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import static java.lang.System.*;\n"
+ "public final class Foo {\n"
+ " String bar = getProperty(\"bar\");\n"
+ "}\n");
}
@Test public void emptyImports() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports(Collections.<String>emptyList());
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void emptyStaticImports() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports(Collections.<String>emptyList());
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void addImportFromSubpackage() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.emitField("com.squareup.bar.Baz", "baz", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ " com.squareup.bar.Baz baz;\n"
+ "}\n");
}
@Test public void ifControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.beginControlFlow("if (s.isEmpty())");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endControlFlow();
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " if (s.isEmpty()) {\n"
+ " int j = s.length() + 13;\n"
+ " }\n"
+ " }\n"
+ "}\n");
}
@Test public void doWhileControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.beginControlFlow("do");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endControlFlow("while (s.isEmpty())");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " do {\n"
+ " int j = s.length() + 13;\n"
+ " } while (s.isEmpty());\n"
+ " }\n"
+ "}\n");
}
@Test public void tryCatchFinallyControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.beginControlFlow("try");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.nextControlFlow("catch (RuntimeException e)");
javaWriter.emitStatement("e.printStackTrace()");
javaWriter.nextControlFlow("finally");
javaWriter.emitStatement("int k = %s", 13);
javaWriter.endControlFlow();
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " try {\n"
+ " int j = s.length() + 13;\n"
+ " } catch (RuntimeException e) {\n"
+ " e.printStackTrace();\n"
+ " } finally {\n"
+ " int k = 13;\n"
+ " }\n"
+ " }\n"
+ "}\n");
}
@Test public void annotatedType() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("javax.inject.Singleton");
javaWriter.emitAnnotation("javax.inject.Singleton");
javaWriter.emitAnnotation(SuppressWarnings.class,
JavaWriter.stringLiteral("unchecked"));
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import javax.inject.Singleton;\n"
+ "@Singleton\n"
+ "@SuppressWarnings(\"unchecked\")\n"
+ "class Foo {\n"
+ "}\n");
}
@Test public void annotatedMember() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.emitAnnotation(Deprecated.class);
javaWriter.emitField("java.lang.String", "s", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " @Deprecated\n"
+ " String s;\n"
+ "}\n");
}
@Test public void annotatedWithAttributes() throws IOException {
Map<String, Object> attributes = new LinkedHashMap<String, Object>();
attributes.put("overrides", true);
attributes.put("entryPoints", new Object[] { "entryPointA", "entryPointB", "entryPointC" });
attributes.put("staticInjections", "com.squareup.Quux");
javaWriter.emitPackage("com.squareup");
javaWriter.emitAnnotation("Module", attributes);
javaWriter.beginType("com.squareup.FooModule", "class", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "@Module(\n"
+ " overrides = true,\n"
+ " entryPoints = {\n"
+ " entryPointA,\n"
+ " entryPointB,\n"
+ " entryPointC\n"
+ " },\n"
+ " staticInjections = com.squareup.Quux\n"
+ ")\n"
+ "class FooModule {\n"
+ "}\n");
}
@Test public void parameterizedType() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("java.util.Map", "java.util.Date");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.emitField("java.util.Map<java.lang.String, java.util.Date>", "map", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import java.util.Date;\n"
+ "import java.util.Map;\n"
+ "class Foo {\n"
+ " Map<String, Date> map;\n"
+ "}\n");
}
@Test public void eolComment() throws IOException {
javaWriter.emitEndOfLineComment("foo");
assertCode(""
+ "// foo\n");
}
@Test public void javadoc() throws IOException {
javaWriter.emitJavadoc("foo");
assertCode(""
+ "/**\n"
+ " * foo\n"
+ " */\n");
}
@Test public void multilineJavadoc() throws IOException {
javaWriter.emitJavadoc("0123456789 0123456789 0123456789 0123456789 0123456789 0123456789\n"
+ "0123456789 0123456789 0123456789 0123456789");
assertCode(""
+ "/**\n"
+ " * 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789\n"
+ " * 0123456789 0123456789 0123456789 0123456789\n"
+ " */\n");
}
@Test public void testStringLiteral() {
assertThat(JavaWriter.stringLiteral("")).isEqualTo("\"\"");
assertThat(JavaWriter.stringLiteral("JavaWriter")).isEqualTo("\"JavaWriter\"");
assertThat(JavaWriter.stringLiteral("\\")).isEqualTo("\"\\\\\"");
assertThat(JavaWriter.stringLiteral("\"")).isEqualTo("\"\\\"\"");
assertThat(JavaWriter.stringLiteral("\t")).isEqualTo("\"\\\t\"");
assertThat(JavaWriter.stringLiteral("\n")).isEqualTo("\"\\\n\"");
}
@Test public void testType() {
assertThat(JavaWriter.type(String.class)).as("simple type").isEqualTo("java.lang.String");
assertThat(JavaWriter.type(Set.class)).as("raw type").isEqualTo("java.util.Set");
assertThat(JavaWriter.type(Set.class, "?")).as("wildcard type").isEqualTo("java.util.Set<?>");
assertThat(JavaWriter.type(Map.class, JavaWriter.type(String.class), "?"))
.as("mixed type and wildcard generic type parameters")
.isEqualTo("java.util.Map<java.lang.String, ?>");
try {
JavaWriter.type(String.class, "foo");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("parameterized non-generic").isInstanceOf(IllegalArgumentException.class);
}
try {
JavaWriter.type(Map.class, "foo");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("too few type arguments").isInstanceOf(IllegalArgumentException.class);
}
try {
JavaWriter.type(Set.class, "foo", "bar");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("too many type arguments").isInstanceOf(IllegalArgumentException.class);
}
}
@Test public void compressType() throws IOException {
javaWriter.emitPackage("blah");
javaWriter.emitImports(Set.class.getCanonicalName(), Binding.class.getCanonicalName());
String actual = javaWriter.compressType("java.util.Set<com.example.Binding<blah.Foo.Blah>>");
assertThat(actual).isEqualTo("Set<Binding<Foo.Blah>>");
}
@Test public void compressDeeperType() throws IOException {
javaWriter.emitPackage("blah");
javaWriter.emitImports(Binding.class.getCanonicalName());
String actual = javaWriter.compressType("com.example.Binding<blah.foo.Foo.Blah>");
assertThat(actual).isEqualTo("Binding<blah.foo.Foo.Blah>");
}
@Test public void compressWildcardType() throws IOException {
javaWriter.emitPackage("blah");
javaWriter.emitImports(Binding.class.getCanonicalName());
String actual = javaWriter.compressType("com.example.Binding<? extends blah.Foo.Blah>");
assertThat(actual).isEqualTo("Binding<? extends Foo.Blah>");
}
@Test public void compressSimpleNameCollisionInSamePackage() throws IOException {
javaWriter.emitPackage("denominator");
javaWriter.emitImports("javax.inject.Provider", "dagger.internal.Binding");
String actual = javaWriter.compressType("dagger.internal.Binding<denominator.Provider>");
assertThat(actual).isEqualTo("Binding<denominator.Provider>");
}
private void assertCode(String expected) {
assertThat(stringWriter.toString()).isEqualTo(expected);
}
}
| src/test/java/com/squareup/java/JavaWriterTest.java | // Copyright 2013 Square, Inc.
package com.squareup.java;
import com.example.Binding;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
public final class JavaWriterTest {
private final StringWriter stringWriter = new StringWriter();
private final JavaWriter javaWriter = new JavaWriter(stringWriter);
@Test public void typeDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void enumDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "enum", Modifier.PUBLIC);
javaWriter.emitEnumValue("BAR");
javaWriter.emitEnumValue("BAZ");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public enum Foo {\n"
+ " BAR,\n"
+ " BAZ,\n"
+ "}\n");
}
@Test public void fieldDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.emitField("java.lang.String", "string", Modifier.PRIVATE | Modifier.STATIC);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " private static String string;\n"
+ "}\n");
}
@Test public void fieldDeclarationWithInitialValue() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.emitField("java.lang.String", "string", 0, "\"bar\" + \"baz\"");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " String string = \"bar\" + \"baz\";\n"
+ "}\n");
}
@Test public void abstractMethodDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("java.lang.String", "foo", Modifier.ABSTRACT | Modifier.PUBLIC,
"java.lang.Object", "object", "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public abstract String foo(Object object, String s);\n"
+ "}\n");
}
@Test public void nonAbstractMethodDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " }\n"
+ "}\n");
}
@Test public void constructorDeclaration() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod(null, "com.squareup.Foo", Modifier.PUBLIC, "java.lang.String", "s");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " public Foo(String s) {\n"
+ " }\n"
+ "}\n");
}
@Test public void statement() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " int j = s.length() + 13;\n"
+ " }\n"
+ "}\n");
}
@Test public void statementFollowedByComment() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.emitEndOfLineComment("foo");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " int j = s.length() + 13;\n"
+ " // foo\n"
+ " }\n"
+ "}\n");
}
@Test public void multiLineStatement() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Triangle", "class", 0);
javaWriter.beginMethod("double", "pythagorean", 0, "int", "a", "int", "b");
javaWriter.emitStatement("int cSquared = a * a\n+ b * b");
javaWriter.emitStatement("return Math.sqrt(cSquared)");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Triangle {\n"
+ " double pythagorean(int a, int b) {\n"
+ " int cSquared = a * a\n"
+ " + b * b;\n"
+ " return Math.sqrt(cSquared);\n"
+ " }\n"
+ "}\n");
}
@Test public void addImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("java.util.ArrayList");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.emitField("java.util.ArrayList", "list", 0, "new java.util.ArrayList()");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import java.util.ArrayList;\n"
+ "public final class Foo {\n"
+ " ArrayList list = new java.util.ArrayList();\n"
+ "}\n");
}
@Test public void addStaticImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports("java.lang.System.getProperty");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.emitField("String", "bar", 0, "getProperty(\"bar\")");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import static java.lang.System.getProperty;\n"
+ "public final class Foo {\n"
+ " String bar = getProperty(\"bar\");\n"
+ "}\n");
}
@Test public void addStaticWildcardImport() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports("java.lang.System.*");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.emitField("String", "bar", 0, "getProperty(\"bar\")");
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import static java.lang.System.*;\n"
+ "public final class Foo {\n"
+ " String bar = getProperty(\"bar\");\n"
+ "}\n");
}
@Test public void emptyImports() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports(Collections.<String>emptyList());
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void emptyStaticImports() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitStaticImports(Collections.<String>emptyList());
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ "}\n");
}
@Test public void addImportFromSubpackage() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", Modifier.PUBLIC | Modifier.FINAL);
javaWriter.emitField("com.squareup.bar.Baz", "baz", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "public final class Foo {\n"
+ " com.squareup.bar.Baz baz;\n"
+ "}\n");
}
@Test public void ifControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.beginControlFlow("if (s.isEmpty())");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endControlFlow();
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " if (s.isEmpty()) {\n"
+ " int j = s.length() + 13;\n"
+ " }\n"
+ " }\n"
+ "}\n");
}
@Test public void doWhileControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.beginControlFlow("do");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.endControlFlow("while (s.isEmpty())");
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " do {\n"
+ " int j = s.length() + 13;\n"
+ " } while (s.isEmpty());\n"
+ " }\n"
+ "}\n");
}
@Test public void tryCatchFinallyControlFlow() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
javaWriter.beginControlFlow("try");
javaWriter.emitStatement("int j = s.length() + %s", 13);
javaWriter.nextControlFlow("catch (RuntimeException e)");
javaWriter.emitStatement("e.printStackTrace()");
javaWriter.nextControlFlow("finally");
javaWriter.emitStatement("int k = %s", 13);
javaWriter.endControlFlow();
javaWriter.endMethod();
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " int foo(String s) {\n"
+ " try {\n"
+ " int j = s.length() + 13;\n"
+ " } catch (RuntimeException e) {\n"
+ " e.printStackTrace();\n"
+ " } finally {\n"
+ " int k = 13;\n"
+ " }\n"
+ " }\n"
+ "}\n");
}
@Test public void annotatedType() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("javax.inject.Singleton");
javaWriter.emitAnnotation("javax.inject.Singleton");
javaWriter.emitAnnotation(SuppressWarnings.class,
JavaWriter.stringLiteral("unchecked"));
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import javax.inject.Singleton;\n"
+ "@Singleton\n"
+ "@SuppressWarnings(\"unchecked\")\n"
+ "class Foo {\n"
+ "}\n");
}
@Test public void annotatedMember() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.emitAnnotation(Deprecated.class);
javaWriter.emitField("java.lang.String", "s", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "class Foo {\n"
+ " @Deprecated\n"
+ " String s;\n"
+ "}\n");
}
@Test public void annotatedWithAttributes() throws IOException {
Map<String, Object> attributes = new LinkedHashMap<String, Object>();
attributes.put("overrides", true);
attributes.put("entryPoints", new Object[] { "entryPointA", "entryPointB", "entryPointC" });
attributes.put("staticInjections", "com.squareup.Quux");
javaWriter.emitPackage("com.squareup");
javaWriter.emitAnnotation("Module", attributes);
javaWriter.beginType("com.squareup.FooModule", "class", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "@Module(\n"
+ " overrides = true,\n"
+ " entryPoints = {\n"
+ " entryPointA,\n"
+ " entryPointB,\n"
+ " entryPointC\n"
+ " },\n"
+ " staticInjections = com.squareup.Quux\n"
+ ")\n"
+ "class FooModule {\n"
+ "}\n");
}
@Test public void parameterizedType() throws IOException {
javaWriter.emitPackage("com.squareup");
javaWriter.emitImports("java.util.Map", "java.util.Date");
javaWriter.beginType("com.squareup.Foo", "class", 0);
javaWriter.emitField("java.util.Map<java.lang.String, java.util.Date>", "map", 0);
javaWriter.endType();
assertCode(""
+ "package com.squareup;\n"
+ "\n"
+ "import java.util.Date;\n"
+ "import java.util.Map;\n"
+ "class Foo {\n"
+ " Map<String, Date> map;\n"
+ "}\n");
}
@Test public void eolComment() throws IOException {
javaWriter.emitEndOfLineComment("foo");
assertCode(""
+ "// foo\n");
}
@Test public void javadoc() throws IOException {
javaWriter.emitJavadoc("foo");
assertCode(""
+ "/**\n"
+ " * foo\n"
+ " */\n");
}
@Test public void multilineJavadoc() throws IOException {
javaWriter.emitJavadoc("0123456789 0123456789 0123456789 0123456789 0123456789 0123456789\n"
+ "0123456789 0123456789 0123456789 0123456789");
assertCode(""
+ "/**\n"
+ " * 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789\n"
+ " * 0123456789 0123456789 0123456789 0123456789\n"
+ " */\n");
}
@Test public void testStringLiteral() {
assertThat(JavaWriter.stringLiteral("")).isEqualTo("\"\"");
assertThat(JavaWriter.stringLiteral("JavaWriter")).isEqualTo("\"JavaWriter\"");
assertThat(JavaWriter.stringLiteral("\\")).isEqualTo("\"\\\\\"");
assertThat(JavaWriter.stringLiteral("\"")).isEqualTo("\"\\\"\"");
assertThat(JavaWriter.stringLiteral("\t")).isEqualTo("\"\\\t\"");
assertThat(JavaWriter.stringLiteral("\n")).isEqualTo("\"\\\n\"");
}
@Test public void testType() {
assertThat(JavaWriter.type(String.class)).as("simple type").isEqualTo("java.lang.String");
assertThat(JavaWriter.type(Set.class)).as("raw type").isEqualTo("java.util.Set");
assertThat(JavaWriter.type(Set.class, "?")).as("wildcard type").isEqualTo("java.util.Set<?>");
assertThat(JavaWriter.type(Map.class, JavaWriter.type(String.class), "?"))
.as("mixed type and wildcard generic type parameters")
.isEqualTo("java.util.Map<java.lang.String, ?>");
try {
JavaWriter.type(String.class, "foo");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("parameterized non-generic").isInstanceOf(IllegalArgumentException.class);
}
try {
JavaWriter.type(Map.class, "foo");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("too few type arguments").isInstanceOf(IllegalArgumentException.class);
}
try {
JavaWriter.type(Set.class, "foo", "bar");
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (Throwable e) {
assertThat(e).as("too many type arguments").isInstanceOf(IllegalArgumentException.class);
}
}
@Test public void compressType() throws IOException {
javaWriter.emitPackage("blah");
javaWriter.emitImports(Set.class.getCanonicalName(), Binding.class.getCanonicalName());
String actual = javaWriter.compressType("java.util.Set<com.example.Binding<blah.Foo.Blah>>");
assertThat(actual).isEqualTo("Set<Binding<Foo.Blah>>");
}
@Test public void compressDeeperType() throws IOException {
javaWriter.emitPackage("blah");
javaWriter.emitImports(Binding.class.getCanonicalName());
String actual = javaWriter.compressType("com.example.Binding<blah.foo.Foo.Blah>");
assertThat(actual).isEqualTo("Binding<blah.foo.Foo.Blah>");
}
@Test public void compressWildcardType() throws IOException {
javaWriter.emitPackage("blah");
javaWriter.emitImports(Binding.class.getCanonicalName());
String actual = javaWriter.compressType("com.example.Binding<? extends blah.Foo.Blah>");
assertThat(actual).isEqualTo("Binding<? extends Foo.Blah>");
}
@Test public void compressSimpleNameCollisionInSamePackage() throws IOException {
javaWriter.emitPackage("denominator");
javaWriter.emitImports("javax.inject.Provider", "dagger.internal.Binding");
String actual = javaWriter.compressType("dagger.internal.Binding<denominator.Provider>");
assertThat(actual).isEqualTo("Binding<denominator.Provider>");
}
private void assertCode(String expected) {
assertThat(stringWriter.toString()).isEqualTo(expected);
}
}
| updated test
| src/test/java/com/squareup/java/JavaWriterTest.java | updated test | <ide><path>rc/test/java/com/squareup/java/JavaWriterTest.java
<ide> + "}\n");
<ide> }
<ide>
<del> @Test public void statementFollowedByComment() throws IOException {
<del> javaWriter.emitPackage("com.squareup");
<del> javaWriter.beginType("com.squareup.Foo", "class", 0);
<del> javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
<add> @Test public void statementPrecededByComment() throws IOException {
<add> javaWriter.emitPackage("com.squareup");
<add> javaWriter.beginType("com.squareup.Foo", "class", 0);
<add> javaWriter.beginMethod("int", "foo", 0, "java.lang.String", "s");
<add> javaWriter.emitEndOfLineComment("foo");
<ide> javaWriter.emitStatement("int j = s.length() + %s", 13);
<del> javaWriter.emitEndOfLineComment("foo");
<del> javaWriter.endMethod();
<del> javaWriter.endType();
<del> assertCode(""
<del> + "package com.squareup;\n"
<del> + "\n"
<del> + "class Foo {\n"
<del> + " int foo(String s) {\n"
<add> javaWriter.endMethod();
<add> javaWriter.endType();
<add> assertCode(""
<add> + "package com.squareup;\n"
<add> + "\n"
<add> + "class Foo {\n"
<add> + " int foo(String s) {\n"
<add> + " // foo\n"
<ide> + " int j = s.length() + 13;\n"
<del> + " // foo\n"
<ide> + " }\n"
<ide> + "}\n");
<ide> } |
|
Java | bsd-3-clause | 81bff65f2fdec735c8cd2ff7a48ad6b02c7939af | 0 | krzyk/rultor,pecko/rultor,linlihai/rultor,joansmith/rultor,joansmith/rultor,joansmith/rultor,dalifreire/rultor,dalifreire/rultor,maurezen/rultor,linlihai/rultor,maurezen/rultor,linlihai/rultor,maurezen/rultor,pecko/rultor,pecko/rultor,dalifreire/rultor,joansmith/rultor,joansmith/rultor,dalifreire/rultor,pecko/rultor,linlihai/rultor,krzyk/rultor,pecko/rultor,krzyk/rultor,dalifreire/rultor,maurezen/rultor,maurezen/rultor,krzyk/rultor,linlihai/rultor,krzyk/rultor | /**
* Copyright (c) 2009-2014, rultor.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.agents.github;
import com.google.common.collect.Iterables;
import com.jcabi.aspects.Immutable;
import com.jcabi.github.Bulk;
import com.jcabi.github.Comment;
import com.jcabi.github.Github;
import com.jcabi.github.Issue;
import com.jcabi.github.Smarts;
import com.jcabi.log.Logger;
import com.jcabi.xml.XML;
import com.rultor.agents.AbstractAgent;
import com.rultor.agents.daemons.Home;
import com.rultor.spi.Profile;
import java.io.IOException;
import java.util.Collections;
import java.util.ResourceBundle;
import javax.json.Json;
import javax.json.JsonObject;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.xembly.Directive;
import org.xembly.Directives;
/**
* Understands request.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 1.3
*/
@Immutable
@ToString
@EqualsAndHashCode(callSuper = false, of = { "github", "question" })
@SuppressWarnings("PMD.CyclomaticComplexity")
public final class Understands extends AbstractAgent {
/**
* Message bundle.
*/
private static final ResourceBundle PHRASES =
ResourceBundle.getBundle("phrases");
/**
* Github.
*/
private final transient Github github;
/**
* Question.
*/
private final transient Question question;
/**
* Ctor.
* @param ghub Github client
* @param qtn Question
*/
public Understands(final Github ghub, final Question qtn) {
super(
"/talk[@later='true']",
"/talk/wire[github-repo and github-issue]"
);
this.github = ghub;
this.question = qtn;
}
// @checkstyle ExecutableStatementCountCheck (50 lines)
@Override
public Iterable<Directive> process(final XML xml) throws IOException {
final Issue.Smart issue = new TalkIssues(this.github, xml).get();
final Iterable<Comment.Smart> comments = new Smarts<Comment.Smart>(
Iterables.concat(
Collections.singleton(Understands.asComment(issue)),
new Bulk<Comment>(issue.comments().iterate())
)
);
final int seen = Understands.seen(xml);
int next = seen;
int fresh = 0;
int total = 0;
Req req = Req.EMPTY;
for (final Comment.Smart comment : comments) {
++total;
if (comment.number() <= seen) {
continue;
}
++fresh;
req = this.parse(comment, xml);
if (req.equals(Req.LATER)) {
break;
}
next = comment.number();
if (!req.equals(Req.EMPTY)) {
break;
}
}
if (next < seen) {
throw new IllegalStateException(
String.format(
"comment #%d is younger than #%d, something is wrong",
next, seen
)
);
}
final Directives dirs = new Directives();
if (req.equals(Req.EMPTY)) {
Logger.info(
this, "nothing new in %s#%d, fresh/total: %d/%d",
issue.repo().coordinates(), issue.number(), fresh, total
);
} else if (req.equals(Req.DONE)) {
Logger.info(
this, "simple request in %s#%d",
issue.repo().coordinates(), issue.number()
);
} else if (req.equals(Req.LATER)) {
Logger.info(
this, "temporary pause in %s#%d, at message #%d",
issue.repo().coordinates(), issue.number(), next
);
} else {
dirs.xpath("/talk[not(request)]").strict(1).add("request")
.attr("id", Integer.toString(next))
.append(req.dirs());
}
if (next > seen) {
dirs.xpath("/talk/wire")
.addIf("github-seen")
.set(Integer.toString(next));
}
return dirs.xpath("/talk")
.attr("later", Boolean.toString(!req.equals(Req.EMPTY)));
}
/**
* Understand.
* @param comment Comment
* @param xml XML
* @return Req
* @throws IOException If fails
*/
private Req parse(final Comment.Smart comment, final XML xml)
throws IOException {
Req req;
try {
req = this.question.understand(
comment, new Home(xml, Integer.toString(comment.number())).uri()
);
} catch (final Profile.ConfigException ex) {
new Answer(comment).post(
String.format(
Understands.PHRASES.getString("Understands.broken-profile"),
ExceptionUtils.getRootCauseMessage(ex)
)
);
req = Req.EMPTY;
}
return req;
}
/**
* Last seen message.
* @param xml XML
* @return Number
*/
private static int seen(final XML xml) {
final int seen;
if (xml.nodes("/talk/wire/github-seen").isEmpty()) {
seen = 0;
} else {
seen = Integer.parseInt(
xml.xpath("/talk/wire/github-seen/text()").get(0)
);
}
return seen;
}
/**
* Make a message from issue's body.
* @param issue The issue
* @return Comment
*/
private static Comment asComment(final Issue.Smart issue) {
// @checkstyle AnonInnerLengthCheck (50 lines)
return new Comment() {
@Override
public Issue issue() {
return issue;
}
@Override
public int number() {
return 1;
}
@Override
public void remove() {
throw new UnsupportedOperationException("#remove()");
}
@Override
public int compareTo(final Comment comment) {
return 1;
}
@Override
public void patch(final JsonObject json) {
throw new UnsupportedOperationException("#patch()");
}
@Override
public JsonObject json() throws IOException {
return Json.createObjectBuilder()
.add("body", issue.body())
.add(
"user",
Json.createObjectBuilder().add(
"login", issue.author().login()
)
)
.build();
}
};
}
}
| src/main/java/com/rultor/agents/github/Understands.java | /**
* Copyright (c) 2009-2014, rultor.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.agents.github;
import com.google.common.collect.Iterables;
import com.jcabi.aspects.Immutable;
import com.jcabi.github.Bulk;
import com.jcabi.github.Comment;
import com.jcabi.github.Github;
import com.jcabi.github.Issue;
import com.jcabi.github.Smarts;
import com.jcabi.log.Logger;
import com.jcabi.xml.XML;
import com.rultor.agents.AbstractAgent;
import com.rultor.agents.daemons.Home;
import com.rultor.spi.Profile;
import java.io.IOException;
import java.util.Collections;
import java.util.ResourceBundle;
import javax.json.Json;
import javax.json.JsonObject;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.xembly.Directive;
import org.xembly.Directives;
/**
* Understands request.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 1.3
*/
@Immutable
@ToString
@EqualsAndHashCode(callSuper = false, of = { "github", "question" })
public final class Understands extends AbstractAgent {
/**
* Message bundle.
*/
private static final ResourceBundle PHRASES =
ResourceBundle.getBundle("phrases");
/**
* Github.
*/
private final transient Github github;
/**
* Question.
*/
private final transient Question question;
/**
* Ctor.
* @param ghub Github client
* @param qtn Question
*/
public Understands(final Github ghub, final Question qtn) {
super(
"/talk[@later='true']",
"/talk/wire[github-repo and github-issue]"
);
this.github = ghub;
this.question = qtn;
}
// @checkstyle ExecutableStatementCountCheck (50 lines)
@Override
public Iterable<Directive> process(final XML xml) throws IOException {
final Issue.Smart issue = new TalkIssues(this.github, xml).get();
final Iterable<Comment.Smart> comments = new Smarts<Comment.Smart>(
Iterables.concat(
Collections.singleton(Understands.asComment(issue)),
new Bulk<Comment>(issue.comments().iterate())
)
);
final int seen = Understands.seen(xml);
int next = seen;
int fresh = 0;
int total = 0;
Req req = Req.EMPTY;
for (final Comment.Smart comment : comments) {
++total;
if (comment.number() <= seen) {
continue;
}
++fresh;
req = this.parse(comment, xml);
if (req.equals(Req.LATER)) {
break;
}
next = comment.number();
if (!req.equals(Req.EMPTY)) {
break;
}
}
final Directives dirs = new Directives();
if (req.equals(Req.EMPTY)) {
Logger.info(
this, "nothing new in %s#%d, fresh/total: %d/%d",
issue.repo().coordinates(), issue.number(), fresh, total
);
} else if (req.equals(Req.DONE)) {
Logger.info(
this, "simple request in %s#%d",
issue.repo().coordinates(), issue.number()
);
} else if (req.equals(Req.LATER)) {
Logger.info(
this, "temporary pause in %s#%d, at message #%d",
issue.repo().coordinates(), issue.number(), next
);
} else {
dirs.xpath("/talk[not(request)]").add("request")
.attr("id", Integer.toString(next))
.append(req.dirs());
}
if (next > seen) {
dirs.xpath("/talk/wire")
.addIf("github-seen")
.set(Integer.toString(next));
}
return dirs.xpath("/talk")
.attr("later", Boolean.toString(!req.equals(Req.EMPTY)));
}
/**
* Understand.
* @param comment Comment
* @param xml XML
* @return Req
* @throws IOException If fails
*/
private Req parse(final Comment.Smart comment, final XML xml)
throws IOException {
Req req;
try {
req = this.question.understand(
comment, new Home(xml, Integer.toString(comment.number())).uri()
);
} catch (final Profile.ConfigException ex) {
new Answer(comment).post(
String.format(
Understands.PHRASES.getString("Understands.broken-profile"),
ExceptionUtils.getRootCauseMessage(ex)
)
);
req = Req.EMPTY;
}
return req;
}
/**
* Last seen message.
* @param xml XML
* @return Number
*/
private static int seen(final XML xml) {
final int seen;
if (xml.nodes("/talk/wire/github-seen").isEmpty()) {
seen = 0;
} else {
seen = Integer.parseInt(
xml.xpath("/talk/wire/github-seen/text()").get(0)
);
}
return seen;
}
/**
* Make a message from issue's body.
* @param issue The issue
* @return Comment
*/
private static Comment asComment(final Issue.Smart issue) {
// @checkstyle AnonInnerLengthCheck (50 lines)
return new Comment() {
@Override
public Issue issue() {
return issue;
}
@Override
public int number() {
return 1;
}
@Override
public void remove() {
throw new UnsupportedOperationException("#remove()");
}
@Override
public int compareTo(final Comment comment) {
return 1;
}
@Override
public void patch(final JsonObject json) {
throw new UnsupportedOperationException("#patch()");
}
@Override
public JsonObject json() throws IOException {
return Json.createObjectBuilder()
.add("body", issue.body())
.add(
"user",
Json.createObjectBuilder().add(
"login", issue.author().login()
)
)
.build();
}
};
}
}
| #645 check for invalid comment numbers
| src/main/java/com/rultor/agents/github/Understands.java | #645 check for invalid comment numbers | <ide><path>rc/main/java/com/rultor/agents/github/Understands.java
<ide> @Immutable
<ide> @ToString
<ide> @EqualsAndHashCode(callSuper = false, of = { "github", "question" })
<add>@SuppressWarnings("PMD.CyclomaticComplexity")
<ide> public final class Understands extends AbstractAgent {
<ide>
<ide> /**
<ide> break;
<ide> }
<ide> }
<add> if (next < seen) {
<add> throw new IllegalStateException(
<add> String.format(
<add> "comment #%d is younger than #%d, something is wrong",
<add> next, seen
<add> )
<add> );
<add> }
<ide> final Directives dirs = new Directives();
<ide> if (req.equals(Req.EMPTY)) {
<ide> Logger.info(
<ide> issue.repo().coordinates(), issue.number(), next
<ide> );
<ide> } else {
<del> dirs.xpath("/talk[not(request)]").add("request")
<add> dirs.xpath("/talk[not(request)]").strict(1).add("request")
<ide> .attr("id", Integer.toString(next))
<ide> .append(req.dirs());
<ide> } |
|
Java | apache-2.0 | 73d151275a618e5782fed108000440845c75f429 | 0 | jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2002-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.sandwell.JavaSimulation3D;
import static com.sandwell.JavaSimulation.Util.formatNumber;
import java.util.ArrayList;
import java.util.HashMap;
import com.jaamsim.input.InputAgent;
import com.jaamsim.math.Color4d;
import com.sandwell.JavaSimulation.BooleanInput;
import com.sandwell.JavaSimulation.BooleanListInput;
import com.sandwell.JavaSimulation.BooleanVector;
import com.sandwell.JavaSimulation.ColourInput;
import com.sandwell.JavaSimulation.DoubleInput;
import com.sandwell.JavaSimulation.DoubleListInput;
import com.sandwell.JavaSimulation.DoubleVector;
import com.sandwell.JavaSimulation.EntityInput;
import com.sandwell.JavaSimulation.EntityListInput;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.IntegerVector;
import com.sandwell.JavaSimulation.Keyword;
import com.sandwell.JavaSimulation.ProbabilityDistribution;
import com.sandwell.JavaSimulation.Process;
import com.sandwell.JavaSimulation.Tester;
import com.sandwell.JavaSimulation.Vector;
/**
* Class ModelEntity - JavaSimulation3D
*/
public class ModelEntity extends DisplayEntity {
// Breakdowns
@Keyword(desc = "Reliability is defined as:\n" +
" 100% - (plant breakdown time / total operation time)\n " +
"or\n " +
"(Operational Time)/(Breakdown + Operational Time)",
example = "Object1 Reliability { 0.95 }")
private final DoubleInput availability;
protected double hoursForNextFailure; // The number of working hours required before the next breakdown
protected double iATFailure; // inter arrival time between failures
protected boolean breakdownPending; // true when a breakdown is to occur
protected boolean brokendown; // true => entity is presently broken down
protected boolean maintenance; // true => entity is presently in maintenance
protected boolean associatedBreakdown; // true => entity is presently in Associated Breakdown
protected boolean associatedMaintenance; // true => entity is presently in Associated Maintenance
protected double breakdownStartTime; // Start time of the most recent breakdown
protected double breakdownEndTime; // End time of the most recent breakdown
// Breakdown Probability Distributions
@Keyword(desc = "A ProbabilityDistribution object that governs the duration of breakdowns (in hours).",
example = "Object1 DowntimeDurationDistribution { BreakdownProbDist1 }")
private final EntityInput<ProbabilityDistribution> downtimeDurationDistribution;
@Keyword(desc = "A ProbabilityDistribution object that governs when breakdowns occur (in hours).",
example = "Object1 DowntimeIATDistribution { BreakdownProbDist1 }")
private final EntityInput<ProbabilityDistribution> downtimeIATDistribution;
// Maintenance
@Keyword(desc = "The simulation time for the start of the first maintenance for each maintenance cycle.",
example = "Object1 FirstMaintenanceTime { 24 h }")
protected DoubleListInput firstMaintenanceTimes;
@Keyword(desc = "The time between maintenance activities for each maintenance cycle",
example = "Object1 MaintenanceInterval { 168 h }")
protected DoubleListInput maintenanceIntervals;
@Keyword(desc = "The durations of a single maintenance event for each maintenance cycle.",
example = "Object1 MaintenanceDuration { 336 h }")
protected DoubleListInput maintenanceDurations;
protected IntegerVector maintenancePendings; // Number of maintenance periods that are due
@Keyword(desc = "A Boolean value. Allows scheduled maintenances to be skipped if it overlaps " +
"with another planned maintenance event.",
example = "Object1 SkipMaintenanceIfOverlap { TRUE }")
protected BooleanListInput skipMaintenanceIfOverlap;
@Keyword(desc = "A list of objects that share the maintenance schedule with this object. " +
"In order for the maintenance to start, all objects on this list must be available." +
"This keyword is for Handlers and Signal Blocks only.",
example = "Block1 SharedMaintenance { Block2 Block2 }")
private final EntityListInput<ModelEntity> sharedMaintenanceList;
protected ModelEntity masterMaintenanceEntity; // The entity that has maintenance information
protected boolean performMaintenanceAfterShipDelayPending; // maintenance needs to be done after shipDelay
// Maintenance based on hours of operations
@Keyword(desc = "Working time for the start of the first maintenance for each maintenance cycle",
example = "Object1 FirstMaintenanceOperatingHours { 1000 2500 h }")
private final DoubleListInput firstMaintenanceOperatingHours;
@Keyword(desc = "Working time between one maintenance event and the next for each maintenance cycle",
example = "Object1 MaintenanceOperatingHoursIntervals { 2000 5000 h }")
private final DoubleListInput maintenanceOperatingHoursIntervals;
@Keyword(desc = "Duration of maintenance events based on working hours for each maintenance cycle",
example = "Ship1 MaintenanceOperatingHoursDurations { 24 48 h }")
private final DoubleListInput maintenanceOperatingHoursDurations;
protected IntegerVector maintenanceOperatingHoursPendings; // Number of maintenance periods that are due
protected DoubleVector hoursForNextMaintenanceOperatingHours;
protected double maintenanceStartTime; // Start time of the most recent maintenance
protected double maintenanceEndTime; // End time of the most recent maintenance
protected DoubleVector nextMaintenanceTimes; // next start time for each maintenance
protected double nextMaintenanceDuration; // duration for next maintenance
protected DoubleVector lastScheduledMaintenanceTimes;
@Keyword(desc = "If maintenance has been deferred by the DeferMaintenanceLookAhead keyword " +
"for longer than this time, the maintenance will start even if " +
"there is an object within the lookahead. There must be one entry for each " +
"defined maintenance schedule if DeferMaintenanceLookAhead is used. This" +
"keyword is only used for signal blocks.",
example = "Object1 DeferMaintenanceLimit { 50 50 h }")
private final DoubleListInput deferMaintenanceLimit;
@Keyword(desc = "If the duration of the downtime is longer than this time, equipment will be released",
example = "Object1 DowntimeToReleaseEquipment { 1.0 h }")
protected final DoubleInput downtimeToReleaseEquipment;
@Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is TRUE, " +
"then routes/tasks are released before performing the maintenance in the cycle.",
example = "Object1 ReleaseEquipment { TRUE FALSE FALSE }")
protected final BooleanListInput releaseEquipment;
@Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is " +
"TRUE, then maintenance in the cycle can start even if the equipment is presently " +
"working.",
example = "Object1 ForceMaintenance { TRUE FALSE FALSE }")
protected final BooleanListInput forceMaintenance;
// Statistics
@Keyword(desc = "If TRUE, then statistics for this object are " +
"included in the main output report.",
example = "Object1 PrintToReport { TRUE }")
private final BooleanInput printToReport;
// States
protected static Vector stateList = new Vector( 11, 1 ); // List of valid states
private final HashMap<String, StateRecord> stateMap;
protected double workingHours; // Accumulated working time spent in working states
protected DoubleVector hoursPerState; // Elapsed time to date for each state
private static class StateRecord {
String stateName;
int index;
double initializationHours;
double totalHours;
double completedCycleHours;
double currentCycleHours;
public StateRecord(String state, int i) {
stateName = state;
index = i;
}
public int getIndex() {
return index;
}
public String getStateName() {
return stateName;
}
public double getTotalHours() {
return totalHours;
}
public double getCompletedCycleHours() {
return completedCycleHours;
}
@Override
public String toString() {
return getStateName();
}
public void addHours(double dur) {
totalHours += dur;
currentCycleHours += dur;
}
public void collectInitializationStats() {
initializationHours = totalHours;
totalHours = 0.0d;
completedCycleHours = 0.0d;
}
public void collectCycleStats() {
completedCycleHours += currentCycleHours;
currentCycleHours = 0.0d;
}
public void clearReportStats() {
totalHours = 0.0d;
completedCycleHours = 0.0d;
}
public void clearCurrentCycleHours() {
currentCycleHours = 0.0d;
}
}
private double timeOfLastStateUpdate;
private int numberOfCompletedCycles;
protected double lastHistogramUpdateTime; // Last time at which a histogram was updated for this entity
protected double secondToLastHistogramUpdateTime; // Second to last time at which a histogram was updated for this entity
protected DoubleVector lastStartTimePerState; // Last time at which the state changed from some other state to each state
protected DoubleVector secondToLastStartTimePerState; // The second to last time at which the state changed from some other state to each state
private StateRecord presentState; // The present state of the entity
protected double timeOfLastStateChange; // Time at which the state was last changed
protected FileEntity stateReportFile; // The file to store the state information
private String finalLastState = ""; // The final state of the entity (in a sequence of transitional states)
private double timeOfLastPrintedState = 0; // The time that the last state printed in the trace state file
// Graphics
protected final static Color4d breakdownColor = ColourInput.DARK_RED; // Color of the entity in breaking down
protected final static Color4d maintenanceColor = ColourInput.RED; // Color of the entity in maintenance
static {
stateList.addElement( "Idle" );
stateList.addElement( "Working" );
stateList.addElement( "Breakdown" );
stateList.addElement( "Maintenance" );
}
{
maintenanceDurations = new DoubleListInput("MaintenanceDurations", "Maintenance", new DoubleVector());
maintenanceDurations.setValidRange(0.0d, Double.POSITIVE_INFINITY);
maintenanceDurations.setUnits("h");
this.addInput(maintenanceDurations, true, "MaintenanceDuration");
maintenanceIntervals = new DoubleListInput("MaintenanceIntervals", "Maintenance", new DoubleVector());
maintenanceIntervals.setValidRange(0.0d, Double.POSITIVE_INFINITY);
maintenanceIntervals.setUnits("h");
this.addInput(maintenanceIntervals, true, "MaintenanceInterval");
firstMaintenanceTimes = new DoubleListInput("FirstMaintenanceTimes", "Maintenance", new DoubleVector());
firstMaintenanceTimes.setValidRange(0.0d, Double.POSITIVE_INFINITY);
firstMaintenanceTimes.setUnits("h");
this.addInput(firstMaintenanceTimes, true, "FirstMaintenanceTime");
forceMaintenance = new BooleanListInput("ForceMaintenance", "Maintenance", null);
this.addInput(forceMaintenance, true);
releaseEquipment = new BooleanListInput("ReleaseEquipment", "Maintenance", null);
this.addInput(releaseEquipment, true);
availability = new DoubleInput("Reliability", "Breakdowns", 1.0d, 0.0d, 1.0d);
this.addInput(availability, true);
downtimeIATDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeIATDistribution", "Breakdowns", null);
this.addInput(downtimeIATDistribution, true);
downtimeDurationDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeDurationDistribution", "Breakdowns", null);
this.addInput(downtimeDurationDistribution, true);
downtimeToReleaseEquipment = new DoubleInput("DowntimeToReleaseEquipment", "Breakdowns", 0.0d, 0.0d, Double.POSITIVE_INFINITY);
this.addInput(downtimeToReleaseEquipment, true);
skipMaintenanceIfOverlap = new BooleanListInput("SkipMaintenanceIfOverlap", "Maintenance", new BooleanVector());
this.addInput(skipMaintenanceIfOverlap, true);
deferMaintenanceLimit = new DoubleListInput("DeferMaintenanceLimit", "Maintenance", null);
deferMaintenanceLimit.setValidRange(0.0d, Double.POSITIVE_INFINITY);
deferMaintenanceLimit.setUnits("h");
this.addInput(deferMaintenanceLimit, true);
sharedMaintenanceList = new EntityListInput<ModelEntity>(ModelEntity.class, "SharedMaintenance", "Maintenance", new ArrayList<ModelEntity>(0));
this.addInput(sharedMaintenanceList, true);
firstMaintenanceOperatingHours = new DoubleListInput("FirstMaintenanceOperatingHours", "Maintenance", new DoubleVector());
firstMaintenanceOperatingHours.setValidRange(0.0d, Double.POSITIVE_INFINITY);
firstMaintenanceOperatingHours.setUnits("h");
this.addInput(firstMaintenanceOperatingHours, true);
maintenanceOperatingHoursDurations = new DoubleListInput("MaintenanceOperatingHoursDurations", "Maintenance", new DoubleVector());
maintenanceOperatingHoursDurations.setValidRange(1e-15, Double.POSITIVE_INFINITY);
maintenanceOperatingHoursDurations.setUnits("h");
this.addInput(maintenanceOperatingHoursDurations, true);
maintenanceOperatingHoursIntervals = new DoubleListInput("MaintenanceOperatingHoursIntervals", "Maintenance", new DoubleVector());
maintenanceOperatingHoursIntervals.setValidRange(1e-15, Double.POSITIVE_INFINITY);
maintenanceOperatingHoursIntervals.setUnits("h");
this.addInput(maintenanceOperatingHoursIntervals, true);
printToReport = new BooleanInput("PrintToReport", "Report", true);
this.addInput(printToReport, true);
}
public ModelEntity() {
hoursPerState = new DoubleVector();
lastHistogramUpdateTime = 0.0;
secondToLastHistogramUpdateTime = 0.0;
lastStartTimePerState = new DoubleVector();
secondToLastStartTimePerState = new DoubleVector();
timeOfLastStateChange = 0.0;
hoursForNextFailure = 0.0;
iATFailure = 0.0;
maintenancePendings = new IntegerVector( 1, 1 );
maintenanceOperatingHoursPendings = new IntegerVector( 1, 1 );
hoursForNextMaintenanceOperatingHours = new DoubleVector( 1, 1 );
performMaintenanceAfterShipDelayPending = false;
lastScheduledMaintenanceTimes = new DoubleVector();
breakdownStartTime = 0.0;
breakdownEndTime = Double.POSITIVE_INFINITY;
breakdownPending = false;
brokendown = false;
associatedBreakdown = false;
maintenanceStartTime = 0.0;
maintenanceEndTime = Double.POSITIVE_INFINITY;
maintenance = false;
associatedMaintenance = false;
workingHours = 0.0;
stateMap = new HashMap<String, StateRecord>();
timeOfLastStateChange = 0.0;
initStateMap();
}
/**
* Clear internal properties
*/
public void clearInternalProperties() {
timeOfLastStateChange = 0.0;
hoursForNextFailure = 0.0;
performMaintenanceAfterShipDelayPending = false;
breakdownPending = false;
brokendown = false;
associatedBreakdown = false;
maintenance = false;
associatedMaintenance = false;
workingHours = 0.0;
}
@Override
public void validate()
throws InputErrorException {
super.validate();
this.validateMaintenance();
Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursIntervals.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursIntervals");
Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursDurations.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursDurations");
if( getAvailability() < 1.0 ) {
if( getDowntimeDurationDistribution() == null ) {
throw new InputErrorException("When availability is less than one you must define downtimeDurationDistribution in your input file!");
}
}
if( downtimeIATDistribution.getValue() != null ) {
if( getDowntimeDurationDistribution() == null ) {
throw new InputErrorException("When DowntimeIATDistribution is set, DowntimeDurationDistribution must also be set.");
}
}
if( skipMaintenanceIfOverlap.getValue().size() > 0 )
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), skipMaintenanceIfOverlap.getValue(), "FirstMaintenanceTimes", "SkipMaintenanceIfOverlap");
if( releaseEquipment.getValue() != null )
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), releaseEquipment.getValue(), "FirstMaintenanceTimes", "ReleaseEquipment");
if( forceMaintenance.getValue() != null ) {
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), forceMaintenance.getValue(), "FirstMaintenanceTimes", "ForceMaintenance");
}
if(downtimeDurationDistribution.getValue() != null &&
downtimeDurationDistribution.getValue().getMinimumValue() < 0)
throw new InputErrorException("DowntimeDurationDistribution cannot allow negative values");
if(downtimeIATDistribution.getValue() != null &&
downtimeIATDistribution.getValue().getMinimumValue() < 0)
throw new InputErrorException("DowntimeIATDistribution cannot allow negative values");
}
@Override
public void earlyInit() {
super.earlyInit();
if( downtimeDurationDistribution.getValue() != null ) {
downtimeDurationDistribution.getValue().initialize();
}
if( downtimeIATDistribution.getValue() != null ) {
downtimeIATDistribution.getValue().initialize();
}
}
/**
* Runs after initialization period
*/
public void collectInitializationStats() {
this.updateStateRecordHours();
for ( StateRecord each : stateMap.values() ) {
each.collectInitializationStats();
}
numberOfCompletedCycles = 0;
}
/**
* Runs when cycle is finished
*/
public void collectCycleStats() {
this.updateStateRecordHours();
// finalize cycle for each state record
for ( StateRecord each : stateMap.values() ) {
each.collectCycleStats();
}
numberOfCompletedCycles++;
}
/**
* Runs after each report interval
*/
public void clearReportStats() {
// clear totalHours for each state record
for ( StateRecord each : stateMap.values() ) {
each.clearReportStats();
}
numberOfCompletedCycles = 0;
}
public int getNumberOfCompletedCycles() {
return numberOfCompletedCycles;
}
/**
* Clear the current cycle hours
*/
protected void clearCurrentCycleHours() {
this.updateStateRecordHours();
// clear current cycle hours for each state record
for ( StateRecord each : stateMap.values() ) {
each.clearCurrentCycleHours();
}
}
public void initStateMap() {
// Populate the hash map for the states and StateRecord
stateMap.clear();
for (int i = 0; i < getStateList().size(); i++) {
String state = (String)getStateList().get(i);
StateRecord stateRecord = new StateRecord(state, i);
stateMap.put(state.toLowerCase() , stateRecord);
}
timeOfLastStateUpdate = getCurrentTime();
}
private StateRecord getStateRecordFor(String state) {
return stateMap.get(state.toLowerCase());
}
private StateRecord getStateRecordFor(int index) {
String state = (String)getStateList().get(index);
return getStateRecordFor(state);
}
public double getCompletedCycleHoursFor(String state) {
return getStateRecordFor(state).getCompletedCycleHours();
}
public double getCompletedCycleHoursFor(int index) {
return getStateRecordFor(index).getCompletedCycleHours();
}
public double getCompletedCycleHours() {
double total = 0.0d;
for (int i = 0; i < getStateList().size(); i ++)
total += getStateRecordFor(i).getCompletedCycleHours();
return total;
}
public double getTotalHoursFor(int index) {
return getStateRecordFor(index).getTotalHours();
}
public double getTotalHoursFor(String state) {
StateRecord rec = getStateRecordFor(state);
double hours = rec.getTotalHours();
if (presentState == rec)
hours += getCurrentTime() - timeOfLastStateUpdate;
return hours;
}
// ******************************************************************************************************
// INPUT
// ******************************************************************************************************
public void validateMaintenance() {
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceIntervals.getValue(), "FirstMaintenanceTimes", "MaintenanceIntervals");
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceDurations.getValue(), "FirstMaintenanceTimes", "MaintenanceDurations");
for( int i = 0; i < maintenanceIntervals.getValue().size(); i++ ) {
if( maintenanceIntervals.getValue().get( i ) < maintenanceDurations.getValue().get( i ) ) {
throw new InputErrorException("MaintenanceInterval should be greater than MaintenanceDuration (%f) <= (%f)",
maintenanceIntervals.getValue().get(i), maintenanceDurations.getValue().get(i));
}
}
}
// ******************************************************************************************************
// INITIALIZATION METHODS
// ******************************************************************************************************
public void clearStatistics() {
for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
hoursForNextMaintenanceOperatingHours.set( i, hoursForNextMaintenanceOperatingHours.get( i ) - this.getWorkingHours() );
}
initHoursPerState();
timeOfLastStateChange = getCurrentTime();
// Determine the time for the first breakdown event
/*if ( downtimeIATDistribution == null ) {
if( breakdownSeed != 0 ) {
breakdownRandGen.initialiseWith( breakdownSeed );
hoursForNextFailure = breakdownRandGen.getUniformFrom_To( 0.5*iATFailure, 1.5*iATFailure );
} else {
hoursForNextFailure = getNextBreakdownIAT();
}
}
else {
hoursForNextFailure = getNextBreakdownIAT();
}*/
}
public void initializeStatistics() {
initHoursPerState();
timeOfLastStateChange = getCurrentTime();
}
/**
* *!*!*!*! OVERLOAD !*!*!*!*
* Initialize statistics
*/
public void initialize() {
brokendown = false;
maintenance = false;
associatedBreakdown = false;
associatedMaintenance = false;
// Create state trace file if required
if (testFlag(FLAG_TRACESTATE)) {
String fileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + "-" + this.getName() + ".trc";
stateReportFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
}
initHoursPerState();
lastStartTimePerState.fillWithEntriesOf( getStateList().size(), 0.0 );
secondToLastStartTimePerState.fillWithEntriesOf( getStateList().size(), 0.0 );
timeOfLastStateChange = getCurrentTime();
workingHours = 0.0;
// Calculate the average downtime duration if distributions are used
double average = 0.0;
if(getDowntimeDurationDistribution() != null)
average = getDowntimeDurationDistribution().getExpectedValue();
// Calculate the average downtime inter-arrival time
if( (getAvailability() == 1.0 || average == 0.0) ) {
iATFailure = 10.0E10;
}
else {
if( getDowntimeIATDistribution() != null ) {
iATFailure = getDowntimeIATDistribution().getExpectedValue();
// Adjust the downtime inter-arrival time to get the specified availability
if( ! Tester.equalCheckTolerance( iATFailure, ( (average / (1.0 - getAvailability())) - average ) ) ) {
getDowntimeIATDistribution().setValueFactor_For( ( (average / (1.0 - getAvailability())) - average) / iATFailure, this );
iATFailure = getDowntimeIATDistribution().getExpectedValue();
}
}
else {
iATFailure = ( (average / (1.0 - getAvailability())) - average );
}
}
// Determine the time for the first breakdown event
hoursForNextFailure = getNextBreakdownIAT();
int ind = this.indexOfState( "Idle" );
if( ind != -1 ) {
this.setPresentState( "Idle" );
}
brokendown = false;
// Start the maintenance network
if( firstMaintenanceTimes.getValue().size() != 0 ) {
maintenancePendings.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), 0 );
lastScheduledMaintenanceTimes.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), Double.POSITIVE_INFINITY );
this.doMaintenanceNetwork();
}
// calculate hours for first operating hours breakdown
for ( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
hoursForNextMaintenanceOperatingHours.add( firstMaintenanceOperatingHours.getValue().get( i ) );
maintenanceOperatingHoursPendings.add( 0 );
}
}
// ******************************************************************************************************
// ACCESSOR METHODS
// ******************************************************************************************************
/**
* Return the time at which the most recent maintenance is scheduled to end
*/
public double getMaintenanceEndTime() {
return maintenanceEndTime;
}
/**
* Return the time at which a the most recent breakdown is scheduled to end
*/
public double getBreakdownEndTime() {
return breakdownEndTime;
}
public double getTimeOfLastStateChange() {
return timeOfLastStateChange;
}
/**
* Returns the availability proportion.
*/
public double getAvailability() {
return availability.getValue();
}
public DoubleListInput getFirstMaintenanceTimes() {
return firstMaintenanceTimes;
}
public boolean getPrintToReport() {
return printToReport.getValue();
}
public boolean isBrokendown() {
return brokendown;
}
public boolean isBreakdownPending() {
return breakdownPending;
}
public boolean isInAssociatedBreakdown() {
return associatedBreakdown;
}
public boolean isInMaintenance() {
return maintenance;
}
public boolean isInAssociatedMaintenance() {
return associatedMaintenance;
}
public boolean isInService() {
return ( brokendown || maintenance || associatedBreakdown || associatedMaintenance );
}
public void setBrokendown( boolean bool ) {
brokendown = bool;
this.setPresentState();
}
public void setMaintenance( boolean bool ) {
maintenance = bool;
this.setPresentState();
}
public void setAssociatedBreakdown( boolean bool ) {
associatedBreakdown = bool;
}
public void setAssociatedMaintenance( boolean bool ) {
associatedMaintenance = bool;
}
public ProbabilityDistribution getDowntimeDurationDistribution() {
return downtimeDurationDistribution.getValue();
}
public double getDowntimeToReleaseEquipment() {
return downtimeToReleaseEquipment.getValue();
}
public boolean hasServiceDefined() {
return( maintenanceDurations.getValue().size() > 0 || getDowntimeDurationDistribution() != null );
}
// ******************************************************************************************************
// HOURS AND STATES
// ******************************************************************************************************
/**
* Updates the statistics for the present status.
*/
public void updateHours() {
if( getPresentState().length() == 0 ) {
timeOfLastStateChange = getCurrentTime();
return;
}
int index = this.indexOfState( getPresentState() );
if( index == -1 ) {
throw new ErrorException( "Present state not found in StateList." );
}
double dur = getCurrentTime() - timeOfLastStateChange;
if( dur > 0.0 ) {
/*int index = getStateList().indexOfString( presentState );
if( index == -1 ) {
throw new ErrorException( " Present state not found in StateList." );
}
hoursPerState.addAt( dur, index );*/
addHoursAt(dur, getPresentStateIndex());
timeOfLastStateChange = getCurrentTime();
// Update working hours, if required
//if( getWorkingStateList().contains( presentState ) ) {
if( this.isWorking() ) {
workingHours += dur;
}
}
}
public void updateStateRecordHours() {
if (presentState == null) {
timeOfLastStateUpdate = getCurrentTime();
return;
}
double time = getCurrentTime();
if (time != timeOfLastStateUpdate) {
presentState.addHours(time - timeOfLastStateUpdate);
timeOfLastStateUpdate = getCurrentTime();
}
}
public void initHoursPerState() {
hoursPerState.clear();
if( getStateList().size() != 0 )
hoursPerState.fillWithEntriesOf( getStateList().size(), 0.0 );
}
/**
* Return true if the entity is working
*/
public boolean isWorking() {
return false;
}
/**
* Returns the present status.
*/
public String getPresentState() {
if (presentState == null)
return "";
return presentState.getStateName();
}
public boolean presentStateEquals(String state) {
return getPresentState().equals(state);
}
public boolean presentStateMatches(String state) {
return getPresentState().equalsIgnoreCase(state);
}
public boolean presentStateStartsWith(String prefix) {
return getPresentState().startsWith(prefix);
}
public boolean presentStateEndsWith(String suffix) {
return getPresentState().endsWith(suffix);
}
protected int getPresentStateIndex() {
if (presentState == null)
return -1;
return presentState.getIndex();
}
public void setPresentState() {}
/**
* Updates the statistics, then sets the present status to be the specified value.
*/
public void setPresentState( String state ) {
if( traceFlag ) this.trace("setState( "+state+" )");
if( traceFlag ) this.traceLine(" Old State = "+getPresentState() );
if( ! presentStateEquals( state ) ) {
if (testFlag(FLAG_TRACESTATE)) this.printStateTrace(state);
int ind = this.indexOfState( state );
if( ind != -1 ) {
this.updateHours();
this.updateStateRecordHours();
presentState = getStateRecordFor(state);
if( lastStartTimePerState.size() > 0 ) {
if( secondToLastStartTimePerState.size() > 0 ) {
secondToLastStartTimePerState.set( ind, lastStartTimePerState.get( ind ) );
}
lastStartTimePerState.set( ind, getCurrentTime() );
}
}
else {
throw new ErrorException( this + " Specified state: " + state + " was not found in the StateList: " + this.getStateList() );
}
}
}
/**
* Print that state information on the trace state log file
*/
public void printStateTrace( String state ) {
// First state ever
if( finalLastState.equals("") ) {
finalLastState = state;
stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n",
0.0d, this.getName(), getPresentState(), formatNumber(getCurrentTime())));
stateReportFile.flush();
timeOfLastPrintedState = getCurrentTime();
}
else {
// The final state in a sequence from the previous state change (one step behind)
if ( ! Tester.equalCheckTimeStep( timeOfLastPrintedState, getCurrentTime() ) ) {
stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n",
timeOfLastPrintedState, this.getName(), finalLastState, formatNumber(getCurrentTime() - timeOfLastPrintedState)));
// for( int i = 0; i < stateTraceRelatedModelEntities.size(); i++ ) {
// ModelEntitiy each = (ModelEntitiy) stateTraceRelatedModelEntities.get( i );
// putString( )
// }
stateReportFile.flush();
timeOfLastPrintedState = getCurrentTime();
}
finalLastState = state;
}
}
/**
* Returns the amount of time spent in the specified status.
*/
public double getCurrentCycleHoursFor( String state ) {
int index = this.indexOfState( state );
if( index != -1 ) {
this.updateHours();
return getCurrentCycleHoursFor( index );
}
else {
throw new ErrorException( "Specified state: " + state + " was not found in the StateList." );
}
}
/**
* Return spent hours for a given state at the index in stateList
*/
public double getCurrentCycleHoursFor(int index) {
return hoursPerState.get(index);
}
/**
* Set the last time a histogram was updated for this entity
*/
public void setLastHistogramUpdateTime( double time ) {
secondToLastHistogramUpdateTime = lastHistogramUpdateTime;
lastHistogramUpdateTime = time;
}
/**
* Returns the time from the start of the start state to the start of the end state
*/
public double getTimeFromStartState_ToEndState( String startState, String endState) {
// Determine the index of the start state
int startIndex = this.indexOfState( startState );
if( startIndex == -1 ) {
throw new ErrorException( "Specified state: " + startState + " was not found in the StateList." );
}
// Determine the index of the end state
int endIndex = this.indexOfState( endState );
if( endIndex == -1 ) {
throw new ErrorException( "Specified state: " + endState + " was not found in the StateList." );
}
// Is the start time of the end state greater or equal to the start time of the start state?
if( lastStartTimePerState.get( endIndex ) >= lastStartTimePerState.get( startIndex ) ) {
// If either time was not in the present cycle, return NaN
if( lastStartTimePerState.get( endIndex ) <= lastHistogramUpdateTime ||
lastStartTimePerState.get( startIndex ) <= lastHistogramUpdateTime ) {
return Double.NaN;
}
// Return the time from the last start time of the start state to the last start time of the end state
return lastStartTimePerState.get( endIndex ) - lastStartTimePerState.get( startIndex );
}
else {
// If either time was not in the present cycle, return NaN
if( lastStartTimePerState.get( endIndex ) <= lastHistogramUpdateTime ||
secondToLastStartTimePerState.get( startIndex ) <= secondToLastHistogramUpdateTime ) {
return Double.NaN;
}
// Return the time from the second to last start time of the start date to the last start time of the end state
return lastStartTimePerState.get( endIndex ) - secondToLastStartTimePerState.get( startIndex );
}
}
/**
* Return the commitment
*/
public double getCommitment() {
return 1.0 - this.getFractionOfTimeForState( "Idle" );
}
/**
* Return the fraction of time for the given status
*/
public double getFractionOfTimeForState( String aState ) {
if( getCurrentCycleHours() > 0.0 ) {
return ((this.getCurrentCycleHoursFor( aState ) / getCurrentCycleHours()) );
}
else {
return 0.0;
}
}
/**
* Return the percentage of time for the given status
*/
public double getPercentageOfTimeForState( String aState ) {
if( getCurrentCycleHours() > 0.0 ) {
return ((this.getCurrentCycleHoursFor( aState ) / getCurrentCycleHours()) * 100.0);
}
else {
return 0.0;
}
}
/**
* Returns the number of hours the entity is in use.
* *!*!*!*! OVERLOAD !*!*!*!*
*/
public double getWorkingHours() {
this.updateHours();
return workingHours;
}
/**
* Add hours to the specified state by index on the stateList
*/
protected void addHoursAt(double dur, int index) {
hoursPerState.addAt(dur, index);
}
public Vector getStateList() {
return stateList;
}
public int indexOfState( String state ) {
StateRecord stateRecord = stateMap.get( state.toLowerCase() );
if (stateRecord != null)
return stateRecord.getIndex();
return -1;
}
/**
* Return total number of states
*/
public int getNumberOfStates() {
return hoursPerState.size();
}
/**
* Return the total hours in current cycle for all the states
*/
public double getCurrentCycleHours() {
return hoursPerState.sum();
}
// *******************************************************************************************************
// MAINTENANCE METHODS
// *******************************************************************************************************
/**
* Perform tasks required before a maintenance period
*/
public void doPreMaintenance() {
//@debug@ cr 'Entity should be overloaded' print
}
/**
* Start working again following a breakdown or maintenance period
*/
public void restart() {
//@debug@ cr 'Entity should be overloaded' print
}
/**
* Disconnect routes, release truck assignments, etc. when performing maintenance or breakdown
*/
public void releaseEquipment() {}
public boolean releaseEquipmentForMaintenanceSchedule( int index ) {
if( releaseEquipment.getValue() == null )
return true;
return releaseEquipment.getValue().get( index );
}
public boolean forceMaintenanceSchedule( int index ) {
if( forceMaintenance.getValue() == null )
return false;
return forceMaintenance.getValue().get( index );
}
/**
* Perform all maintenance schedules that are due
*/
public void doMaintenance() {
// scheduled maintenance
for( int index = 0; index < maintenancePendings.size(); index++ ) {
if( this.getMaintenancePendings().get( index ) > 0 ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.doMaintenance(index);
}
}
// Operating hours maintenance
for( int index = 0; index < maintenanceOperatingHoursPendings.size(); index++ ) {
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( index ) ) {
hoursForNextMaintenanceOperatingHours.set(index, this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( index ));
maintenanceOperatingHoursPendings.addAt( 1, index );
this.doMaintenanceOperatingHours(index);
}
}
}
/**
* Perform all the planned maintenance that is due for the given schedule
*/
public void doMaintenance( int index ) {
double wait;
if( masterMaintenanceEntity != null ) {
wait = masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index );
}
else {
wait = this.getMaintenanceDurations().getValue().get( index );
}
if( wait > 0.0 && maintenancePendings.get( index ) != 0 ) {
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" );
// Keep track of the start and end of maintenance times
maintenanceStartTime = getCurrentTime();
if( masterMaintenanceEntity != null ) {
maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ) );
}
else {
maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * maintenanceDurations.getValue().get( index ) );
}
this.setPresentState( "Maintenance" );
maintenance = true;
this.doPreMaintenance();
// Release equipment if necessary
if( this.releaseEquipmentForMaintenanceSchedule( index ) ) {
this.releaseEquipment();
}
while( maintenancePendings.get( index ) != 0 ) {
maintenancePendings.subAt( 1, index );
scheduleWait( wait );
// If maintenance pending goes negative, something is wrong
if( maintenancePendings.get( index ) < 0 ) {
this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenancePendings.get( index ) );
}
}
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" );
// The maintenance is over
this.setPresentState( "Idle" );
maintenance = false;
this.restart();
}
}
/**
* Perform all the planned maintenance that is due
*/
public void doMaintenanceOperatingHours( int index ) {
if(maintenanceOperatingHoursPendings.get( index ) == 0 )
return;
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" );
// Keep track of the start and end of maintenance times
maintenanceStartTime = getCurrentTime();
maintenanceEndTime = maintenanceStartTime +
(maintenanceOperatingHoursPendings.get( index ) * getMaintenanceOperatingHoursDurationFor(index));
this.setPresentState( "Maintenance" );
maintenance = true;
this.doPreMaintenance();
while( maintenanceOperatingHoursPendings.get( index ) != 0 ) {
//scheduleWait( maintenanceDurations.get( index ) );
scheduleWait( maintenanceEndTime - maintenanceStartTime );
maintenanceOperatingHoursPendings.subAt( 1, index );
// If maintenance pending goes negative, something is wrong
if( maintenanceOperatingHoursPendings.get( index ) < 0 ) {
this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenanceOperatingHoursPendings.get( index ) );
}
}
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" );
// The maintenance is over
maintenance = false;
this.setPresentState( "Idle" );
this.restart();
}
/**
* Check if a maintenance is due. if so, try to perform the maintenance
*/
public boolean checkMaintenance() {
if( traceFlag ) this.trace( "checkMaintenance()" );
if( checkOperatingHoursMaintenance() ) {
return true;
}
// List of all entities going to maintenance
ArrayList<ModelEntity> sharedMaintenanceEntities;
// This is not a master maintenance entity
if( masterMaintenanceEntity != null ) {
sharedMaintenanceEntities = masterMaintenanceEntity.getSharedMaintenanceList();
}
// This is a master maintenance entity
else {
sharedMaintenanceEntities = getSharedMaintenanceList();
}
// If this entity is in shared maintenance relation with a group of entities
if( sharedMaintenanceEntities.size() > 0 || masterMaintenanceEntity != null ) {
// Are all entities in the group ready for maintenance
if( this.areAllEntitiesAvailable() ) {
// For every entity in the shared maintenance list plus the master maintenance entity
for( int i=0; i <= sharedMaintenanceEntities.size(); i++ ) {
ModelEntity aModel;
// Locate master maintenance entity( after all entity in shared maintenance list have been taken care of )
if( i == sharedMaintenanceEntities.size() ) {
// This entity is manster maintenance entity
if( masterMaintenanceEntity == null ) {
aModel = this;
}
// This entity is on the shared maintenannce list of the master maintenance entity
else {
aModel = masterMaintenanceEntity;
}
}
// Next entity in the shared maintenance list
else {
aModel = sharedMaintenanceEntities.get( i );
}
// Check for aModel maintenances
for( int index = 0; index < maintenancePendings.size(); index++ ) {
if( aModel.getMaintenancePendings().get( index ) > 0 ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
aModel.startProcess("doMaintenance", index);
}
}
}
return true;
}
else {
return false;
}
}
// This block is maintained indipendently
else {
// Check for maintenances
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 ) {
if( this.canStartMaintenance( i ) ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + i );
this.startProcess("doMaintenance", i);
return true;
}
}
}
}
return false;
}
/**
* Determine how many hours of maintenance is scheduled between startTime and endTime
*/
public double getScheduledMaintenanceHoursForPeriod( double startTime, double endTime ) {
if( traceFlag ) this.trace("Handler.getScheduledMaintenanceHoursForPeriod( "+startTime+", "+endTime+" )" );
double totalHours = 0.0;
double firstTime = 0.0;
// Add on hours for all pending maintenance
for( int i=0; i < maintenancePendings.size(); i++ ) {
totalHours += maintenancePendings.get( i ) * maintenanceDurations.getValue().get( i );
}
if( traceFlag ) this.traceLine( "Hours of pending maintenances="+totalHours );
// Add on hours for all maintenance scheduled to occur in the given period from startTime to endTime
for( int i=0; i < maintenancePendings.size(); i++ ) {
// Find the first time that maintenance is scheduled after startTime
firstTime = firstMaintenanceTimes.getValue().get( i );
while( firstTime < startTime ) {
firstTime += maintenanceIntervals.getValue().get( i );
}
if( traceFlag ) this.traceLine(" first time maintenance "+i+" is scheduled after startTime= "+firstTime );
// Now have the first maintenance start time after startTime
// Add all maintenances that lie in the given interval
while( firstTime < endTime ) {
if( traceFlag ) this.traceLine(" Checking for maintenances for period:"+firstTime+" to "+endTime );
// Add the maintenance
totalHours += maintenanceDurations.getValue().get( i );
// Update the search period
endTime += maintenanceDurations.getValue().get( i );
// Look for next maintenance in new interval
firstTime += maintenanceIntervals.getValue().get( i );
if( traceFlag ) this.traceLine(" Adding Maintenance duration = "+maintenanceDurations.getValue().get( i ) );
}
}
// Return the total hours of maintenance scheduled from startTime to endTime
if( traceFlag ) this.traceLine( "Maintenance hours to add= "+totalHours );
return totalHours;
}
public boolean checkOperatingHoursMaintenance() {
if( traceFlag ) this.trace("checkOperatingHoursMaintenance()");
// Check for maintenances
for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
// If the entity is not available, maintenance cannot start
if( ! this.canStartMaintenance( i ) )
continue;
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) {
hoursForNextMaintenanceOperatingHours.set(i, (this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( i )));
maintenanceOperatingHoursPendings.addAt( 1, i );
if( traceFlag ) this.trace( "Starting Maintenance Operating Hours Schedule : " + i );
this.startProcess("doMaintenanceOperatingHours", i);
return true;
}
}
return false;
}
/**
* Wrapper method for doMaintenance_Wait.
*/
public void doMaintenanceNetwork() {
this.startProcess("doMaintenanceNetwork_Wait");
}
/**
* Network for planned maintenance.
* This method should be called in the initialize method of the specific entity.
*/
public void doMaintenanceNetwork_Wait() {
// Initialize schedules
for( int i=0; i < maintenancePendings.size(); i++ ) {
maintenancePendings.set( i, 0 );
}
nextMaintenanceTimes = new DoubleVector(firstMaintenanceTimes.getValue());
nextMaintenanceDuration = 0;
// Find the next maintenance event
int index = 0;
double earliestTime = Double.POSITIVE_INFINITY;
for( int i=0; i < nextMaintenanceTimes.size(); i++ ) {
double time = nextMaintenanceTimes.get( i );
if( Tester.lessCheckTolerance( time, earliestTime ) ) {
earliestTime = time;
index = i;
nextMaintenanceDuration = maintenanceDurations.getValue().get( i );
}
}
// Make sure that maintenance for entities on the shared list are being called after those entities have been initialize (AT TIME ZERO)
scheduleLastLIFO();
while( true ) {
double dt = earliestTime - getCurrentTime();
// Wait for the maintenance check time
if( dt > Process.getEventTolerance() ) {
scheduleWait( dt );
}
// Increment the number of maintenances due for the entity
maintenancePendings.addAt( 1, index );
// If this is a master maintenance entity
if (getSharedMaintenanceList().size() > 0) {
// If all the entities on the shared list are ready for maintenance
if( this.areAllEntitiesAvailable() ) {
// Put this entity to maintenance
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.startProcess("doMaintenance", index);
}
}
// If this entity is maintained independently
else {
// Do maintenance if possible
if( ! this.isInService() && this.canStartMaintenance( index ) ) {
// if( traceFlag ) this.trace( "doMaintenanceNetwork_Wait: Starting Maintenance. PresentState = "+presentState+" IsAvailable? = "+this.isAvailable() );
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.startProcess("doMaintenance", index);
}
// Keep track of the time the maintenance was attempted
else {
lastScheduledMaintenanceTimes.set( index, getCurrentTime() );
// If skipMaintenance was defined, cancel the maintenance
if( this.shouldSkipMaintenance( index ) ) {
// if a different maintenance is due, cancel this maintenance
boolean cancelMaintenance = false;
for( int i=0; i < maintenancePendings.size(); i++ ) {
if( i != index ) {
if( maintenancePendings.get( i ) > 0 ) {
cancelMaintenance = true;
break;
}
}
}
if( cancelMaintenance || this.isInMaintenance() ) {
maintenancePendings.subAt( 1, index );
}
}
// Do a check after the limit has expired
if( this.getDeferMaintenanceLimit( index ) > 0.0 ) {
this.startProcess( "scheduleCheckMaintenance", this.getDeferMaintenanceLimit( index ) );
}
}
}
// Determine the next maintenance time
nextMaintenanceTimes.addAt( maintenanceIntervals.getValue().get( index ), index );
// Find the next maintenance event
index = 0;
earliestTime = Double.POSITIVE_INFINITY;
for( int i=0; i < nextMaintenanceTimes.size(); i++ ) {
double time = nextMaintenanceTimes.get( i );
if( Tester.lessCheckTolerance( time, earliestTime ) ) {
earliestTime = time;
index = i;
nextMaintenanceDuration = maintenanceDurations.getValue().get( i );
}
}
}
}
public double getDeferMaintenanceLimit( int index ) {
if( deferMaintenanceLimit.getValue() == null )
return 0.0d;
return deferMaintenanceLimit.getValue().get( index );
}
public void scheduleCheckMaintenance( double wait ) {
scheduleWait( wait );
this.checkMaintenance();
}
public boolean shouldSkipMaintenance( int index ) {
if( skipMaintenanceIfOverlap.getValue().size() == 0 )
return false;
return skipMaintenanceIfOverlap.getValue().get( index );
}
/**
* Return TRUE if there is a pending maintenance for any schedule
*/
public boolean isMaintenancePending() {
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 ) {
return true;
}
}
for( int i = 0; i < hoursForNextMaintenanceOperatingHours.size(); i++ ) {
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) {
return true;
}
}
return false;
}
public boolean isForcedMaintenancePending() {
if( forceMaintenance.getValue() == null )
return false;
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 && forceMaintenance.getValue().get(i) ) {
return true;
}
}
return false;
}
public ArrayList<ModelEntity> getSharedMaintenanceList () {
return sharedMaintenanceList.getValue();
}
public IntegerVector getMaintenancePendings () {
return maintenancePendings;
}
public DoubleListInput getMaintenanceDurations() {
return maintenanceDurations;
}
/**
* Return the start of the next scheduled maintenance time if not in maintenance,
* or the start of the current scheduled maintenance time if in maintenance
*/
public double getNextMaintenanceStartTime() {
if( nextMaintenanceTimes == null )
return Double.POSITIVE_INFINITY;
else
return nextMaintenanceTimes.getMin();
}
/**
* Return the duration of the next maintenance event (assuming only one pending)
*/
public double getNextMaintenanceDuration() {
return nextMaintenanceDuration;
}
// Shows if an Entity would ever go on service
public boolean hasServiceScheduled() {
if( firstMaintenanceTimes.getValue().size() != 0 || masterMaintenanceEntity != null ) {
return true;
}
return false;
}
public void setMasterMaintenanceBlock( ModelEntity aModel ) {
masterMaintenanceEntity = aModel;
}
// *******************************************************************************************************
// BREAKDOWN METHODS
// *******************************************************************************************************
/**
* No Comments Given.
*/
public void calculateTimeOfNextFailure() {
hoursForNextFailure = (this.getWorkingHours() + this.getNextBreakdownIAT());
}
/**
* Activity Network for Breakdowns.
*/
public void doBreakdown() {
}
/**
* Prints the header for the entity's state list.
* @return bottomLine contains format for each column of the bottom line of the group report
*/
public IntegerVector printUtilizationHeaderOn( FileEntity anOut ) {
IntegerVector bottomLine = new IntegerVector();
if( getStateList().size() != 0 ) {
anOut.putStringTabs( "Name", 1 );
bottomLine.add( ReportAgent.BLANK );
int doLoop = getStateList().size();
for( int x = 0; x < doLoop; x++ ) {
String state = (String)getStateList().get( x );
anOut.putStringTabs( state, 1 );
bottomLine.add( ReportAgent.AVERAGE_PCT_ONE_DEC );
}
anOut.newLine();
}
return bottomLine;
}
/**
* Print the entity's name and percentage of hours spent in each state.
* @return columnValues are the values for each column in the group report (0 if the value is a String)
*/
public DoubleVector printUtilizationOn( FileEntity anOut ) {
double total;
DoubleVector columnValues = new DoubleVector();
this.updateHours();
if( getNumberOfStates() != 0 ) {
total = getCurrentCycleHours();
if( !(total == 0.0) ) {
this.updateHours();
anOut.putStringTabs( getName(), 1 );
columnValues.add( 0.0 );
for( int i = 0; i < getNumberOfStates(); i++ ) {
double value = getTotalHoursFor( i ) / total;
anOut.putDoublePercentWithDecimals( value, 1 );
anOut.putTabs( 1 );
columnValues.add( value );
}
anOut.newLine();
}
}
return columnValues;
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean isAvailable() {
throw new ErrorException( "Must override isAvailable in any subclass of ModelEntity." );
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean canStartMaintenance( int index ) {
return isAvailable();
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean canStartForcedMaintenance() {
return isAvailable();
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean areAllEntitiesAvailable() {
throw new ErrorException( "Must override areAllEntitiesAvailable in any subclass of ModelEntity." );
}
/**
* Return the time of the next breakdown duration
*/
public double getBreakdownDuration() {
// if( traceFlag ) this.trace( "getBreakdownDuration()" );
// If a distribution was specified, then select a duration randomly from the distribution
if ( getDowntimeDurationDistribution() != null ) {
return getDowntimeDurationDistribution().nextValue();
}
else {
return 0.0;
}
}
/**
* Return the time of the next breakdown IAT
*/
public double getNextBreakdownIAT() {
if( getDowntimeIATDistribution() != null ) {
return getDowntimeIATDistribution().nextValue();
}
else {
return iATFailure;
}
}
public double getHoursForNextFailure() {
return hoursForNextFailure;
}
public void setHoursForNextFailure( double hours ) {
hoursForNextFailure = hours;
}
/**
Returns a vector of strings describing the ModelEntity.
Override to add details
@return Vector - tab delimited strings describing the DisplayEntity
**/
@Override
public Vector getInfo() {
Vector info = super.getInfo();
if ( presentStateEquals("") )
info.addElement( "Present State\t<no state>" );
else
info.addElement( "Present State" + "\t" + getPresentState() );
return info;
}
protected DoubleVector getMaintenanceOperatingHoursIntervals() {
return maintenanceOperatingHoursIntervals.getValue();
}
protected double getMaintenanceOperatingHoursDurationFor(int index) {
return maintenanceOperatingHoursDurations.getValue().get(index);
}
protected ProbabilityDistribution getDowntimeIATDistribution() {
return downtimeIATDistribution.getValue();
}
} | src/main/java/com/sandwell/JavaSimulation3D/ModelEntity.java | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2002-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.sandwell.JavaSimulation3D;
import static com.sandwell.JavaSimulation.Util.formatNumber;
import java.util.ArrayList;
import java.util.HashMap;
import com.jaamsim.input.InputAgent;
import com.jaamsim.math.Color4d;
import com.sandwell.JavaSimulation.BooleanInput;
import com.sandwell.JavaSimulation.BooleanListInput;
import com.sandwell.JavaSimulation.BooleanVector;
import com.sandwell.JavaSimulation.ColourInput;
import com.sandwell.JavaSimulation.DoubleInput;
import com.sandwell.JavaSimulation.DoubleListInput;
import com.sandwell.JavaSimulation.DoubleVector;
import com.sandwell.JavaSimulation.EntityInput;
import com.sandwell.JavaSimulation.EntityListInput;
import com.sandwell.JavaSimulation.ErrorException;
import com.sandwell.JavaSimulation.FileEntity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.IntegerVector;
import com.sandwell.JavaSimulation.Keyword;
import com.sandwell.JavaSimulation.ProbabilityDistribution;
import com.sandwell.JavaSimulation.Process;
import com.sandwell.JavaSimulation.Tester;
import com.sandwell.JavaSimulation.Vector;
/**
* Class ModelEntity - JavaSimulation3D
*/
public class ModelEntity extends DisplayEntity {
// Breakdowns
@Keyword(desc = "Reliability is defined as:\n" +
" 100% - (plant breakdown time / total operation time)\n " +
"or\n " +
"(Operational Time)/(Breakdown + Operational Time)",
example = "Object1 Reliability { 0.95 }")
private final DoubleInput availability;
protected double hoursForNextFailure; // The number of working hours required before the next breakdown
protected double iATFailure; // inter arrival time between failures
protected boolean breakdownPending; // true when a breakdown is to occur
protected boolean brokendown; // true => entity is presently broken down
protected boolean maintenance; // true => entity is presently in maintenance
protected boolean associatedBreakdown; // true => entity is presently in Associated Breakdown
protected boolean associatedMaintenance; // true => entity is presently in Associated Maintenance
protected double breakdownStartTime; // Start time of the most recent breakdown
protected double breakdownEndTime; // End time of the most recent breakdown
// Breakdown Probability Distributions
@Keyword(desc = "A ProbabilityDistribution object that governs the duration of breakdowns (in hours).",
example = "Object1 DowntimeDurationDistribution { BreakdownProbDist1 }")
private final EntityInput<ProbabilityDistribution> downtimeDurationDistribution;
@Keyword(desc = "A ProbabilityDistribution object that governs when breakdowns occur (in hours).",
example = "Object1 DowntimeIATDistribution { BreakdownProbDist1 }")
private final EntityInput<ProbabilityDistribution> downtimeIATDistribution;
// Maintenance
@Keyword(desc = "The simulation time for the start of the first maintenance for each maintenance cycle.",
example = "Object1 FirstMaintenanceTime { 24 h }")
protected DoubleListInput firstMaintenanceTimes;
@Keyword(desc = "The time between maintenance activities for each maintenance cycle",
example = "Object1 MaintenanceInterval { 168 h }")
protected DoubleListInput maintenanceIntervals;
@Keyword(desc = "The durations of a single maintenance event for each maintenance cycle.",
example = "Object1 MaintenanceDuration { 336 h }")
protected DoubleListInput maintenanceDurations;
protected IntegerVector maintenancePendings; // Number of maintenance periods that are due
@Keyword(desc = "A Boolean value. Allows scheduled maintenances to be skipped if it overlaps " +
"with another planned maintenance event.",
example = "Object1 SkipMaintenanceIfOverlap { TRUE }")
protected BooleanListInput skipMaintenanceIfOverlap;
@Keyword(desc = "A list of objects that share the maintenance schedule with this object. " +
"In order for the maintenance to start, all objects on this list must be available." +
"This keyword is for Handlers and Signal Blocks only.",
example = "Block1 SharedMaintenance { Block2 Block2 }")
private final EntityListInput<ModelEntity> sharedMaintenanceList;
protected ModelEntity masterMaintenanceEntity; // The entity that has maintenance information
protected boolean performMaintenanceAfterShipDelayPending; // maintenance needs to be done after shipDelay
// Maintenance based on hours of operations
@Keyword(desc = "Working time for the start of the first maintenance for each maintenance cycle",
example = "Object1 FirstMaintenanceOperatingHours { 1000 2500 h }")
private final DoubleListInput firstMaintenanceOperatingHours;
@Keyword(desc = "Working time between one maintenance event and the next for each maintenance cycle",
example = "Object1 MaintenanceOperatingHoursIntervals { 2000 5000 h }")
private final DoubleListInput maintenanceOperatingHoursIntervals;
@Keyword(desc = "Duration of maintenance events based on working hours for each maintenance cycle",
example = "Ship1 MaintenanceOperatingHoursDurations { 24 48 h }")
private final DoubleListInput maintenanceOperatingHoursDurations;
protected IntegerVector maintenanceOperatingHoursPendings; // Number of maintenance periods that are due
protected DoubleVector hoursForNextMaintenanceOperatingHours;
protected double maintenanceStartTime; // Start time of the most recent maintenance
protected double maintenanceEndTime; // End time of the most recent maintenance
protected DoubleVector nextMaintenanceTimes; // next start time for each maintenance
protected double nextMaintenanceDuration; // duration for next maintenance
protected DoubleVector lastScheduledMaintenanceTimes;
@Keyword(desc = "If maintenance has been deferred by the DeferMaintenanceLookAhead keyword " +
"for longer than this time, the maintenance will start even if " +
"there is an object within the lookahead. There must be one entry for each " +
"defined maintenance schedule if DeferMaintenanceLookAhead is used. This" +
"keyword is only used for signal blocks.",
example = "Object1 DeferMaintenanceLimit { 50 50 h }")
private final DoubleListInput deferMaintenanceLimit;
@Keyword(desc = "If the duration of the downtime is longer than this time, equipment will be released",
example = "Object1 DowntimeToReleaseEquipment { 1.0 h }")
protected final DoubleInput downtimeToReleaseEquipment;
@Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is TRUE, " +
"then routes/tasks are released before performing the maintenance in the cycle.",
example = "Object1 ReleaseEquipment { TRUE FALSE FALSE }")
protected final BooleanListInput releaseEquipment;
@Keyword(desc = "A list of Boolean values corresponding to the maintenance cycles. If a value is " +
"TRUE, then maintenance in the cycle can start even if the equipment is presently " +
"working.",
example = "Object1 ForceMaintenance { TRUE FALSE FALSE }")
protected final BooleanListInput forceMaintenance;
// Statistics
@Keyword(desc = "If TRUE, then statistics for this object are " +
"included in the main output report.",
example = "Object1 PrintToReport { TRUE }")
private final BooleanInput printToReport;
// States
protected static Vector stateList = new Vector( 11, 1 ); // List of valid states
private final HashMap<String, StateRecord> stateMap;
protected double workingHours; // Accumulated working time spent in working states
protected DoubleVector hoursPerState; // Elapsed time to date for each state
private static class StateRecord {
String stateName;
int index;
double initializationHours;
double totalHours;
double completedCycleHours;
double currentCycleHours;
public StateRecord(String state, int i) {
stateName = state;
index = i;
}
public int getIndex() {
return index;
}
public String getStateName() {
return stateName;
}
public double getTotalHours() {
return totalHours;
}
public double getCompletedCycleHours() {
return completedCycleHours;
}
@Override
public String toString() {
return getStateName();
}
public void addHours(double dur) {
totalHours += dur;
currentCycleHours += dur;
}
public void collectInitializationStats() {
initializationHours = totalHours;
totalHours = 0.0d;
completedCycleHours = 0.0d;
}
public void collectCycleStats() {
completedCycleHours += currentCycleHours;
currentCycleHours = 0.0d;
}
public void clearReportStats() {
totalHours = 0.0d;
completedCycleHours = 0.0d;
}
public void clearCurrentCycleHours() {
currentCycleHours = 0.0d;
}
}
private double timeOfLastStateUpdate;
private int numberOfCompletedCycles;
protected double lastHistogramUpdateTime; // Last time at which a histogram was updated for this entity
protected double secondToLastHistogramUpdateTime; // Second to last time at which a histogram was updated for this entity
protected DoubleVector lastStartTimePerState; // Last time at which the state changed from some other state to each state
protected DoubleVector secondToLastStartTimePerState; // The second to last time at which the state changed from some other state to each state
private StateRecord presentState; // The present state of the entity
protected double timeOfLastStateChange; // Time at which the state was last changed
protected FileEntity stateReportFile; // The file to store the state information
private String finalLastState = ""; // The final state of the entity (in a sequence of transitional states)
private double timeOfLastPrintedState = 0; // The time that the last state printed in the trace state file
// Graphics
protected final static Color4d breakdownColor = ColourInput.DARK_RED; // Color of the entity in breaking down
protected final static Color4d maintenanceColor = ColourInput.RED; // Color of the entity in maintenance
static {
stateList.addElement( "Idle" );
stateList.addElement( "Working" );
stateList.addElement( "Breakdown" );
stateList.addElement( "Maintenance" );
}
{
maintenanceDurations = new DoubleListInput("MaintenanceDurations", "Maintenance", new DoubleVector());
maintenanceDurations.setValidRange(0.0d, Double.POSITIVE_INFINITY);
maintenanceDurations.setUnits("h");
this.addInput(maintenanceDurations, true, "MaintenanceDuration");
maintenanceIntervals = new DoubleListInput("MaintenanceIntervals", "Maintenance", new DoubleVector());
maintenanceIntervals.setValidRange(0.0d, Double.POSITIVE_INFINITY);
maintenanceIntervals.setUnits("h");
this.addInput(maintenanceIntervals, true, "MaintenanceInterval");
firstMaintenanceTimes = new DoubleListInput("FirstMaintenanceTimes", "Maintenance", new DoubleVector());
firstMaintenanceTimes.setValidRange(0.0d, Double.POSITIVE_INFINITY);
firstMaintenanceTimes.setUnits("h");
this.addInput(firstMaintenanceTimes, true, "FirstMaintenanceTime");
forceMaintenance = new BooleanListInput("ForceMaintenance", "Maintenance", null);
this.addInput(forceMaintenance, true);
releaseEquipment = new BooleanListInput("ReleaseEquipment", "Maintenance", null);
this.addInput(releaseEquipment, true);
availability = new DoubleInput("Reliability", "Breakdowns", 1.0d, 0.0d, 1.0d);
this.addInput(availability, true);
downtimeIATDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeIATDistribution", "Breakdowns", null);
this.addInput(downtimeIATDistribution, true);
downtimeDurationDistribution = new EntityInput<ProbabilityDistribution>(ProbabilityDistribution.class, "DowntimeDurationDistribution", "Breakdowns", null);
this.addInput(downtimeDurationDistribution, true);
downtimeToReleaseEquipment = new DoubleInput("DowntimeToReleaseEquipment", "Breakdowns", 0.0d, 0.0d, Double.POSITIVE_INFINITY);
this.addInput(downtimeToReleaseEquipment, true);
skipMaintenanceIfOverlap = new BooleanListInput("SkipMaintenanceIfOverlap", "Maintenance", new BooleanVector());
this.addInput(skipMaintenanceIfOverlap, true);
deferMaintenanceLimit = new DoubleListInput("DeferMaintenanceLimit", "Maintenance", null);
deferMaintenanceLimit.setValidRange(0.0d, Double.POSITIVE_INFINITY);
deferMaintenanceLimit.setUnits("h");
this.addInput(deferMaintenanceLimit, true);
sharedMaintenanceList = new EntityListInput<ModelEntity>(ModelEntity.class, "SharedMaintenance", "Maintenance", new ArrayList<ModelEntity>(0));
this.addInput(sharedMaintenanceList, true);
firstMaintenanceOperatingHours = new DoubleListInput("FirstMaintenanceOperatingHours", "Maintenance", new DoubleVector());
firstMaintenanceOperatingHours.setValidRange(0.0d, Double.POSITIVE_INFINITY);
firstMaintenanceOperatingHours.setUnits("h");
this.addInput(firstMaintenanceOperatingHours, true);
maintenanceOperatingHoursDurations = new DoubleListInput("MaintenanceOperatingHoursDurations", "Maintenance", new DoubleVector());
maintenanceOperatingHoursDurations.setValidRange(1e-15, Double.POSITIVE_INFINITY);
maintenanceOperatingHoursDurations.setUnits("h");
this.addInput(maintenanceOperatingHoursDurations, true);
maintenanceOperatingHoursIntervals = new DoubleListInput("MaintenanceOperatingHoursIntervals", "Maintenance", new DoubleVector());
maintenanceOperatingHoursIntervals.setValidRange(1e-15, Double.POSITIVE_INFINITY);
maintenanceOperatingHoursIntervals.setUnits("h");
this.addInput(maintenanceOperatingHoursIntervals, true);
printToReport = new BooleanInput("PrintToReport", "Report", true);
this.addInput(printToReport, true);
}
public ModelEntity() {
hoursPerState = new DoubleVector();
lastHistogramUpdateTime = 0.0;
secondToLastHistogramUpdateTime = 0.0;
lastStartTimePerState = new DoubleVector();
secondToLastStartTimePerState = new DoubleVector();
timeOfLastStateChange = 0.0;
hoursForNextFailure = 0.0;
iATFailure = 0.0;
maintenancePendings = new IntegerVector( 1, 1 );
maintenanceOperatingHoursPendings = new IntegerVector( 1, 1 );
hoursForNextMaintenanceOperatingHours = new DoubleVector( 1, 1 );
performMaintenanceAfterShipDelayPending = false;
lastScheduledMaintenanceTimes = new DoubleVector();
breakdownStartTime = 0.0;
breakdownEndTime = Double.POSITIVE_INFINITY;
breakdownPending = false;
brokendown = false;
associatedBreakdown = false;
maintenanceStartTime = 0.0;
maintenanceEndTime = Double.POSITIVE_INFINITY;
maintenance = false;
associatedMaintenance = false;
workingHours = 0.0;
stateMap = new HashMap<String, StateRecord>();
timeOfLastStateChange = 0.0;
initStateMap();
}
/**
* Clear internal properties
*/
public void clearInternalProperties() {
timeOfLastStateChange = 0.0;
hoursForNextFailure = 0.0;
performMaintenanceAfterShipDelayPending = false;
breakdownPending = false;
brokendown = false;
associatedBreakdown = false;
maintenance = false;
associatedMaintenance = false;
workingHours = 0.0;
}
@Override
public void validate()
throws InputErrorException {
super.validate();
this.validateMaintenance();
Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursIntervals.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursIntervals");
Input.validateIndexedLists(firstMaintenanceOperatingHours.getValue(), maintenanceOperatingHoursDurations.getValue(), "FirstMaintenanceOperatingHours", "MaintenanceOperatingHoursDurations");
if( getAvailability() < 1.0 ) {
if( getDowntimeDurationDistribution() == null ) {
throw new InputErrorException("When availability is less than one you must define downtimeDurationDistribution in your input file!");
}
}
if( downtimeIATDistribution.getValue() != null ) {
if( getDowntimeDurationDistribution() == null ) {
throw new InputErrorException("When DowntimeIATDistribution is set, DowntimeDurationDistribution must also be set.");
}
}
if( skipMaintenanceIfOverlap.getValue().size() > 0 )
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), skipMaintenanceIfOverlap.getValue(), "FirstMaintenanceTimes", "SkipMaintenanceIfOverlap");
if( releaseEquipment.getValue() != null )
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), releaseEquipment.getValue(), "FirstMaintenanceTimes", "ReleaseEquipment");
if( forceMaintenance.getValue() != null ) {
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), forceMaintenance.getValue(), "FirstMaintenanceTimes", "ForceMaintenance");
}
if(downtimeDurationDistribution.getValue() != null &&
downtimeDurationDistribution.getValue().getMinimumValue() < 0)
throw new InputErrorException("DowntimeDurationDistribution cannot allow negative values");
if(downtimeIATDistribution.getValue() != null &&
downtimeIATDistribution.getValue().getMinimumValue() < 0)
throw new InputErrorException("DowntimeIATDistribution cannot allow negative values");
}
@Override
public void earlyInit() {
super.earlyInit();
if( downtimeDurationDistribution.getValue() != null ) {
downtimeDurationDistribution.getValue().initialize();
}
if( downtimeIATDistribution.getValue() != null ) {
downtimeIATDistribution.getValue().initialize();
}
}
/**
* Runs after initialization period
*/
public void collectInitializationStats() {
this.updateStateRecordHours();
for ( StateRecord each : stateMap.values() ) {
each.collectInitializationStats();
}
numberOfCompletedCycles = 0;
}
/**
* Runs when cycle is finished
*/
public void collectCycleStats() {
this.updateStateRecordHours();
// finalize cycle for each state record
for ( StateRecord each : stateMap.values() ) {
each.collectCycleStats();
}
numberOfCompletedCycles++;
}
/**
* Runs after each report interval
*/
public void clearReportStats() {
// clear totalHours for each state record
for ( StateRecord each : stateMap.values() ) {
each.clearReportStats();
}
numberOfCompletedCycles = 0;
}
public int getNumberOfCompletedCycles() {
return numberOfCompletedCycles;
}
/**
* Clear the current cycle hours
*/
protected void clearCurrentCycleHours() {
this.updateStateRecordHours();
// clear current cycle hours for each state record
for ( StateRecord each : stateMap.values() ) {
each.clearCurrentCycleHours();
}
}
public void initStateMap() {
// Populate the hash map for the states and StateRecord
stateMap.clear();
for (int i = 0; i < getStateList().size(); i++) {
String state = (String)getStateList().get(i);
StateRecord stateRecord = new StateRecord(state, i);
stateMap.put(state.toLowerCase() , stateRecord);
}
timeOfLastStateUpdate = getCurrentTime();
}
private StateRecord getStateRecordFor(String state) {
return stateMap.get(state.toLowerCase());
}
private StateRecord getStateRecordFor(int index) {
String state = (String)getStateList().get(index);
return getStateRecordFor(state);
}
public double getCompletedCycleHoursFor(String state) {
return getStateRecordFor(state).getCompletedCycleHours();
}
public double getCompletedCycleHoursFor(int index) {
return getStateRecordFor(index).getCompletedCycleHours();
}
public double getCompletedCycleHours() {
double total = 0.0d;
for (int i = 0; i < getStateList().size(); i ++)
total += getStateRecordFor(i).getCompletedCycleHours();
return total;
}
public double getTotalHoursFor(int index) {
return getStateRecordFor(index).getTotalHours();
}
public double getTotalHoursFor(String state) {
return getStateRecordFor(state).getTotalHours();
}
// ******************************************************************************************************
// INPUT
// ******************************************************************************************************
public void validateMaintenance() {
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceIntervals.getValue(), "FirstMaintenanceTimes", "MaintenanceIntervals");
Input.validateIndexedLists(firstMaintenanceTimes.getValue(), maintenanceDurations.getValue(), "FirstMaintenanceTimes", "MaintenanceDurations");
for( int i = 0; i < maintenanceIntervals.getValue().size(); i++ ) {
if( maintenanceIntervals.getValue().get( i ) < maintenanceDurations.getValue().get( i ) ) {
throw new InputErrorException("MaintenanceInterval should be greater than MaintenanceDuration (%f) <= (%f)",
maintenanceIntervals.getValue().get(i), maintenanceDurations.getValue().get(i));
}
}
}
// ******************************************************************************************************
// INITIALIZATION METHODS
// ******************************************************************************************************
public void clearStatistics() {
for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
hoursForNextMaintenanceOperatingHours.set( i, hoursForNextMaintenanceOperatingHours.get( i ) - this.getWorkingHours() );
}
initHoursPerState();
timeOfLastStateChange = getCurrentTime();
// Determine the time for the first breakdown event
/*if ( downtimeIATDistribution == null ) {
if( breakdownSeed != 0 ) {
breakdownRandGen.initialiseWith( breakdownSeed );
hoursForNextFailure = breakdownRandGen.getUniformFrom_To( 0.5*iATFailure, 1.5*iATFailure );
} else {
hoursForNextFailure = getNextBreakdownIAT();
}
}
else {
hoursForNextFailure = getNextBreakdownIAT();
}*/
}
public void initializeStatistics() {
initHoursPerState();
timeOfLastStateChange = getCurrentTime();
}
/**
* *!*!*!*! OVERLOAD !*!*!*!*
* Initialize statistics
*/
public void initialize() {
brokendown = false;
maintenance = false;
associatedBreakdown = false;
associatedMaintenance = false;
// Create state trace file if required
if (testFlag(FLAG_TRACESTATE)) {
String fileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + "-" + this.getName() + ".trc";
stateReportFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
}
initHoursPerState();
lastStartTimePerState.fillWithEntriesOf( getStateList().size(), 0.0 );
secondToLastStartTimePerState.fillWithEntriesOf( getStateList().size(), 0.0 );
timeOfLastStateChange = getCurrentTime();
workingHours = 0.0;
// Calculate the average downtime duration if distributions are used
double average = 0.0;
if(getDowntimeDurationDistribution() != null)
average = getDowntimeDurationDistribution().getExpectedValue();
// Calculate the average downtime inter-arrival time
if( (getAvailability() == 1.0 || average == 0.0) ) {
iATFailure = 10.0E10;
}
else {
if( getDowntimeIATDistribution() != null ) {
iATFailure = getDowntimeIATDistribution().getExpectedValue();
// Adjust the downtime inter-arrival time to get the specified availability
if( ! Tester.equalCheckTolerance( iATFailure, ( (average / (1.0 - getAvailability())) - average ) ) ) {
getDowntimeIATDistribution().setValueFactor_For( ( (average / (1.0 - getAvailability())) - average) / iATFailure, this );
iATFailure = getDowntimeIATDistribution().getExpectedValue();
}
}
else {
iATFailure = ( (average / (1.0 - getAvailability())) - average );
}
}
// Determine the time for the first breakdown event
hoursForNextFailure = getNextBreakdownIAT();
int ind = this.indexOfState( "Idle" );
if( ind != -1 ) {
this.setPresentState( "Idle" );
}
brokendown = false;
// Start the maintenance network
if( firstMaintenanceTimes.getValue().size() != 0 ) {
maintenancePendings.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), 0 );
lastScheduledMaintenanceTimes.fillWithEntriesOf( firstMaintenanceTimes.getValue().size(), Double.POSITIVE_INFINITY );
this.doMaintenanceNetwork();
}
// calculate hours for first operating hours breakdown
for ( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
hoursForNextMaintenanceOperatingHours.add( firstMaintenanceOperatingHours.getValue().get( i ) );
maintenanceOperatingHoursPendings.add( 0 );
}
}
// ******************************************************************************************************
// ACCESSOR METHODS
// ******************************************************************************************************
/**
* Return the time at which the most recent maintenance is scheduled to end
*/
public double getMaintenanceEndTime() {
return maintenanceEndTime;
}
/**
* Return the time at which a the most recent breakdown is scheduled to end
*/
public double getBreakdownEndTime() {
return breakdownEndTime;
}
public double getTimeOfLastStateChange() {
return timeOfLastStateChange;
}
/**
* Returns the availability proportion.
*/
public double getAvailability() {
return availability.getValue();
}
public DoubleListInput getFirstMaintenanceTimes() {
return firstMaintenanceTimes;
}
public boolean getPrintToReport() {
return printToReport.getValue();
}
public boolean isBrokendown() {
return brokendown;
}
public boolean isBreakdownPending() {
return breakdownPending;
}
public boolean isInAssociatedBreakdown() {
return associatedBreakdown;
}
public boolean isInMaintenance() {
return maintenance;
}
public boolean isInAssociatedMaintenance() {
return associatedMaintenance;
}
public boolean isInService() {
return ( brokendown || maintenance || associatedBreakdown || associatedMaintenance );
}
public void setBrokendown( boolean bool ) {
brokendown = bool;
this.setPresentState();
}
public void setMaintenance( boolean bool ) {
maintenance = bool;
this.setPresentState();
}
public void setAssociatedBreakdown( boolean bool ) {
associatedBreakdown = bool;
}
public void setAssociatedMaintenance( boolean bool ) {
associatedMaintenance = bool;
}
public ProbabilityDistribution getDowntimeDurationDistribution() {
return downtimeDurationDistribution.getValue();
}
public double getDowntimeToReleaseEquipment() {
return downtimeToReleaseEquipment.getValue();
}
public boolean hasServiceDefined() {
return( maintenanceDurations.getValue().size() > 0 || getDowntimeDurationDistribution() != null );
}
// ******************************************************************************************************
// HOURS AND STATES
// ******************************************************************************************************
/**
* Updates the statistics for the present status.
*/
public void updateHours() {
if( getPresentState().length() == 0 ) {
timeOfLastStateChange = getCurrentTime();
return;
}
int index = this.indexOfState( getPresentState() );
if( index == -1 ) {
throw new ErrorException( "Present state not found in StateList." );
}
double dur = getCurrentTime() - timeOfLastStateChange;
if( dur > 0.0 ) {
/*int index = getStateList().indexOfString( presentState );
if( index == -1 ) {
throw new ErrorException( " Present state not found in StateList." );
}
hoursPerState.addAt( dur, index );*/
addHoursAt(dur, getPresentStateIndex());
timeOfLastStateChange = getCurrentTime();
// Update working hours, if required
//if( getWorkingStateList().contains( presentState ) ) {
if( this.isWorking() ) {
workingHours += dur;
}
}
}
public void updateStateRecordHours() {
if (presentState == null) {
timeOfLastStateUpdate = getCurrentTime();
return;
}
double time = getCurrentTime();
if (time != timeOfLastStateUpdate) {
presentState.addHours(time - timeOfLastStateUpdate);
timeOfLastStateUpdate = getCurrentTime();
}
}
public void initHoursPerState() {
hoursPerState.clear();
if( getStateList().size() != 0 )
hoursPerState.fillWithEntriesOf( getStateList().size(), 0.0 );
}
/**
* Return true if the entity is working
*/
public boolean isWorking() {
return false;
}
/**
* Returns the present status.
*/
public String getPresentState() {
if (presentState == null)
return "";
return presentState.getStateName();
}
public boolean presentStateEquals(String state) {
return getPresentState().equals(state);
}
public boolean presentStateMatches(String state) {
return getPresentState().equalsIgnoreCase(state);
}
public boolean presentStateStartsWith(String prefix) {
return getPresentState().startsWith(prefix);
}
public boolean presentStateEndsWith(String suffix) {
return getPresentState().endsWith(suffix);
}
protected int getPresentStateIndex() {
if (presentState == null)
return -1;
return presentState.getIndex();
}
public void setPresentState() {}
/**
* Updates the statistics, then sets the present status to be the specified value.
*/
public void setPresentState( String state ) {
if( traceFlag ) this.trace("setState( "+state+" )");
if( traceFlag ) this.traceLine(" Old State = "+getPresentState() );
if( ! presentStateEquals( state ) ) {
if (testFlag(FLAG_TRACESTATE)) this.printStateTrace(state);
int ind = this.indexOfState( state );
if( ind != -1 ) {
this.updateHours();
this.updateStateRecordHours();
presentState = getStateRecordFor(state);
if( lastStartTimePerState.size() > 0 ) {
if( secondToLastStartTimePerState.size() > 0 ) {
secondToLastStartTimePerState.set( ind, lastStartTimePerState.get( ind ) );
}
lastStartTimePerState.set( ind, getCurrentTime() );
}
}
else {
throw new ErrorException( this + " Specified state: " + state + " was not found in the StateList: " + this.getStateList() );
}
}
}
/**
* Print that state information on the trace state log file
*/
public void printStateTrace( String state ) {
// First state ever
if( finalLastState.equals("") ) {
finalLastState = state;
stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n",
0.0d, this.getName(), getPresentState(), formatNumber(getCurrentTime())));
stateReportFile.flush();
timeOfLastPrintedState = getCurrentTime();
}
else {
// The final state in a sequence from the previous state change (one step behind)
if ( ! Tester.equalCheckTimeStep( timeOfLastPrintedState, getCurrentTime() ) ) {
stateReportFile.putString(String.format("%.5f %s.setState( \"%s\" ) dt = %s\n",
timeOfLastPrintedState, this.getName(), finalLastState, formatNumber(getCurrentTime() - timeOfLastPrintedState)));
// for( int i = 0; i < stateTraceRelatedModelEntities.size(); i++ ) {
// ModelEntitiy each = (ModelEntitiy) stateTraceRelatedModelEntities.get( i );
// putString( )
// }
stateReportFile.flush();
timeOfLastPrintedState = getCurrentTime();
}
finalLastState = state;
}
}
/**
* Returns the amount of time spent in the specified status.
*/
public double getCurrentCycleHoursFor( String state ) {
int index = this.indexOfState( state );
if( index != -1 ) {
this.updateHours();
return getCurrentCycleHoursFor( index );
}
else {
throw new ErrorException( "Specified state: " + state + " was not found in the StateList." );
}
}
/**
* Return spent hours for a given state at the index in stateList
*/
public double getCurrentCycleHoursFor(int index) {
return hoursPerState.get(index);
}
/**
* Set the last time a histogram was updated for this entity
*/
public void setLastHistogramUpdateTime( double time ) {
secondToLastHistogramUpdateTime = lastHistogramUpdateTime;
lastHistogramUpdateTime = time;
}
/**
* Returns the time from the start of the start state to the start of the end state
*/
public double getTimeFromStartState_ToEndState( String startState, String endState) {
// Determine the index of the start state
int startIndex = this.indexOfState( startState );
if( startIndex == -1 ) {
throw new ErrorException( "Specified state: " + startState + " was not found in the StateList." );
}
// Determine the index of the end state
int endIndex = this.indexOfState( endState );
if( endIndex == -1 ) {
throw new ErrorException( "Specified state: " + endState + " was not found in the StateList." );
}
// Is the start time of the end state greater or equal to the start time of the start state?
if( lastStartTimePerState.get( endIndex ) >= lastStartTimePerState.get( startIndex ) ) {
// If either time was not in the present cycle, return NaN
if( lastStartTimePerState.get( endIndex ) <= lastHistogramUpdateTime ||
lastStartTimePerState.get( startIndex ) <= lastHistogramUpdateTime ) {
return Double.NaN;
}
// Return the time from the last start time of the start state to the last start time of the end state
return lastStartTimePerState.get( endIndex ) - lastStartTimePerState.get( startIndex );
}
else {
// If either time was not in the present cycle, return NaN
if( lastStartTimePerState.get( endIndex ) <= lastHistogramUpdateTime ||
secondToLastStartTimePerState.get( startIndex ) <= secondToLastHistogramUpdateTime ) {
return Double.NaN;
}
// Return the time from the second to last start time of the start date to the last start time of the end state
return lastStartTimePerState.get( endIndex ) - secondToLastStartTimePerState.get( startIndex );
}
}
/**
* Return the commitment
*/
public double getCommitment() {
return 1.0 - this.getFractionOfTimeForState( "Idle" );
}
/**
* Return the fraction of time for the given status
*/
public double getFractionOfTimeForState( String aState ) {
if( getCurrentCycleHours() > 0.0 ) {
return ((this.getCurrentCycleHoursFor( aState ) / getCurrentCycleHours()) );
}
else {
return 0.0;
}
}
/**
* Return the percentage of time for the given status
*/
public double getPercentageOfTimeForState( String aState ) {
if( getCurrentCycleHours() > 0.0 ) {
return ((this.getCurrentCycleHoursFor( aState ) / getCurrentCycleHours()) * 100.0);
}
else {
return 0.0;
}
}
/**
* Returns the number of hours the entity is in use.
* *!*!*!*! OVERLOAD !*!*!*!*
*/
public double getWorkingHours() {
this.updateHours();
return workingHours;
}
/**
* Add hours to the specified state by index on the stateList
*/
protected void addHoursAt(double dur, int index) {
hoursPerState.addAt(dur, index);
}
public Vector getStateList() {
return stateList;
}
public int indexOfState( String state ) {
StateRecord stateRecord = stateMap.get( state.toLowerCase() );
if (stateRecord != null)
return stateRecord.getIndex();
return -1;
}
/**
* Return total number of states
*/
public int getNumberOfStates() {
return hoursPerState.size();
}
/**
* Return the total hours in current cycle for all the states
*/
public double getCurrentCycleHours() {
return hoursPerState.sum();
}
// *******************************************************************************************************
// MAINTENANCE METHODS
// *******************************************************************************************************
/**
* Perform tasks required before a maintenance period
*/
public void doPreMaintenance() {
//@debug@ cr 'Entity should be overloaded' print
}
/**
* Start working again following a breakdown or maintenance period
*/
public void restart() {
//@debug@ cr 'Entity should be overloaded' print
}
/**
* Disconnect routes, release truck assignments, etc. when performing maintenance or breakdown
*/
public void releaseEquipment() {}
public boolean releaseEquipmentForMaintenanceSchedule( int index ) {
if( releaseEquipment.getValue() == null )
return true;
return releaseEquipment.getValue().get( index );
}
public boolean forceMaintenanceSchedule( int index ) {
if( forceMaintenance.getValue() == null )
return false;
return forceMaintenance.getValue().get( index );
}
/**
* Perform all maintenance schedules that are due
*/
public void doMaintenance() {
// scheduled maintenance
for( int index = 0; index < maintenancePendings.size(); index++ ) {
if( this.getMaintenancePendings().get( index ) > 0 ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.doMaintenance(index);
}
}
// Operating hours maintenance
for( int index = 0; index < maintenanceOperatingHoursPendings.size(); index++ ) {
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( index ) ) {
hoursForNextMaintenanceOperatingHours.set(index, this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( index ));
maintenanceOperatingHoursPendings.addAt( 1, index );
this.doMaintenanceOperatingHours(index);
}
}
}
/**
* Perform all the planned maintenance that is due for the given schedule
*/
public void doMaintenance( int index ) {
double wait;
if( masterMaintenanceEntity != null ) {
wait = masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index );
}
else {
wait = this.getMaintenanceDurations().getValue().get( index );
}
if( wait > 0.0 && maintenancePendings.get( index ) != 0 ) {
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" );
// Keep track of the start and end of maintenance times
maintenanceStartTime = getCurrentTime();
if( masterMaintenanceEntity != null ) {
maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * masterMaintenanceEntity.getMaintenanceDurations().getValue().get( index ) );
}
else {
maintenanceEndTime = maintenanceStartTime + ( maintenancePendings.get( index ) * maintenanceDurations.getValue().get( index ) );
}
this.setPresentState( "Maintenance" );
maintenance = true;
this.doPreMaintenance();
// Release equipment if necessary
if( this.releaseEquipmentForMaintenanceSchedule( index ) ) {
this.releaseEquipment();
}
while( maintenancePendings.get( index ) != 0 ) {
maintenancePendings.subAt( 1, index );
scheduleWait( wait );
// If maintenance pending goes negative, something is wrong
if( maintenancePendings.get( index ) < 0 ) {
this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenancePendings.get( index ) );
}
}
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" );
// The maintenance is over
this.setPresentState( "Idle" );
maintenance = false;
this.restart();
}
}
/**
* Perform all the planned maintenance that is due
*/
public void doMaintenanceOperatingHours( int index ) {
if(maintenanceOperatingHoursPendings.get( index ) == 0 )
return;
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- start of maintenance" );
// Keep track of the start and end of maintenance times
maintenanceStartTime = getCurrentTime();
maintenanceEndTime = maintenanceStartTime +
(maintenanceOperatingHoursPendings.get( index ) * getMaintenanceOperatingHoursDurationFor(index));
this.setPresentState( "Maintenance" );
maintenance = true;
this.doPreMaintenance();
while( maintenanceOperatingHoursPendings.get( index ) != 0 ) {
//scheduleWait( maintenanceDurations.get( index ) );
scheduleWait( maintenanceEndTime - maintenanceStartTime );
maintenanceOperatingHoursPendings.subAt( 1, index );
// If maintenance pending goes negative, something is wrong
if( maintenanceOperatingHoursPendings.get( index ) < 0 ) {
this.error( "ModelEntity.doMaintenance_Wait()", "Maintenace pending should not be negative", "maintenacePending = "+maintenanceOperatingHoursPendings.get( index ) );
}
}
if( traceFlag ) this.trace( "ModelEntity.doMaintenance_Wait() -- end of maintenance" );
// The maintenance is over
maintenance = false;
this.setPresentState( "Idle" );
this.restart();
}
/**
* Check if a maintenance is due. if so, try to perform the maintenance
*/
public boolean checkMaintenance() {
if( traceFlag ) this.trace( "checkMaintenance()" );
if( checkOperatingHoursMaintenance() ) {
return true;
}
// List of all entities going to maintenance
ArrayList<ModelEntity> sharedMaintenanceEntities;
// This is not a master maintenance entity
if( masterMaintenanceEntity != null ) {
sharedMaintenanceEntities = masterMaintenanceEntity.getSharedMaintenanceList();
}
// This is a master maintenance entity
else {
sharedMaintenanceEntities = getSharedMaintenanceList();
}
// If this entity is in shared maintenance relation with a group of entities
if( sharedMaintenanceEntities.size() > 0 || masterMaintenanceEntity != null ) {
// Are all entities in the group ready for maintenance
if( this.areAllEntitiesAvailable() ) {
// For every entity in the shared maintenance list plus the master maintenance entity
for( int i=0; i <= sharedMaintenanceEntities.size(); i++ ) {
ModelEntity aModel;
// Locate master maintenance entity( after all entity in shared maintenance list have been taken care of )
if( i == sharedMaintenanceEntities.size() ) {
// This entity is manster maintenance entity
if( masterMaintenanceEntity == null ) {
aModel = this;
}
// This entity is on the shared maintenannce list of the master maintenance entity
else {
aModel = masterMaintenanceEntity;
}
}
// Next entity in the shared maintenance list
else {
aModel = sharedMaintenanceEntities.get( i );
}
// Check for aModel maintenances
for( int index = 0; index < maintenancePendings.size(); index++ ) {
if( aModel.getMaintenancePendings().get( index ) > 0 ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
aModel.startProcess("doMaintenance", index);
}
}
}
return true;
}
else {
return false;
}
}
// This block is maintained indipendently
else {
// Check for maintenances
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 ) {
if( this.canStartMaintenance( i ) ) {
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + i );
this.startProcess("doMaintenance", i);
return true;
}
}
}
}
return false;
}
/**
* Determine how many hours of maintenance is scheduled between startTime and endTime
*/
public double getScheduledMaintenanceHoursForPeriod( double startTime, double endTime ) {
if( traceFlag ) this.trace("Handler.getScheduledMaintenanceHoursForPeriod( "+startTime+", "+endTime+" )" );
double totalHours = 0.0;
double firstTime = 0.0;
// Add on hours for all pending maintenance
for( int i=0; i < maintenancePendings.size(); i++ ) {
totalHours += maintenancePendings.get( i ) * maintenanceDurations.getValue().get( i );
}
if( traceFlag ) this.traceLine( "Hours of pending maintenances="+totalHours );
// Add on hours for all maintenance scheduled to occur in the given period from startTime to endTime
for( int i=0; i < maintenancePendings.size(); i++ ) {
// Find the first time that maintenance is scheduled after startTime
firstTime = firstMaintenanceTimes.getValue().get( i );
while( firstTime < startTime ) {
firstTime += maintenanceIntervals.getValue().get( i );
}
if( traceFlag ) this.traceLine(" first time maintenance "+i+" is scheduled after startTime= "+firstTime );
// Now have the first maintenance start time after startTime
// Add all maintenances that lie in the given interval
while( firstTime < endTime ) {
if( traceFlag ) this.traceLine(" Checking for maintenances for period:"+firstTime+" to "+endTime );
// Add the maintenance
totalHours += maintenanceDurations.getValue().get( i );
// Update the search period
endTime += maintenanceDurations.getValue().get( i );
// Look for next maintenance in new interval
firstTime += maintenanceIntervals.getValue().get( i );
if( traceFlag ) this.traceLine(" Adding Maintenance duration = "+maintenanceDurations.getValue().get( i ) );
}
}
// Return the total hours of maintenance scheduled from startTime to endTime
if( traceFlag ) this.traceLine( "Maintenance hours to add= "+totalHours );
return totalHours;
}
public boolean checkOperatingHoursMaintenance() {
if( traceFlag ) this.trace("checkOperatingHoursMaintenance()");
// Check for maintenances
for( int i = 0; i < getMaintenanceOperatingHoursIntervals().size(); i++ ) {
// If the entity is not available, maintenance cannot start
if( ! this.canStartMaintenance( i ) )
continue;
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) {
hoursForNextMaintenanceOperatingHours.set(i, (this.getWorkingHours() + getMaintenanceOperatingHoursIntervals().get( i )));
maintenanceOperatingHoursPendings.addAt( 1, i );
if( traceFlag ) this.trace( "Starting Maintenance Operating Hours Schedule : " + i );
this.startProcess("doMaintenanceOperatingHours", i);
return true;
}
}
return false;
}
/**
* Wrapper method for doMaintenance_Wait.
*/
public void doMaintenanceNetwork() {
this.startProcess("doMaintenanceNetwork_Wait");
}
/**
* Network for planned maintenance.
* This method should be called in the initialize method of the specific entity.
*/
public void doMaintenanceNetwork_Wait() {
// Initialize schedules
for( int i=0; i < maintenancePendings.size(); i++ ) {
maintenancePendings.set( i, 0 );
}
nextMaintenanceTimes = new DoubleVector(firstMaintenanceTimes.getValue());
nextMaintenanceDuration = 0;
// Find the next maintenance event
int index = 0;
double earliestTime = Double.POSITIVE_INFINITY;
for( int i=0; i < nextMaintenanceTimes.size(); i++ ) {
double time = nextMaintenanceTimes.get( i );
if( Tester.lessCheckTolerance( time, earliestTime ) ) {
earliestTime = time;
index = i;
nextMaintenanceDuration = maintenanceDurations.getValue().get( i );
}
}
// Make sure that maintenance for entities on the shared list are being called after those entities have been initialize (AT TIME ZERO)
scheduleLastLIFO();
while( true ) {
double dt = earliestTime - getCurrentTime();
// Wait for the maintenance check time
if( dt > Process.getEventTolerance() ) {
scheduleWait( dt );
}
// Increment the number of maintenances due for the entity
maintenancePendings.addAt( 1, index );
// If this is a master maintenance entity
if (getSharedMaintenanceList().size() > 0) {
// If all the entities on the shared list are ready for maintenance
if( this.areAllEntitiesAvailable() ) {
// Put this entity to maintenance
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.startProcess("doMaintenance", index);
}
}
// If this entity is maintained independently
else {
// Do maintenance if possible
if( ! this.isInService() && this.canStartMaintenance( index ) ) {
// if( traceFlag ) this.trace( "doMaintenanceNetwork_Wait: Starting Maintenance. PresentState = "+presentState+" IsAvailable? = "+this.isAvailable() );
if( traceFlag ) this.trace( "Starting Maintenance Schedule: " + index );
this.startProcess("doMaintenance", index);
}
// Keep track of the time the maintenance was attempted
else {
lastScheduledMaintenanceTimes.set( index, getCurrentTime() );
// If skipMaintenance was defined, cancel the maintenance
if( this.shouldSkipMaintenance( index ) ) {
// if a different maintenance is due, cancel this maintenance
boolean cancelMaintenance = false;
for( int i=0; i < maintenancePendings.size(); i++ ) {
if( i != index ) {
if( maintenancePendings.get( i ) > 0 ) {
cancelMaintenance = true;
break;
}
}
}
if( cancelMaintenance || this.isInMaintenance() ) {
maintenancePendings.subAt( 1, index );
}
}
// Do a check after the limit has expired
if( this.getDeferMaintenanceLimit( index ) > 0.0 ) {
this.startProcess( "scheduleCheckMaintenance", this.getDeferMaintenanceLimit( index ) );
}
}
}
// Determine the next maintenance time
nextMaintenanceTimes.addAt( maintenanceIntervals.getValue().get( index ), index );
// Find the next maintenance event
index = 0;
earliestTime = Double.POSITIVE_INFINITY;
for( int i=0; i < nextMaintenanceTimes.size(); i++ ) {
double time = nextMaintenanceTimes.get( i );
if( Tester.lessCheckTolerance( time, earliestTime ) ) {
earliestTime = time;
index = i;
nextMaintenanceDuration = maintenanceDurations.getValue().get( i );
}
}
}
}
public double getDeferMaintenanceLimit( int index ) {
if( deferMaintenanceLimit.getValue() == null )
return 0.0d;
return deferMaintenanceLimit.getValue().get( index );
}
public void scheduleCheckMaintenance( double wait ) {
scheduleWait( wait );
this.checkMaintenance();
}
public boolean shouldSkipMaintenance( int index ) {
if( skipMaintenanceIfOverlap.getValue().size() == 0 )
return false;
return skipMaintenanceIfOverlap.getValue().get( index );
}
/**
* Return TRUE if there is a pending maintenance for any schedule
*/
public boolean isMaintenancePending() {
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 ) {
return true;
}
}
for( int i = 0; i < hoursForNextMaintenanceOperatingHours.size(); i++ ) {
if( this.getWorkingHours() > hoursForNextMaintenanceOperatingHours.get( i ) ) {
return true;
}
}
return false;
}
public boolean isForcedMaintenancePending() {
if( forceMaintenance.getValue() == null )
return false;
for( int i = 0; i < maintenancePendings.size(); i++ ) {
if( maintenancePendings.get( i ) > 0 && forceMaintenance.getValue().get(i) ) {
return true;
}
}
return false;
}
public ArrayList<ModelEntity> getSharedMaintenanceList () {
return sharedMaintenanceList.getValue();
}
public IntegerVector getMaintenancePendings () {
return maintenancePendings;
}
public DoubleListInput getMaintenanceDurations() {
return maintenanceDurations;
}
/**
* Return the start of the next scheduled maintenance time if not in maintenance,
* or the start of the current scheduled maintenance time if in maintenance
*/
public double getNextMaintenanceStartTime() {
if( nextMaintenanceTimes == null )
return Double.POSITIVE_INFINITY;
else
return nextMaintenanceTimes.getMin();
}
/**
* Return the duration of the next maintenance event (assuming only one pending)
*/
public double getNextMaintenanceDuration() {
return nextMaintenanceDuration;
}
// Shows if an Entity would ever go on service
public boolean hasServiceScheduled() {
if( firstMaintenanceTimes.getValue().size() != 0 || masterMaintenanceEntity != null ) {
return true;
}
return false;
}
public void setMasterMaintenanceBlock( ModelEntity aModel ) {
masterMaintenanceEntity = aModel;
}
// *******************************************************************************************************
// BREAKDOWN METHODS
// *******************************************************************************************************
/**
* No Comments Given.
*/
public void calculateTimeOfNextFailure() {
hoursForNextFailure = (this.getWorkingHours() + this.getNextBreakdownIAT());
}
/**
* Activity Network for Breakdowns.
*/
public void doBreakdown() {
}
/**
* Prints the header for the entity's state list.
* @return bottomLine contains format for each column of the bottom line of the group report
*/
public IntegerVector printUtilizationHeaderOn( FileEntity anOut ) {
IntegerVector bottomLine = new IntegerVector();
if( getStateList().size() != 0 ) {
anOut.putStringTabs( "Name", 1 );
bottomLine.add( ReportAgent.BLANK );
int doLoop = getStateList().size();
for( int x = 0; x < doLoop; x++ ) {
String state = (String)getStateList().get( x );
anOut.putStringTabs( state, 1 );
bottomLine.add( ReportAgent.AVERAGE_PCT_ONE_DEC );
}
anOut.newLine();
}
return bottomLine;
}
/**
* Print the entity's name and percentage of hours spent in each state.
* @return columnValues are the values for each column in the group report (0 if the value is a String)
*/
public DoubleVector printUtilizationOn( FileEntity anOut ) {
double total;
DoubleVector columnValues = new DoubleVector();
this.updateHours();
if( getNumberOfStates() != 0 ) {
total = getCurrentCycleHours();
if( !(total == 0.0) ) {
this.updateHours();
anOut.putStringTabs( getName(), 1 );
columnValues.add( 0.0 );
for( int i = 0; i < getNumberOfStates(); i++ ) {
double value = getTotalHoursFor( i ) / total;
anOut.putDoublePercentWithDecimals( value, 1 );
anOut.putTabs( 1 );
columnValues.add( value );
}
anOut.newLine();
}
}
return columnValues;
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean isAvailable() {
throw new ErrorException( "Must override isAvailable in any subclass of ModelEntity." );
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean canStartMaintenance( int index ) {
return isAvailable();
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean canStartForcedMaintenance() {
return isAvailable();
}
/**
* This method must be overridden in any subclass of ModelEntity.
*/
public boolean areAllEntitiesAvailable() {
throw new ErrorException( "Must override areAllEntitiesAvailable in any subclass of ModelEntity." );
}
/**
* Return the time of the next breakdown duration
*/
public double getBreakdownDuration() {
// if( traceFlag ) this.trace( "getBreakdownDuration()" );
// If a distribution was specified, then select a duration randomly from the distribution
if ( getDowntimeDurationDistribution() != null ) {
return getDowntimeDurationDistribution().nextValue();
}
else {
return 0.0;
}
}
/**
* Return the time of the next breakdown IAT
*/
public double getNextBreakdownIAT() {
if( getDowntimeIATDistribution() != null ) {
return getDowntimeIATDistribution().nextValue();
}
else {
return iATFailure;
}
}
public double getHoursForNextFailure() {
return hoursForNextFailure;
}
public void setHoursForNextFailure( double hours ) {
hoursForNextFailure = hours;
}
/**
Returns a vector of strings describing the ModelEntity.
Override to add details
@return Vector - tab delimited strings describing the DisplayEntity
**/
@Override
public Vector getInfo() {
Vector info = super.getInfo();
if ( presentStateEquals("") )
info.addElement( "Present State\t<no state>" );
else
info.addElement( "Present State" + "\t" + getPresentState() );
return info;
}
protected DoubleVector getMaintenanceOperatingHoursIntervals() {
return maintenanceOperatingHoursIntervals.getValue();
}
protected double getMaintenanceOperatingHoursDurationFor(int index) {
return maintenanceOperatingHoursDurations.getValue().get(index);
}
protected ProbabilityDistribution getDowntimeIATDistribution() {
return downtimeIATDistribution.getValue();
}
} | JS3D: make getTotalHoursFor(state) to return up-to-date hours
Signed-off-by: Ali Marandi <[email protected]>
Signed-off-by: Harvey Harrison <[email protected]>
| src/main/java/com/sandwell/JavaSimulation3D/ModelEntity.java | JS3D: make getTotalHoursFor(state) to return up-to-date hours | <ide><path>rc/main/java/com/sandwell/JavaSimulation3D/ModelEntity.java
<ide> }
<ide>
<ide> public double getTotalHoursFor(String state) {
<del> return getStateRecordFor(state).getTotalHours();
<add> StateRecord rec = getStateRecordFor(state);
<add> double hours = rec.getTotalHours();
<add> if (presentState == rec)
<add> hours += getCurrentTime() - timeOfLastStateUpdate;
<add>
<add> return hours;
<ide> }
<ide>
<ide> // ****************************************************************************************************** |
|
Java | lgpl-2.1 | 2feb4e2c86a211f3841ed3f546644d8e15e76dd3 | 0 | xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.store.migration.hibernate;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.hibernate.boot.Metadata;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.internal.store.hibernate.HibernateStore;
import com.xpn.xwiki.stats.impl.RefererStats;
import com.xpn.xwiki.stats.impl.VisitStats;
import com.xpn.xwiki.store.DatabaseProduct;
import com.xpn.xwiki.store.migration.DataMigrationException;
import com.xpn.xwiki.store.migration.XWikiDBVersion;
/**
* This migration aims at applying the fix done on https://jira.xwiki.org/browse/XWIKI-15215 (change the type of some
* column so that they fit in the maximum allowed maximum row size for the used table type) instances older than
* 11.3RC1. Without this it's difficult to migrate to utf8mb3. It's also a requirement for
* {@link AbstractResizeMigration}.
* <p>
* The columns are:
* <ul>
* <li>LegacyEvent/activitystream_events
* <ul>
* <li>url</li>
* <li>title</li>
* <li>body</li>
* <li>param1</li>
* <li>param2</li>
* <li>param3</li>
* <li>param4</li>
* <li>param5</li>
* </ul>
* </li>
* <li>RefererStats/xwikistatsreferer
* <ul>
* <li>referer</li>
* </ul>
* </li>
* <li>VisitStats/xwikistatsvisit
* <ul>
* <li>userAgent</li>
* <li>cookie</li>
* </ul>
* </li>
* <li>XWikiPreferences/xwikipreferences
* <ul>
* <li>leftPanels</li>
* <li>rightPanels</li>
* <li>documentBundles</li>
* </ul>
* </li>
* </ul>
*
* @version $Id$
* @since 13.2RC1
* @since 12.10.6
*/
@Component
@Named("R130200000XWIKI17200")
@Singleton
public class R130200000XWIKI17200DataMigration extends AbstractHibernateDataMigration
{
@Inject
private Logger logger;
@Inject
private HibernateStore hibernateStore;
@Override
public String getDescription()
{
return "Make sure the database follow the currently expected type for some large string columns.";
}
@Override
public XWikiDBVersion getVersion()
{
return new XWikiDBVersion(130200000);
}
@Override
protected void hibernateMigrate() throws DataMigrationException, XWikiException
{
// Nothing to do here, everything's done as part of Liquibase pre update
}
@Override
public boolean shouldExecute(XWikiDBVersion startupVersion)
{
// Only really required for MySQL since https://jira.xwiki.org/browse/XWIKI-15215 was only affecting MySQL
return this.hibernateStore.getDatabaseProductName() == DatabaseProduct.MYSQL;
}
@Override
public String getPreHibernateLiquibaseChangeLog() throws DataMigrationException
{
StringBuilder builder = new StringBuilder();
Map<String, List<String>> map = new HashMap<>();
map.put("org.xwiki.eventstream.store.internal.LegacyEvent",
Arrays.asList("url", "title", "body", "param1", "param2", "param3", "param4", "param5"));
map.put(RefererStats.class.getName(), Arrays.asList("referer"));
map.put(VisitStats.class.getName(), Arrays.asList("userAgent", "cookie"));
map.put("XWiki.XWikiPreferences", Arrays.asList("leftPanels", "rightPanels", "documentBundles"));
try (SessionImplementor session = (SessionImplementor) this.hibernateStore.getSessionFactory().openSession()) {
JdbcConnectionAccess jdbcConnectionAccess = session.getJdbcConnectionAccess();
try (Connection connection = jdbcConnectionAccess.obtainConnection()) {
DatabaseMetaData databaseMetaData = connection.getMetaData();
// Get rid of XWV_COOKIE key leftover if it exist
deleteIndexIfExist(VisitStats.class, "xwv_cookie", databaseMetaData, builder);
// Update properties
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
for (String property : entry.getValue()) {
maybeUpdateField(databaseMetaData, entry.getKey(), property, builder);
}
}
}
} catch (SQLException e) {
throw new DataMigrationException("Error while extracting metadata", e);
}
if (builder.length() > 0) {
return String.format("<changeSet author=\"xwiki\" id=\"R%s\">%s</changeSet>", getVersion().getVersion(),
builder.toString());
}
return null;
}
private void deleteIndexIfExist(Class entityClass, String indexName, DatabaseMetaData databaseMetaData,
StringBuilder builder) throws SQLException
{
String databaseName = this.hibernateStore.getDatabaseFromWikiName();
PersistentClass persistentClass =
this.hibernateStore.getConfigurationMetadata().getEntityBinding(entityClass.getName());
String tableName = this.hibernateStore.getConfiguredTableName(persistentClass);
ResultSet resultSet;
if (this.hibernateStore.isCatalog()) {
resultSet = databaseMetaData.getIndexInfo(databaseName, null, tableName, false, false);
} else {
resultSet = databaseMetaData.getIndexInfo(null, databaseName, tableName, false, false);
}
while (resultSet.next()) {
String databaseIndexName = resultSet.getString("INDEX_NAME");
if (indexName.equalsIgnoreCase(databaseIndexName)) {
// Delete the index
builder.append("<dropIndex indexName=\"");
builder.append(databaseIndexName);
builder.append("\" tableName=\"");
builder.append(tableName);
builder.append("\"/>\n");
break;
}
}
}
private void maybeUpdateField(DatabaseMetaData databaseMetaData, String entity, String propertyName,
StringBuilder update) throws SQLException
{
Metadata configurationMetadata = this.hibernateStore.getConfigurationMetadata();
PersistentClass persistentClass = configurationMetadata.getEntityBinding(entity);
Property property = persistentClass.getProperty(propertyName);
String tableName = this.hibernateStore.getConfiguredTableName(persistentClass);
String columnName = this.hibernateStore.getConfiguredColumnName(persistentClass, propertyName);
try (ResultSet resultSet = getColumns(databaseMetaData, tableName, columnName)) {
if (resultSet.next()) {
String currentColumnType = resultSet.getString("TYPE_NAME");
Column column = (Column) property.getColumnIterator().next();
String expectedColumnType =
this.hibernateStore.getDialect().getTypeName(column.getSqlTypeCode(configurationMetadata));
if (!currentColumnType.equalsIgnoreCase(expectedColumnType)) {
int expectedLenght = column.getLength();
int currentColumnSize = resultSet.getInt("COLUMN_SIZE");
if (currentColumnSize > expectedLenght) {
column.setLength(currentColumnSize);
}
String dataType = getDataType(column, configurationMetadata);
// Not using <modifyDataType> here because Liquibase ignore attributes likes "NOT NULL"
update.append("<sql>");
update.append(this.hibernateStore.getDialect().getAlterTableString(tableName));
update.append(" MODIFY ");
update.append(column.getQuotedName(this.hibernateStore.getDialect()));
update.append(' ');
update.append(dataType);
update.append("</sql>");
this.logger.info("Updating the type of [{}.{}] to [{}]", tableName, columnName, dataType);
}
}
}
}
private String getDataType(Column column, Metadata configurationMetadata)
{
Dialect dialect = this.hibernateStore.getDialect();
StringBuilder builder = new StringBuilder(column.getSqlType(dialect, configurationMetadata));
if (column.isNullable()) {
builder.append(dialect.getNullColumnString());
} else {
builder.append(" not null");
}
return builder.toString();
}
private ResultSet getColumns(DatabaseMetaData databaseMetaData, String tableName, String columnName)
throws SQLException
{
if (this.hibernateStore.isCatalog()) {
return databaseMetaData.getColumns(this.hibernateStore.getDatabaseFromWikiName(), null, tableName,
columnName);
} else {
return databaseMetaData.getColumns(null, this.hibernateStore.getDatabaseFromWikiName(), tableName,
columnName);
}
}
}
| xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/migration/hibernate/R130200000XWIKI17200DataMigration.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.store.migration.hibernate;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.hibernate.boot.Metadata;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.internal.store.hibernate.HibernateStore;
import com.xpn.xwiki.stats.impl.RefererStats;
import com.xpn.xwiki.stats.impl.VisitStats;
import com.xpn.xwiki.store.DatabaseProduct;
import com.xpn.xwiki.store.migration.DataMigrationException;
import com.xpn.xwiki.store.migration.XWikiDBVersion;
/**
* This migration aims at applying the fix done on https://jira.xwiki.org/browse/XWIKI-15215 (change the type of some
* column so that they fit in the maximum allowed maximum row size for the used table type) instances older than
* 11.3RC1. Without this it's difficult to migrate to utf8mb3. It's also a requirement for
* {@link AbstractResizeMigration}.
* <p>
* The columns are:
* <ul>
* <li>LegacyEvent/activitystream_events
* <ul>
* <li>url</li>
* <li>title</li>
* <li>body</li>
* <li>param1</li>
* <li>param2</li>
* <li>param3</li>
* <li>param4</li>
* <li>param5</li>
* </ul>
* </li>
* <li>RefererStats/xwikistatsreferer
* <ul>
* <li>referer</li>
* </ul>
* </li>
* <li>VisitStats/xwikistatsvisit
* <ul>
* <li>userAgent</li>
* <li>cookie</li>
* </ul>
* </li>
* <li>XWikiPreferences/xwikipreferences
* <ul>
* <li>leftPanels</li>
* <li>rightPanels</li>
* <li>documentBundles</li>
* </ul>
* </li>
* </ul>
*
* @version $Id$
* @since 13.2RC1
* @since 12.10.6
*/
@Component
@Named("R130200000XWIKI17200")
@Singleton
public class R130200000XWIKI17200DataMigration extends AbstractHibernateDataMigration
{
@Inject
private Logger logger;
@Inject
private HibernateStore hibernateStore;
@Override
public String getDescription()
{
return "Make sure the database follow the currently expected type for some large string columns.";
}
@Override
public XWikiDBVersion getVersion()
{
return new XWikiDBVersion(130200000);
}
@Override
protected void hibernateMigrate() throws DataMigrationException, XWikiException
{
// Nothing to do here, everything's done as part of Liquibase pre update
}
@Override
public boolean shouldExecute(XWikiDBVersion startupVersion)
{
// Only really required for MySQL since https://jira.xwiki.org/browse/XWIKI-15215 was only affecting MySQL
return this.hibernateStore.getDatabaseProductName() == DatabaseProduct.MYSQL;
}
@Override
public String getPreHibernateLiquibaseChangeLog() throws DataMigrationException
{
StringBuilder builder = new StringBuilder();
Map<String, List<String>> map = new HashMap<>();
map.put("org.xwiki.eventstream.store.internal.LegacyEvent",
Arrays.asList("url", "title", "body", "param1", "param2", "param3", "param4", "param5"));
map.put(RefererStats.class.getName(), Arrays.asList("referer"));
map.put(VisitStats.class.getName(), Arrays.asList("userAgent", "cookie"));
map.put("XWiki.XWikiPreferences", Arrays.asList("leftPanels", "rightPanels", "documentBundles"));
try (SessionImplementor session = (SessionImplementor) this.hibernateStore.getSessionFactory().openSession()) {
JdbcConnectionAccess jdbcConnectionAccess = session.getJdbcConnectionAccess();
try (Connection connection = jdbcConnectionAccess.obtainConnection()) {
DatabaseMetaData databaseMetaData = connection.getMetaData();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
for (String property : entry.getValue()) {
maybeUpdateField(databaseMetaData, entry.getKey(), property, builder);
}
}
}
} catch (SQLException e) {
throw new DataMigrationException("Error while extracting metadata", e);
}
if (builder.length() > 0) {
return String.format("<changeSet author=\"xwiki\" id=\"R%s\">%s</changeSet>", getVersion().getVersion(),
builder.toString());
}
return null;
}
private void maybeUpdateField(DatabaseMetaData databaseMetaData, String entity, String propertyName,
StringBuilder update) throws SQLException
{
Metadata configurationMetadata = this.hibernateStore.getConfigurationMetadata();
PersistentClass persistentClass = configurationMetadata.getEntityBinding(entity);
Property property = persistentClass.getProperty(propertyName);
String tableName = this.hibernateStore.getConfiguredTableName(persistentClass);
String columnName = this.hibernateStore.getConfiguredColumnName(persistentClass, propertyName);
try (ResultSet resultSet = getColumns(databaseMetaData, tableName, columnName)) {
if (resultSet.next()) {
String currentColumnType = resultSet.getString("TYPE_NAME");
Column column = (Column) property.getColumnIterator().next();
String expectedColumnType =
this.hibernateStore.getDialect().getTypeName(column.getSqlTypeCode(configurationMetadata));
if (!currentColumnType.equalsIgnoreCase(expectedColumnType)) {
int expectedLenght = column.getLength();
int currentColumnSize = resultSet.getInt("COLUMN_SIZE");
if (currentColumnSize > expectedLenght) {
column.setLength(currentColumnSize);
}
String dataType = getDataType(column, configurationMetadata);
// Not using <modifyDataType> here because Liquibase ignore attributes likes "NOT NULL"
update.append("<sql>");
update.append(this.hibernateStore.getDialect().getAlterTableString(tableName));
update.append(" MODIFY ");
update.append(column.getQuotedName(this.hibernateStore.getDialect()));
update.append(' ');
update.append(dataType);
update.append("</sql>");
this.logger.info("Updating the type of [{}.{}] to [{}]", tableName, columnName, dataType);
}
}
}
}
private String getDataType(Column column, Metadata configurationMetadata)
{
Dialect dialect = this.hibernateStore.getDialect();
StringBuilder builder = new StringBuilder(column.getSqlType(dialect, configurationMetadata));
if (column.isNullable()) {
builder.append(dialect.getNullColumnString());
} else {
builder.append(" not null");
}
return builder.toString();
}
private ResultSet getColumns(DatabaseMetaData databaseMetaData, String tableName, String columnName)
throws SQLException
{
if (this.hibernateStore.isCatalog()) {
return databaseMetaData.getColumns(this.hibernateStore.getDatabaseFromWikiName(), null, tableName,
columnName);
} else {
return databaseMetaData.getColumns(null, this.hibernateStore.getDatabaseFromWikiName(), tableName,
columnName);
}
}
}
| XWIKI-19486: Potential error related to XWV_COOKIE key during a migration of extremely old XWiki instance
| xwiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/migration/hibernate/R130200000XWIKI17200DataMigration.java | XWIKI-19486: Potential error related to XWV_COOKIE key during a migration of extremely old XWiki instance | <ide><path>wiki-platform-core/xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/store/migration/hibernate/R130200000XWIKI17200DataMigration.java
<ide> try (Connection connection = jdbcConnectionAccess.obtainConnection()) {
<ide> DatabaseMetaData databaseMetaData = connection.getMetaData();
<ide>
<add> // Get rid of XWV_COOKIE key leftover if it exist
<add> deleteIndexIfExist(VisitStats.class, "xwv_cookie", databaseMetaData, builder);
<add>
<add> // Update properties
<ide> for (Map.Entry<String, List<String>> entry : map.entrySet()) {
<ide> for (String property : entry.getValue()) {
<ide> maybeUpdateField(databaseMetaData, entry.getKey(), property, builder);
<ide> return null;
<ide> }
<ide>
<add> private void deleteIndexIfExist(Class entityClass, String indexName, DatabaseMetaData databaseMetaData,
<add> StringBuilder builder) throws SQLException
<add> {
<add> String databaseName = this.hibernateStore.getDatabaseFromWikiName();
<add> PersistentClass persistentClass =
<add> this.hibernateStore.getConfigurationMetadata().getEntityBinding(entityClass.getName());
<add> String tableName = this.hibernateStore.getConfiguredTableName(persistentClass);
<add>
<add> ResultSet resultSet;
<add> if (this.hibernateStore.isCatalog()) {
<add> resultSet = databaseMetaData.getIndexInfo(databaseName, null, tableName, false, false);
<add> } else {
<add> resultSet = databaseMetaData.getIndexInfo(null, databaseName, tableName, false, false);
<add> }
<add>
<add> while (resultSet.next()) {
<add> String databaseIndexName = resultSet.getString("INDEX_NAME");
<add> if (indexName.equalsIgnoreCase(databaseIndexName)) {
<add> // Delete the index
<add> builder.append("<dropIndex indexName=\"");
<add> builder.append(databaseIndexName);
<add> builder.append("\" tableName=\"");
<add> builder.append(tableName);
<add> builder.append("\"/>\n");
<add>
<add> break;
<add> }
<add> }
<add> }
<add>
<ide> private void maybeUpdateField(DatabaseMetaData databaseMetaData, String entity, String propertyName,
<ide> StringBuilder update) throws SQLException
<ide> { |
|
Java | apache-2.0 | 68e101f58a31c6fb06680b618665c35ace0b8a44 | 0 | jmuehlner/incubator-guacamole-client,glyptodon/guacamole-client,glyptodon/guacamole-client,mike-jumper/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,necouchman/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,jmuehlner/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,glyptodon/guacamole-client,necouchman/incubator-guacamole-client,glyptodon/guacamole-client,jmuehlner/incubator-guacamole-client,mike-jumper/incubator-guacamole-client,necouchman/incubator-guacamole-client,necouchman/incubator-guacamole-client,glyptodon/guacamole-client | /*
* 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.
*/
package org.apache.guacamole;
import org.apache.guacamole.protocol.GuacamoleStatus;
/**
* A generic exception thrown when parts of the Guacamole API encounter
* errors.
*/
public class GuacamoleException extends Exception {
/**
* Creates a new GuacamoleException with the given message and cause.
*
* @param message A human readable description of the exception that
* occurred.
* @param cause The cause of this exception.
*/
public GuacamoleException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a new GuacamoleException with the given message.
*
* @param message A human readable description of the exception that
* occurred.
*/
public GuacamoleException(String message) {
super(message);
}
/**
* Creates a new GuacamoleException with the given cause.
*
* @param cause The cause of this exception.
*/
public GuacamoleException(Throwable cause) {
super(cause);
}
/**
* Returns the Guacamole status associated with this exception. This status
* can then be easily translated into an HTTP error code or Guacamole
* protocol error code.
*
* @return The corresponding Guacamole status.
*/
public GuacamoleStatus getStatus() {
return GuacamoleStatus.SERVER_ERROR;
}
/**
* Returns the numeric HTTP status code associated with this exception.
*
* @return
* The numeric HTTP status code associated with this exception.
*/
public Integer getHttpStatusCode() {
return getStatus().getHttpStatusCode();
}
}
| guacamole-common/src/main/java/org/apache/guacamole/GuacamoleException.java | /*
* 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.
*/
package org.apache.guacamole;
import org.apache.guacamole.protocol.GuacamoleStatus;
/**
* A generic exception thrown when parts of the Guacamole API encounter
* errors.
*/
public class GuacamoleException extends Exception {
/**
* Creates a new GuacamoleException with the given message and cause.
*
* @param message A human readable description of the exception that
* occurred.
* @param cause The cause of this exception.
*/
public GuacamoleException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a new GuacamoleException with the given message.
*
* @param message A human readable description of the exception that
* occurred.
*/
public GuacamoleException(String message) {
super(message);
}
/**
* Creates a new GuacamoleException with the given cause.
*
* @param cause The cause of this exception.
*/
public GuacamoleException(Throwable cause) {
super(cause);
}
/**
* Returns the Guacamole status associated with this exception. This status
* can then be easily translated into an HTTP error code or Guacamole
* protocol error code.
*
* @return The corresponding Guacamole status.
*/
public GuacamoleStatus getStatus() {
return GuacamoleStatus.SERVER_ERROR;
}
}
| GUACAMOLE-504: Add getHttpStatusCode() method to GuacamoleException class.
| guacamole-common/src/main/java/org/apache/guacamole/GuacamoleException.java | GUACAMOLE-504: Add getHttpStatusCode() method to GuacamoleException class. | <ide><path>uacamole-common/src/main/java/org/apache/guacamole/GuacamoleException.java
<ide> public GuacamoleStatus getStatus() {
<ide> return GuacamoleStatus.SERVER_ERROR;
<ide> }
<add>
<add> /**
<add> * Returns the numeric HTTP status code associated with this exception.
<add> *
<add> * @return
<add> * The numeric HTTP status code associated with this exception.
<add> */
<add> public Integer getHttpStatusCode() {
<add> return getStatus().getHttpStatusCode();
<add> }
<ide>
<ide> } |
|
Java | apache-2.0 | 72175e9902ae890682cf1bf5fa4b1bc854580585 | 0 | carewebframework/carewebframework-core,carewebframework/carewebframework-core,carewebframework/carewebframework-core,carewebframework/carewebframework-core | /**
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is also subject to the terms of the Health-Related Additional
* Disclaimer of Warranty and Limitation of Liability available at
* http://www.carewebframework.org/licensing/disclaimer.
*/
package org.carewebframework.ui.sharedforms;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.carewebframework.common.NumUtil;
import org.carewebframework.common.StrUtil;
import org.carewebframework.ui.command.CommandUtil;
import org.carewebframework.ui.zk.AbstractListitemRenderer;
import org.carewebframework.ui.zk.SplitterPane;
import org.carewebframework.ui.zk.SplitterView;
import org.carewebframework.ui.zk.ZKUtil;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.SelectEvent;
import org.zkoss.zk.ui.event.SortEvent;
import org.zkoss.zul.Auxheader;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listhead;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Listitem;
/**
* Controller for list view based forms.
*
* @param <DAO> Data access object type.
*/
public abstract class ListViewForm<DAO> extends CaptionedForm {
private static final long serialVersionUID = 1L;
private static final String SORT_TYPE_ATTR = "@sort_type";
private static final String COL_INDEX_ATTR = "@col_index";
private static final String SIZE_ATTR = "@size";
private SplitterView mainView;
private Listbox listbox;
private Listhead listhead;
private SplitterPane detailPane;
private SplitterPane listPane;
private Auxheader status;
private boolean allowPrint;
private String alternateColor = "#F0F0F0";
private int colCount;
private String dataName;
private boolean deferUpdate = true;
private boolean dataNeedsUpdate = true;
private int sortColumn;
private boolean sortAscending;
protected final ListModelList<DAO> model = new ListModelList<DAO>();
private final AbstractListitemRenderer<DAO, Object> renderer = new AbstractListitemRenderer<DAO, Object>() {
@Override
protected void renderItem(Listitem item, DAO object) {
item.addForward(Events.ON_CLICK, listbox, Events.ON_SELECT);
ListViewForm.this.renderItem(item, object);
}
};
private final EventListener<SortEvent> sortListener = new EventListener<SortEvent>() {
@Override
public void onEvent(SortEvent event) throws Exception {
sortAscending = event.isAscending();
sortColumn = (Integer) event.getTarget().getAttribute(COL_INDEX_ATTR);
}
};
/**
* Abort any pending async call.
*/
protected abstract void asyncAbort();
/**
* Async request to fetch data.
*/
protected abstract void requestData();
@Override
protected void init() {
super.init();
listbox.setItemRenderer(renderer);
listbox.setModel(model);
root = detailPane;
setSize(50);
CommandUtil.associateCommand("REFRESH", listbox);
getContainer().registerProperties(this, "allowPrint", "alternateColor", "deferUpdate", "showDetailPane", "layout",
"horizontal");
}
public void destroy() {
asyncAbort();
}
protected void setup(String title, String... headers) {
setup(title, 1, headers);
}
protected void setup(String title, int sortBy, String... headers) {
setCaption(title);
dataName = title;
String w = Integer.toString(100 / headers.length) + "%";
for (String header : headers) {
String[] pcs = StrUtil.split(header, StrUtil.U, 2);
Listheader lhdr = new Listheader(pcs[0]);
listhead.appendChild(lhdr);
lhdr.setAttribute(SORT_TYPE_ATTR, NumberUtils.toInt(pcs[1]));
lhdr.setAttribute(COL_INDEX_ATTR, colCount++);
lhdr.setWidth(w);
lhdr.addEventListener(Events.ON_SORT, sortListener);
}
sortColumn = Math.abs(sortBy) - 1;
sortAscending = sortBy > 0;
doSort();
}
public boolean getHorizontal() {
return mainView.isHorizontal();
}
public void setHorizontal(boolean value) {
mainView.setHorizontal(value);
}
public String getAlternateColor() {
return alternateColor;
}
public void setAlternateColor(String value) {
this.alternateColor = value;
}
public boolean getShowDetailPane() {
return detailPane.isVisible();
}
public void setShowDetailPane(boolean value) {
if (getShowDetailPane() != value) {
if (value) {
listPane.setRelativeSize(getSize());
} else {
setSize(listPane.getRelativeSize());
listPane.setRelativeSize(100);
}
detailPane.setVisible(value);
}
}
public boolean getAllowPrint() {
return allowPrint;
}
public void setAllowPrint(boolean value) {
this.allowPrint = value;
}
public boolean getDeferUpdate() {
return deferUpdate;
}
public void setDeferUpdate(boolean value) {
this.deferUpdate = value;
}
/**
* Getter method for Layout property. Format:
*
* <pre>
* List Pane Size:Sort Column:Sort Direction;Column 0 Index:Column 0 Width;...
* @return
*/
public String getLayout() {
StringBuilder sb = new StringBuilder();
sb.append(NumUtil.toString(getSize())).append(':').append(sortColumn).append(':').append(sortAscending);
for (Component comp : listhead.getChildren()) {
Listheader lhdr = (Listheader) comp;
sb.append(';').append(lhdr.getAttribute(COL_INDEX_ATTR)).append(':').append(lhdr.getWidth());
}
return sb.toString();
}
/**
* Setter method for Layout property. This property allows an application to control the
* position of the splitter bar and ordering of columns.
*
* @param layout
*/
public void setLayout(String layout) {
String[] pcs = StrUtil.split(layout, ";");
if (pcs.length > 0) {
String[] spl = StrUtil.split(pcs[0], ":", 3);
setSize(NumberUtils.toInt(spl[0]));
sortColumn = NumberUtils.toInt(spl[1]);
sortAscending = BooleanUtils.toBoolean(spl[2]);
}
for (int i = 1; i < pcs.length; i++) {
String[] col = StrUtil.split(pcs[i], ":", 2);
Listheader lhdr = getColumnByIndex(NumberUtils.toInt(col[0]));
if (lhdr != null) {
lhdr.setWidth(col[1]);
ZKUtil.moveChild(lhdr, i - 1);
}
}
doSort();
}
private double getSize() {
return (Double) listPane.getAttribute(SIZE_ATTR);
}
private void setSize(double value) {
listPane.setAttribute(SIZE_ATTR, value);
}
private void doSort() {
getColumnByIndex(sortColumn).sort(sortAscending);
}
/**
* Returns the column corresponding to the specified index.
*
* @param index
* @return
*/
private Listheader getColumnByIndex(int index) {
for (Component comp : listhead.getChildren()) {
if (((Integer) comp.getAttribute(COL_INDEX_ATTR)).intValue() == index) {
return (Listheader) comp;
}
}
return null;
}
/**
* Clears the list and status.
*/
protected void reset() {
model.clear();
listbox.setModel((ListModelList<?>) null);
status(null);
}
protected Listitem getSelectedItem() {
return listbox.getSelectedItem();
}
@SuppressWarnings("unchecked")
protected DAO getSelectedValue() {
Listitem item = getSelectedItem();
if (item != null) {
listbox.renderItem(item);
return (DAO) item.getValue();
}
return null;
}
/**
* Initiate asynchronous call to retrieve data from host.
*/
protected void loadData() {
dataNeedsUpdate = false;
asyncAbort();
reset();
status("Retrieving " + dataName + "...");
try {
requestData();
} catch (Throwable t) {
status("Error Retrieving " + dataName + "...^" + t.getMessage());
}
}
/**
* Converts a DAO object for rendering.
*
* @param dao DAO object to be rendered.
* @param columns Returns a list of objects to render, one per column.
*/
protected abstract void render(DAO dao, List<Object> columns);
/**
* Render a single item.
*
* @param item List item being rendered.
* @param dao DAO object
*/
protected void renderItem(Listitem item, DAO dao) {
List<Object> columns = new ArrayList<Object>();
render(dao, columns);
item.setVisible(!columns.isEmpty());
for (Object colData : columns) {
renderer.createCell(item, colData).setValue(colData);
}
}
/**
* Render the model data.
*/
protected void renderData() {
if (model.isEmpty()) {
status("No " + dataName + " Found");
} else {
status(null);
alphaSort();
listbox.setModel(model);
}
}
/**
* Implement to sort the data before displaying.
*/
protected void alphaSort() {
}
/**
* Forces an update of displayed list.
*/
@Override
public void refresh() {
dataNeedsUpdate = true;
if (!deferUpdate || isActive()) {
loadData();
} else {
reset();
}
}
protected void status(String message) {
if (message != null) {
status.setLabel(StrUtil.piece(message, StrUtil.U));
status.setTooltiptext(StrUtil.piece(message, StrUtil.U, 2, 999));
status.setVisible(true);
listhead.setVisible(false);
} else {
status.setVisible(false);
listhead.setVisible(true);
}
}
public void onClick$mnuRefresh() {
refresh();
}
public void onCommand$listbox() {
refresh();
}
public void onSelect$listbox(Event event) {
event = ZKUtil.getEventOrigin(event);
if (getShowDetailPane() == (event instanceof SelectEvent)) {
itemSelected(getSelectedItem());
}
}
/**
* Called when an item is selected. Override for specialized handling.
*
* @param li Selected list item.
*/
protected void itemSelected(Listitem li) {
}
@Override
public void onActivate() {
super.onActivate();
if (dataNeedsUpdate) {
loadData();
}
}
}
| org.carewebframework.ui-parent/org.carewebframework.ui.sharedforms/src/main/java/org/carewebframework/ui/sharedforms/ListViewForm.java | /**
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is also subject to the terms of the Health-Related Additional
* Disclaimer of Warranty and Limitation of Liability available at
* http://www.carewebframework.org/licensing/disclaimer.
*/
package org.carewebframework.ui.sharedforms;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.carewebframework.common.NumUtil;
import org.carewebframework.common.StrUtil;
import org.carewebframework.ui.command.CommandUtil;
import org.carewebframework.ui.zk.AbstractListitemRenderer;
import org.carewebframework.ui.zk.SplitterPane;
import org.carewebframework.ui.zk.SplitterView;
import org.carewebframework.ui.zk.ZKUtil;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.SelectEvent;
import org.zkoss.zk.ui.event.SortEvent;
import org.zkoss.zul.Auxheader;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listhead;
import org.zkoss.zul.Listheader;
import org.zkoss.zul.Listitem;
/**
* Controller for list view based forms.
*
* @param <DAO> Data access object type.
*/
public abstract class ListViewForm<DAO> extends CaptionedForm {
private static final long serialVersionUID = 1L;
private static final String SORT_TYPE_ATTR = "@sort_type";
private static final String COL_INDEX_ATTR = "@col_index";
private static final String SIZE_ATTR = "@size";
private SplitterView mainView;
private Listbox listbox;
private Listhead listhead;
private SplitterPane detailPane;
private SplitterPane listPane;
private Auxheader status;
private boolean allowPrint;
private String alternateColor = "#F0F0F0";
private int colCount;
private String dataName;
private boolean deferUpdate = true;
private boolean dataNeedsUpdate = true;
private int sortColumn;
private boolean sortAscending;
protected final ListModelList<DAO> model = new ListModelList<DAO>();
private final AbstractListitemRenderer<DAO, Object> renderer = new AbstractListitemRenderer<DAO, Object>() {
@Override
protected void renderItem(Listitem item, DAO object) {
item.addForward(Events.ON_CLICK, listbox, Events.ON_SELECT);
ListViewForm.this.renderItem(item, object);
}
};
private final EventListener<SortEvent> sortListener = new EventListener<SortEvent>() {
@Override
public void onEvent(SortEvent event) throws Exception {
sortAscending = event.isAscending();
sortColumn = (Integer) event.getTarget().getAttribute(COL_INDEX_ATTR);
}
};
/**
* Abort any pending async call.
*/
protected abstract void asyncAbort();
/**
* Async request to fetch data.
*/
protected abstract void requestData();
@Override
protected void init() {
super.init();
listbox.setItemRenderer(renderer);
listbox.setModel(model);
root = detailPane;
setSize(50);
CommandUtil.associateCommand("REFRESH", listbox);
getContainer().registerProperties(this, "allowPrint", "alternateColor", "deferUpdate", "showDetailPane", "layout",
"horizontal");
}
public void destroy() {
asyncAbort();
}
protected void setup(String title, String... headers) {
setup(title, 1, headers);
}
protected void setup(String title, int sortBy, String... headers) {
setCaption(title);
dataName = title;
String w = Integer.toString(100 / headers.length) + "%";
for (String header : headers) {
String[] pcs = StrUtil.split(header, StrUtil.U, 2);
Listheader lhdr = new Listheader(pcs[0]);
listhead.appendChild(lhdr);
lhdr.setAttribute(SORT_TYPE_ATTR, NumberUtils.toInt(pcs[1]));
lhdr.setAttribute(COL_INDEX_ATTR, colCount++);
lhdr.setWidth(w);
lhdr.addEventListener(Events.ON_SORT, sortListener);
}
sortColumn = Math.abs(sortBy) - 1;
sortAscending = sortBy > 0;
doSort();
}
public boolean getHorizontal() {
return mainView.isHorizontal();
}
public void setHorizontal(boolean value) {
mainView.setHorizontal(value);
}
public String getAlternateColor() {
return alternateColor;
}
public void setAlternateColor(String value) {
this.alternateColor = value;
}
public boolean getShowDetailPane() {
return detailPane.isVisible();
}
public void setShowDetailPane(boolean value) {
if (getShowDetailPane() != value) {
if (value) {
listPane.setRelativeSize(getSize());
} else {
setSize(listPane.getRelativeSize());
listPane.setRelativeSize(100);
}
detailPane.setVisible(value);
}
}
public boolean getAllowPrint() {
return allowPrint;
}
public void setAllowPrint(boolean value) {
this.allowPrint = value;
}
public boolean getDeferUpdate() {
return deferUpdate;
}
public void setDeferUpdate(boolean value) {
this.deferUpdate = value;
}
/**
* Getter method for Layout property. Format:
*
* <pre>
* List Pane Size:Sort Column:Sort Direction;Column 0 Index:Column 0 Width;...
* @return
*/
public String getLayout() {
StringBuilder sb = new StringBuilder();
sb.append(NumUtil.toString(getSize())).append(':').append(sortColumn).append(':').append(sortAscending);
for (Component comp : listhead.getChildren()) {
Listheader lhdr = (Listheader) comp;
sb.append(';').append(lhdr.getAttribute(COL_INDEX_ATTR)).append(':').append(lhdr.getWidth());
}
return sb.toString();
}
/**
* Setter method for Layout property. This property allows an application to control the
* position of the splitter bar and ordering of columns.
*
* @param layout
*/
public void setLayout(String layout) {
String[] pcs = StrUtil.split(layout, ";");
if (pcs.length > 0) {
String[] spl = StrUtil.split(pcs[0], ":", 3);
setSize(NumberUtils.toInt(spl[0]));
sortColumn = NumberUtils.toInt(spl[1]);
sortAscending = BooleanUtils.toBoolean(spl[2]);
}
for (int i = 1; i < pcs.length; i++) {
String[] col = StrUtil.split(pcs[i], ":", 2);
Listheader lhdr = getColumnByIndex(NumberUtils.toInt(col[0]));
if (lhdr != null) {
lhdr.setWidth(col[1]);
ZKUtil.moveChild(lhdr, i - 1);
}
}
doSort();
}
private double getSize() {
return (Double) listPane.getAttribute(SIZE_ATTR);
}
private void setSize(double value) {
listPane.setAttribute(SIZE_ATTR, value);
}
private void doSort() {
getColumnByIndex(sortColumn).sort(sortAscending);
}
/**
* Returns the column corresponding to the specified index.
*
* @param index
* @return
*/
private Listheader getColumnByIndex(int index) {
for (Component comp : listhead.getChildren()) {
if (((Integer) comp.getAttribute(COL_INDEX_ATTR)).intValue() == index) {
return (Listheader) comp;
}
}
return null;
}
/**
* Clears the list and status.
*/
protected void reset() {
model.clear();
listbox.setModel((ListModelList<?>) null);
status(null);
}
protected Listitem getSelectedItem() {
return listbox.getSelectedItem();
}
/**
* Initiate asynchronous call to retrieve data from host.
*/
protected void loadData() {
dataNeedsUpdate = false;
asyncAbort();
reset();
status("Retrieving " + dataName + "...");
try {
requestData();
} catch (Throwable t) {
status("Error Retrieving " + dataName + "...^" + t.getMessage());
}
}
/**
* Converts a DAO object for rendering.
*
* @param dao DAO object to be rendered.
* @param columns Returns a list of objects to render, one per column.
*/
protected abstract void render(DAO dao, List<Object> columns);
/**
* Render a single item.
*
* @param item List item being rendered.
* @param dao DAO object
*/
protected void renderItem(Listitem item, DAO dao) {
List<Object> columns = new ArrayList<Object>();
render(dao, columns);
item.setVisible(!columns.isEmpty());
for (Object colData : columns) {
renderer.createCell(item, colData).setValue(colData);
}
}
/**
* Render the model data.
*/
protected void renderData() {
if (model.isEmpty()) {
status("No " + dataName + " Found");
} else {
status(null);
alphaSort();
listbox.setModel(model);
}
}
/**
* Implement to sort the data before displaying.
*/
protected void alphaSort() {
}
/**
* Forces an update of displayed list.
*/
@Override
public void refresh() {
dataNeedsUpdate = true;
if (!deferUpdate || isActive()) {
loadData();
} else {
reset();
}
}
protected void status(String message) {
if (message != null) {
status.setLabel(StrUtil.piece(message, StrUtil.U));
status.setTooltiptext(StrUtil.piece(message, StrUtil.U, 2, 999));
status.setVisible(true);
listhead.setVisible(false);
} else {
status.setVisible(false);
listhead.setVisible(true);
}
}
public void onClick$mnuRefresh() {
refresh();
}
public void onCommand$listbox() {
refresh();
}
public void onSelect$listbox(Event event) {
event = ZKUtil.getEventOrigin(event);
if (getShowDetailPane() == (event instanceof SelectEvent)) {
itemSelected(getSelectedItem());
}
}
/**
* Called when an item is selected. Override for specialized handling.
*
* @param li Selected list item.
*/
protected void itemSelected(Listitem li) {
}
@Override
public void onActivate() {
super.onActivate();
if (dataNeedsUpdate) {
loadData();
}
}
}
| Add getSelectedValue method. | org.carewebframework.ui-parent/org.carewebframework.ui.sharedforms/src/main/java/org/carewebframework/ui/sharedforms/ListViewForm.java | Add getSelectedValue method. | <ide><path>rg.carewebframework.ui-parent/org.carewebframework.ui.sharedforms/src/main/java/org/carewebframework/ui/sharedforms/ListViewForm.java
<ide> return listbox.getSelectedItem();
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<add> protected DAO getSelectedValue() {
<add> Listitem item = getSelectedItem();
<add>
<add> if (item != null) {
<add> listbox.renderItem(item);
<add> return (DAO) item.getValue();
<add> }
<add>
<add> return null;
<add> }
<add>
<ide> /**
<ide> * Initiate asynchronous call to retrieve data from host.
<ide> */ |
|
JavaScript | mit | c83a0ebe4cf5653d958b4d35e485407e72d75dfc | 0 | ForbesLindesay/ascii-math | /*
Generated with the code:
request('http://www.escapecodes.info', function (err, res, body) {
if (err) throw err;
body = body.toString();
var pattern = /<span class=\"tip\">\&([^;]+);<br \/>\&#([^;]+);/g;
var match;
var lookup = {};
while (match = pattern.exec(body)) {
lookup[match[2]] = match[1];
}
fs.writeFileSync(path.join(__dirname, 'escape-lookup.json'), JSON.stringify(lookup, null, 2));
})
*/
var lookup = {
34: 'quot',
38: 'amp',
60: 'lt',
62: 'gt',
161: 'iexcl',
162: 'cent',
163: 'pound',
164: 'curren',
165: 'yen',
166: 'brvbar',
167: 'sect',
168: 'uml',
169: 'copy',
170: 'ordf',
171: 'laquo',
172: 'not',
173: 'shy',
174: 'reg',
175: 'macr',
176: 'deg',
177: 'plusmn',
178: 'sup2',
179: 'sup3',
180: 'acute',
181: 'micro',
182: 'para',
183: 'middot',
184: 'cedil',
185: 'sup1',
186: 'ordm',
187: 'raquo',
188: 'frac14',
189: 'frac12',
190: 'frac34',
191: 'iquest',
192: 'Agrave',
193: 'Aacute',
194: 'Acirc',
195: 'Atilde',
196: 'Auml',
197: 'Aring',
198: 'AElig',
199: 'Ccedil',
200: 'Egrave',
201: 'Eacute',
202: 'Ecirc',
203: 'Euml',
204: 'Igrave',
205: 'Iacute',
206: 'Icirc',
207: 'Iuml',
208: 'ETH',
209: 'Ntilde',
210: 'Ograve',
211: 'Oacute',
212: 'Ocirc',
213: 'Otilde',
214: 'Ouml',
215: 'times',
216: 'Oslash',
217: 'Ugrave',
218: 'Uacute',
219: 'Ucirc',
220: 'Uuml',
221: 'Yacute',
222: 'THORN',
223: 'szlig',
224: 'agrave',
225: 'aacute',
226: 'acirc',
227: 'atilde',
228: 'auml',
229: 'aring',
230: 'aelig',
231: 'ccedil',
232: 'egrave',
233: 'eacute',
234: 'ecirc',
235: 'euml',
236: 'igrave',
237: 'iacute',
238: 'icirc',
239: 'iuml',
240: 'eth',
241: 'ntilde',
242: 'ograve',
243: 'oacute',
244: 'ocirc',
245: 'otilde',
246: 'ouml',
247: 'divide',
248: 'oslash',
249: 'ugrave',
250: 'uacute',
251: 'ucirc',
252: 'uuml',
253: 'yacute',
255: 'yuml',
338: 'OElig',
339: 'oelig',
352: 'Scaron',
353: 'scaron',
376: 'Yuml',
402: 'fnof',
913: 'Alpha',
914: 'Beta',
915: 'Gamma',
916: 'Delta',
917: 'Epsilon',
918: 'Zeta',
919: 'Eta',
920: 'Theta',
921: 'Iota',
922: 'Kappa',
923: 'Lambda',
925: 'Nu',
926: 'Xi',
927: 'Omicron',
928: 'Pi',
929: 'Rho',
931: 'Sigma',
932: 'Tau',
933: 'Upsilon',
934: 'Phi',
935: 'Chi',
936: 'Psi',
937: 'Omega',
945: 'alpha',
946: 'beta',
947: 'gamma',
948: 'delta',
949: 'epsilon',
950: 'zeta',
951: 'eta',
952: 'theta',
953: 'iota',
954: 'kappa',
955: 'lambda',
956: 'mu',
957: 'nu',
958: 'xi',
959: 'omicron',
960: 'pi',
961: 'rho',
962: 'sigmaf',
963: 'sigma',
964: 'tau',
965: 'upsilon',
966: 'phi',
967: 'chi',
968: 'psi',
969: 'omega',
977: 'thetasym',
978: 'upsih',
982: 'piv',
8211: 'ndash',
8212: 'mdash',
8216: 'lsquo',
8217: 'rsquo',
8218: 'sbquo',
8220: 'ldquo',
8221: 'rdquo',
8222: 'bdquo',
8224: 'dagger',
8225: 'Dagger',
8240: 'permil',
8249: 'lsaquo',
8250: 'rsaquo',
8364: 'euro',
8465: 'image',
8472: 'weierp',
8476: 'real',
8482: 'trade',
8501: 'alefsym',
8592: 'larr',
8593: 'uarr',
8594: 'rarr',
8595: 'darr',
8596: 'harr',
8629: 'crarr',
8656: 'lArr',
8657: 'uArr',
8658: 'rArr',
8659: 'dArr',
8660: 'hArr',
8704: 'forall',
8706: 'part',
8707: 'exist',
8709: 'empty',
8711: 'nabla',
8712: 'isin',
8713: 'notin',
8715: 'ni',
8719: 'prod',
8721: 'sum',
8722: 'minus',
8727: 'lowast',
8730: 'radic',
8733: 'prop',
8734: 'infin',
8736: 'ang',
8743: 'and',
8744: 'or',
8745: 'cap',
8746: 'cup',
8747: 'int',
8756: 'there4',
8764: 'sim',
8773: 'cong',
8776: 'asymp',
8800: 'ne',
8801: 'equiv',
8804: 'le',
8805: 'ge',
8834: 'sub',
8835: 'sup',
8836: 'nsub',
8838: 'sube',
8839: 'supe',
8853: 'oplus',
8855: 'otimes',
8869: 'perp',
8901: 'sdot',
8968: 'lceil',
8969: 'rceil',
8970: 'lfloor',
8971: 'rfloor',
9001: 'lang',
9002: 'rang',
9674: 'loz',
9824: 'spades',
9827: 'clubs',
9829: 'hearts',
9830: 'diams'
};
module.exports = HTMLEncode;
function HTMLEncode(str){
var i = str.length,
aRet = [];
while (i--) {
var iC = str.charCodeAt(i);
if (lookup[iC]) {
aRet[i] = '&' + lookup[iC] + ';';
} else if (iC > 127) { //See: http://en.wikipedia.org/wiki/List_of_Unicode_characters for list of unicode characters
aRet[i] = '&#' + iC + ';';
} else {
aRet[i] = str[i];
}
}
return aRet.join('');
} | lib/escape.js | /*
Generated with the code:
request('http://www.escapecodes.info', function (err, res, body) {
if (err) throw err;
body = body.toString();
var pattern = /<span class=\"tip\">\&([^;]+);<br \/>\&#([^;]+);/g;
var match;
var lookup = {};
while (match = pattern.exec(body)) {
lookup[match[2]] = match[1];
}
fs.writeFileSync(path.join(__dirname, 'escape-lookup.json'), JSON.stringify(lookup, null, 2));
})
*/
var lookup = {
34: 'quot',
38: 'amp',
60: 'lt',
62: 'gt',
161: 'iexcl',
162: 'cent',
163: 'pound',
164: 'curren',
165: 'yen',
166: 'brvbar',
167: 'sect',
168: 'uml',
169: 'copy',
170: 'ordf',
171: 'laquo',
172: 'not',
173: 'shy',
174: 'reg',
175: 'macr',
176: 'deg',
177: 'plusmn',
178: 'sup2',
179: 'sup3',
180: 'acute',
181: 'micro',
182: 'para',
183: 'middot',
184: 'cedil',
185: 'sup1',
186: 'ordm',
187: 'raquo',
188: 'frac14',
189: 'frac12',
190: 'frac34',
191: 'iquest',
192: 'Agrave',
193: 'Aacute',
194: 'Acirc',
195: 'Atilde',
196: 'Auml',
197: 'Aring',
198: 'AElig',
199: 'Ccedil',
200: 'Egrave',
201: 'Eacute',
202: 'Ecirc',
203: 'Euml',
204: 'Igrave',
205: 'Iacute',
206: 'Icirc',
207: 'Iuml',
208: 'ETH',
209: 'Ntilde',
210: 'Ograve',
211: 'Oacute',
212: 'Ocirc',
213: 'Otilde',
214: 'Ouml',
215: 'times',
216: 'Oslash',
217: 'Ugrave',
218: 'Uacute',
219: 'Ucirc',
220: 'Uuml',
221: 'Yacute',
222: 'THORN',
223: 'szlig',
224: 'agrave',
225: 'aacute',
226: 'acirc',
227: 'atilde',
228: 'auml',
229: 'aring',
230: 'aelig',
231: 'ccedil',
232: 'egrave',
233: 'eacute',
234: 'ecirc',
235: 'euml',
236: 'igrave',
237: 'iacute',
238: 'icirc',
239: 'iuml',
240: 'eth',
241: 'ntilde',
242: 'ograve',
243: 'oacute',
244: 'ocirc',
245: 'otilde',
246: 'ouml',
247: 'divide',
248: 'oslash',
249: 'ugrave',
250: 'uacute',
251: 'ucirc',
252: 'uuml',
253: 'yacute',
255: 'yuml',
338: 'OElig',
339: 'oelig',
352: 'Scaron',
353: 'scaron',
376: 'Yuml',
402: 'fnof',
913: 'Alpha',
914: 'Beta',
915: 'Gamma',
916: 'Delta',
917: 'Epsilon',
918: 'Zeta',
919: 'Eta',
920: 'Theta',
921: 'Iota',
922: 'Kappa',
923: 'Lambda',
925: 'Nu',
926: 'Xi',
927: 'Omicron',
928: 'Pi',
929: 'Rho',
931: 'Sigma',
932: 'Tau',
933: 'Upsilon',
934: 'Phi',
935: 'Chi',
936: 'Psi',
937: 'Omega',
945: 'alpha',
946: 'beta',
947: 'gamma',
948: 'delta',
949: 'epsilon',
950: 'zeta',
951: 'eta',
952: 'theta',
953: 'iota',
954: 'kappa',
955: 'lambda',
956: 'mu',
957: 'nu',
958: 'xi',
959: 'omicron',
960: 'pi',
961: 'rho',
962: 'sigmaf',
963: 'sigma',
964: 'tau',
965: 'upsilon',
966: 'phi',
967: 'chi',
968: 'psi',
969: 'omega',
977: 'thetasym',
978: 'upsih',
982: 'piv',
8211: 'ndash',
8212: 'mdash',
8216: 'lsquo',
8217: 'rsquo',
8218: 'sbquo',
8220: 'ldquo',
8221: 'rdquo',
8222: 'bdquo',
8224: 'dagger',
8225: 'Dagger',
8240: 'permil',
8249: 'lsaquo',
8250: 'rsaquo',
8364: 'euro',
8465: 'image',
8472: 'weierp',
8476: 'real',
8482: 'trade',
8501: 'alefsym',
8592: 'larr',
8593: 'uarr',
8594: 'rarr',
8595: 'darr',
8596: 'harr',
8629: 'crarr',
8656: 'lArr',
8657: 'uArr',
8658: 'rArr',
8659: 'dArr',
8660: 'hArr',
8704: 'forall',
8706: 'part ',
8707: 'exist',
8709: 'empty',
8711: 'nabla',
8712: 'isin',
8713: 'notin',
8715: 'ni',
8719: 'prod',
8721: 'sum',
8722: 'minus',
8727: 'lowast',
8730: 'radic',
8733: 'prop',
8734: 'infin',
8736: 'ang',
8743: 'and',
8744: 'or ',
8745: 'cap',
8746: 'cup',
8747: 'int',
8756: 'there4',
8764: 'sim',
8773: 'cong',
8776: 'asymp',
8800: 'ne',
8801: 'equiv',
8804: 'le',
8805: 'ge',
8834: 'sub',
8835: 'sup',
8836: 'nsub',
8838: 'sube',
8839: 'supe',
8853: 'oplus',
8855: 'otimes',
8869: 'perp',
8901: 'sdot',
8968: 'lceil',
8969: 'rceil',
8970: 'lfloor',
8971: 'rfloor',
9001: 'lang',
9002: 'rang',
9674: 'loz',
9824: 'spades',
9827: 'clubs',
9829: 'hearts',
9830: 'diams'
};
module.exports = HTMLEncode;
function HTMLEncode(str){
var i = str.length,
aRet = [];
while (i--) {
var iC = str.charCodeAt(i);
if (lookup[iC]) {
aRet[i] = '&' + lookup[iC] + ';';
} else if (iC > 127) { //See: http://en.wikipedia.org/wiki/List_of_Unicode_characters for list of unicode characters
aRet[i] = '&#' + iC + ';';
} else {
aRet[i] = str[i];
}
}
return aRet.join('');
} | fix escaping of `or` and `part`
| lib/escape.js | fix escaping of `or` and `part` | <ide><path>ib/escape.js
<ide> 8659: 'dArr',
<ide> 8660: 'hArr',
<ide> 8704: 'forall',
<del> 8706: 'part ',
<add> 8706: 'part',
<ide> 8707: 'exist',
<ide> 8709: 'empty',
<ide> 8711: 'nabla',
<ide> 8734: 'infin',
<ide> 8736: 'ang',
<ide> 8743: 'and',
<del> 8744: 'or ',
<add> 8744: 'or',
<ide> 8745: 'cap',
<ide> 8746: 'cup',
<ide> 8747: 'int', |
|
Java | apache-2.0 | 46c5480dd3e9cbb9c676d7e14017cd1c5fed9d8a | 0 | OpenHFT/Chronicle-Core | /*
* Copyright 2016 higherfrequencytrading.com
*
* 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.
*/
package net.openhft.chronicle.core;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.function.Consumer;
/**
* Created by peter on 13/12/16.
*/
public enum Mocker {
;
@NotNull
public static <T> T logging(@NotNull Class<T> tClass, String description, @NotNull PrintStream out) {
return intercepting(tClass, description, out::println);
}
@NotNull
public static <T> T logging(@NotNull Class<T> tClass, String description, @NotNull PrintWriter out) {
return intercepting(tClass, description, out::println);
}
@NotNull
public static <T> T logging(@NotNull Class<T> tClass, String description, @NotNull StringWriter out) {
return logging(tClass, description, new PrintWriter(out));
}
@NotNull
public static <T> T queuing(@NotNull Class<T> tClass, String description, @NotNull BlockingQueue<String> queue) {
return intercepting(tClass, description, queue::add);
}
@NotNull
public static <T> T intercepting(@NotNull Class<T> tClass, String description, @NotNull Consumer<String> consumer) {
return intercepting(tClass, description, consumer, null);
}
@NotNull
public static <T> T intercepting(@NotNull Class<T> tClass, String description, @NotNull Consumer<String> consumer, T t) {
//noinspection unchecked
return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new InvocationHandler() {
@Nullable
@Override
public Object invoke(Object proxy, @NotNull Method method, @Nullable Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class)
return method.invoke(this, args);
consumer.accept(description + method.getName() + (args == null ? "()" : Arrays.toString(args)));
if (t != null)
method.invoke(t, args);
return null;
}
});
}
@NotNull
public static <T> T ignored(@NotNull Class<T> tClass) {
//noinspection unchecked
return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new InvocationHandler() {
@Nullable
@Override
public Object invoke(Object proxy, @NotNull Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class)
return method.invoke(this, args);
return null;
}
});
}
}
| src/main/java/net/openhft/chronicle/core/Mocker.java | /*
* Copyright 2016 higherfrequencytrading.com
*
* 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.
*/
package net.openhft.chronicle.core;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.function.Consumer;
/**
* Created by peter on 13/12/16.
*/
public enum Mocker {
;
@NotNull
public static <T> T logging(@NotNull Class<T> tClass, String description, @NotNull PrintStream out) {
return intercepting(tClass, description, out::println);
}
@NotNull
public static <T> T logging(@NotNull Class<T> tClass, String description, @NotNull PrintWriter out) {
return intercepting(tClass, description, out::println);
}
@NotNull
public static <T> T logging(@NotNull Class<T> tClass, String description, @NotNull StringWriter out) {
return logging(tClass, description, new PrintWriter(out));
}
@NotNull
public static <T> T queuing(@NotNull Class<T> tClass, String description, @NotNull BlockingQueue<String> queue) {
return intercepting(tClass, description, queue::add);
}
@NotNull
public static <T> T intercepting(@NotNull Class<T> tClass, String description, @NotNull Consumer<String> consumer) {
//noinspection unchecked
return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new InvocationHandler() {
@Nullable
@Override
public Object invoke(Object proxy, @NotNull Method method, @Nullable Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class)
return method.invoke(this, args);
consumer.accept(description + method.getName() + (args == null ? "()" : Arrays.toString(args)));
return null;
}
});
}
@NotNull
public static <T> T ignored(@NotNull Class<T> tClass) {
//noinspection unchecked
return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new InvocationHandler() {
@Nullable
@Override
public Object invoke(Object proxy, @NotNull Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class)
return method.invoke(this, args);
return null;
}
});
}
}
| Add an option to log all IO
| src/main/java/net/openhft/chronicle/core/Mocker.java | Add an option to log all IO | <ide><path>rc/main/java/net/openhft/chronicle/core/Mocker.java
<ide>
<ide> @NotNull
<ide> public static <T> T intercepting(@NotNull Class<T> tClass, String description, @NotNull Consumer<String> consumer) {
<add> return intercepting(tClass, description, consumer, null);
<add> }
<add>
<add> @NotNull
<add> public static <T> T intercepting(@NotNull Class<T> tClass, String description, @NotNull Consumer<String> consumer, T t) {
<ide> //noinspection unchecked
<ide> return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new InvocationHandler() {
<ide> @Nullable
<ide> if (method.getDeclaringClass() == Object.class)
<ide> return method.invoke(this, args);
<ide> consumer.accept(description + method.getName() + (args == null ? "()" : Arrays.toString(args)));
<add> if (t != null)
<add> method.invoke(t, args);
<ide> return null;
<ide> }
<ide> }); |
|
Java | apache-2.0 | 5ff8477dcf71f5a0c9c900831a2a5778f63bbd23 | 0 | Xlythe/CameraView | package com.xlythe.fragment.camera;
import android.Manifest;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.format.DateFormat;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.LinearInterpolator;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.xlythe.view.camera.CameraView;
import com.xlythe.view.camera.R;
import java.io.File;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;
public abstract class CameraFragment extends Fragment implements CameraView.OnImageCapturedListener, CameraView.OnVideoCapturedListener {
private static final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final int REQUEST_CODE_REQUIRED_PERMISSIONS = 3;
private static final String DESTINATION = "yyyy-MM-dd hh:mm:ss";
private static final String PHOTO_EXT = ".jpg";
private static final String VIDEO_EXT = ".mp4";
private View mCameraHolder;
private View mPermissionPrompt;
private CameraView mCamera;
private View mPermissionRequest;
private View mCapture;
private View mConfirm;
@Nullable
private TextView mDuration;
@Nullable
private ProgressBar mProgress;
@Nullable
private CompoundButton mToggle;
@Nullable
private View mCancel;
private ProgressBarAnimator mAnimator = new ProgressBarAnimator();
private DisplayManager.DisplayListener mDisplayListener;
@SuppressWarnings({"MissingPermission"})
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_REQUIRED_PERMISSIONS) {
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
showCamera();
} else {
showPermissionPrompt();
}
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (Build.VERSION.SDK_INT > 17) {
mDisplayListener = new DisplayManager.DisplayListener() {
@Override
public void onDisplayAdded(int displayId) {}
@Override
public void onDisplayRemoved(int displayId) {}
@SuppressWarnings({"MissingPermission"})
@Override
public void onDisplayChanged(int displayId) {
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
if (mCamera.isOpen()) {
mCamera.close();
mCamera.open();
}
}
}
};
DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
displayManager.registerDisplayListener(mDisplayListener, new Handler());
}
}
@Override
public void onDetach() {
if (Build.VERSION.SDK_INT > 17) {
DisplayManager displayManager = (DisplayManager) getContext().getSystemService(Context.DISPLAY_SERVICE);
displayManager.unregisterDisplayListener(mDisplayListener);
}
super.onDetach();
}
@SuppressWarnings({"MissingPermission"})
@Override
public void onStart() {
super.onStart();
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
showCamera();
} else {
showPermissionPrompt();
}
}
@Override
public void onStop() {
mCamera.close();
super.onStop();
}
public void setEnabled(boolean enabled) {
mCapture.setEnabled(enabled);
}
public boolean isEnabled() {
return mCapture.isEnabled();
}
public void setQuality(CameraView.Quality quality) {
mCamera.setQuality(quality);
}
public CameraView.Quality getQuality() {
return mCamera.getQuality();
}
public void setMaxVideoDuration(long duration) {
mCamera.setMaxVideoDuration(duration);
}
public long getMaxVideoDuration() {
return mCamera.getMaxVideoDuration();
}
public void setMaxVideoSize(long size) {
mCamera.setMaxVideoSize(size);
}
public long getMaxVideoSize() {
return mCamera.getMaxVideoSize();
}
protected void onTakePicture() {}
protected void onRecordStart() {}
protected void onRecordStop() {}
@RequiresPermission(allOf = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE
})
private void showCamera() {
mCameraHolder.setVisibility(View.VISIBLE);
mPermissionPrompt.setVisibility(View.GONE);
mCamera.open();
}
private void showPermissionPrompt() {
mCameraHolder.setVisibility(View.GONE);
mPermissionPrompt.setVisibility(View.VISIBLE);
}
private static String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
Formatter formatter = new Formatter(Locale.getDefault());
if (hours > 0) {
return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return formatter.format("%02d:%02d", minutes, seconds).toString();
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mCameraHolder = view.findViewById(R.id.layout_camera);
mPermissionPrompt = view.findViewById(R.id.layout_permissions);
mPermissionRequest = view.findViewById(R.id.request_permissions);
mCamera = (CameraView) view.findViewById(R.id.camera);
mToggle = (CompoundButton) view.findViewById(R.id.toggle);
mCapture = mCameraHolder.findViewById(R.id.capture);
mProgress = (ProgressBar) view.findViewById(R.id.progress);
mDuration = (TextView) view.findViewById(R.id.duration);
mCancel = view.findViewById(R.id.cancel);
mConfirm = view.findViewById(R.id.confirm);
if (mCameraHolder == null) {
throw new IllegalStateException("No View found with id R.id.layout_camera");
}
if (mCamera == null) {
throw new IllegalStateException("No CameraView found with id R.id.camera");
}
if (mCapture == null) {
throw new IllegalStateException("No CameraView found with id R.id.capture");
}
if (mPermissionPrompt == null) {
throw new IllegalStateException("No View found with id R.id.layout_permissions");
}
if (mPermissionRequest == null) {
throw new IllegalStateException("No View found with id R.id.request_permissions");
}
mCamera.setOnImageCapturedListener(this);
mCamera.setOnVideoCapturedListener(this);
mCapture.setOnTouchListener(new OnTouchListener(getContext()));
if (mConfirm != null) {
mConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCamera.confirmPicture();
}
});
mCamera.setImageConfirmationEnabled(true);
mCamera.setVideoConfirmationEnabled(true);
} else {
mCamera.setImageConfirmationEnabled(false);
mCamera.setVideoConfirmationEnabled(false);
}
mPermissionRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(REQUIRED_PERMISSIONS, REQUEST_CODE_REQUIRED_PERMISSIONS);
}
});
if (mToggle != null) {
mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE);
mToggle.setChecked(mCamera.isUsingFrontFacingCamera());
mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCamera.toggleCamera();
}
});
}
if (mProgress != null) {
mProgress.setMax(10000);
}
if (mDuration != null) {
mDuration.setVisibility(View.GONE);
}
if (mCancel != null) {
mCancel.setVisibility(View.GONE);
}
mConfirm.setVisibility(View.GONE);
}
@Override
public void onFailure() {}
@Override
public void onImageConfirmation() {
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (view == mCancel) {
mCamera.rejectPicture();
} else {
mCamera.confirmPicture();
}
// After confirming/rejecting, show our buttons again
mConfirm.setVisibility(View.GONE);
mCapture.setVisibility(View.VISIBLE);
if (mCancel!= null) {
mCancel.setVisibility(View.GONE);
}
if (mToggle != null) {
mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE);
}
}
};
if (mCancel != null) {
mCancel.setVisibility(View.VISIBLE);
mCancel.setOnClickListener(listener);
}
if (mToggle != null) {
mToggle.setVisibility(View.GONE);
}
mCapture.setVisibility(View.GONE);
mConfirm.setVisibility(View.VISIBLE);
mConfirm.setOnClickListener(listener);
}
@Override
public void onVideoConfirmation() {
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (view == mCancel) {
mCamera.rejectVideo();
} else {
mCamera.confirmVideo();
}
// After confirming/rejecting, show our buttons again
mConfirm.setVisibility(View.GONE);
mCapture.setVisibility(View.VISIBLE);
if (mCancel!= null) {
mCancel.setVisibility(View.GONE);
}
if (mToggle != null) {
mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE);
}
}
};
if (mCancel != null) {
mCancel.setVisibility(View.VISIBLE);
mCancel.setOnClickListener(listener);
}
if (mToggle != null) {
mToggle.setVisibility(View.GONE);
}
mCapture.setVisibility(View.GONE);
mConfirm.setVisibility(View.VISIBLE);
mConfirm.setOnClickListener(listener);
}
/**
* Returns true if all given permissions are available
*/
public static boolean hasPermissions(Context context, String... permissions) {
boolean ok = true;
for (String permission : permissions) {
ok = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
if (!ok) break;
}
return ok;
}
private class ProgressBarAnimator extends ValueAnimator {
private ProgressBarAnimator() {
setInterpolator(new LinearInterpolator());
setFloatValues(0f, 1f);
addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float percent = (float) animation.getAnimatedValue();
onUpdate(percent);
}
});
}
void onUpdate(float percent) {
if (mProgress != null) {
mProgress.setProgress((int) (percent * 10000));
}
if (mDuration != null) {
mDuration.setText(stringForTime((int) (percent * 10000)));
}
}
}
private class OnTouchListener implements View.OnTouchListener {
private final int TAP = 1;
private final int HOLD = 2;
private final int RELEASE = 3;
private final long LONG_PRESS = ViewConfiguration.getLongPressTimeout();
private final Context mContext;
private long mDownEventTimestamp;
private Rect mViewBoundsRect;
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TAP:
onTap();
break;
case HOLD:
onHold();
if (mCamera.getMaxVideoDuration() > 0) {
sendEmptyMessageDelayed(RELEASE, mCamera.getMaxVideoDuration());
}
break;
case RELEASE:
onRelease();
break;
}
}
};
OnTouchListener(Context context) {
mContext = context;
}
Context getContext() {
return mContext;
}
void onTap() {
mCamera.takePicture(new File(getContext().getCacheDir(), DateFormat.format(DESTINATION, new Date()) + PHOTO_EXT));
onTakePicture();
}
void onHold() {
vibrate();
mCamera.startRecording(new File(getContext().getCacheDir(), DateFormat.format(DESTINATION, new Date()) + VIDEO_EXT));
if (mDuration != null) {
mDuration.setVisibility(View.VISIBLE);
}
if (mCamera.getMaxVideoDuration() > 0) {
mAnimator.setDuration(mCamera.getMaxVideoDuration()).start();
}
onRecordStart();
}
void onRelease() {
mCamera.stopRecording();
mAnimator.cancel();
if (mProgress != null) {
mProgress.setProgress(0);
}
if (mDuration != null) {
mDuration.setVisibility(View.GONE);
}
onRecordStop();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownEventTimestamp = System.currentTimeMillis();
mViewBoundsRect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
mHandler.sendEmptyMessageDelayed(HOLD, LONG_PRESS);
v.setPressed(true);
break;
case MotionEvent.ACTION_MOVE:
// If the user moves their finger off the button, trigger RELEASE
if (mViewBoundsRect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
break;
}
// Fall through
case MotionEvent.ACTION_CANCEL:
clearHandler();
if (delta() > LONG_PRESS && (mCamera.getMaxVideoDuration() <= 0 || delta() < mCamera.getMaxVideoDuration())) {
mHandler.sendEmptyMessage(RELEASE);
}
v.setPressed(false);
break;
case MotionEvent.ACTION_UP:
clearHandler();
if (delta() < LONG_PRESS) {
mHandler.sendEmptyMessage(TAP);
} else if ((mCamera.getMaxVideoDuration() <= 0 || delta() < mCamera.getMaxVideoDuration())) {
mHandler.sendEmptyMessage(RELEASE);
}
v.setPressed(false);
break;
}
return true;
}
private long delta() {
return System.currentTimeMillis() - mDownEventTimestamp;
}
private void vibrate() {
Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator.hasVibrator() && hasPermissions(getContext(), Manifest.permission.VIBRATE)) {
vibrator.vibrate(25);
}
}
private void clearHandler() {
mHandler.removeMessages(TAP);
mHandler.removeMessages(HOLD);
mHandler.removeMessages(RELEASE);
}
}
}
| camera-view/src/main/java/com/xlythe/fragment/camera/CameraFragment.java | package com.xlythe.fragment.camera;
import android.Manifest;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresPermission;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.format.DateFormat;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.LinearInterpolator;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.xlythe.view.camera.CameraView;
import com.xlythe.view.camera.R;
import java.io.File;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;
public abstract class CameraFragment extends Fragment implements CameraView.OnImageCapturedListener, CameraView.OnVideoCapturedListener {
private static final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final int REQUEST_CODE_REQUIRED_PERMISSIONS = 3;
private static final String DESTINATION = "yyyy-MM-dd hh:mm:ss";
private static final String PHOTO_EXT = ".jpg";
private static final String VIDEO_EXT = ".mp4";
private View mCameraHolder;
private View mPermissionPrompt;
private CameraView mCamera;
private View mPermissionRequest;
private View mCapture;
private View mConfirm;
@Nullable
private TextView mDuration;
@Nullable
private ProgressBar mProgress;
@Nullable
private CompoundButton mToggle;
@Nullable
private View mCancel;
private ProgressBarAnimator mAnimator = new ProgressBarAnimator();
private DisplayManager.DisplayListener mDisplayListener;
@SuppressWarnings({"MissingPermission"})
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_REQUIRED_PERMISSIONS) {
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
showCamera();
} else {
showPermissionPrompt();
}
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (Build.VERSION.SDK_INT > 17) {
mDisplayListener = new DisplayManager.DisplayListener() {
@Override
public void onDisplayAdded(int displayId) {}
@Override
public void onDisplayRemoved(int displayId) {}
@SuppressWarnings({"MissingPermission"})
@Override
public void onDisplayChanged(int displayId) {
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
if (mCamera.isOpen()) {
mCamera.close();
mCamera.open();
}
}
}
};
DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
displayManager.registerDisplayListener(mDisplayListener, new Handler());
}
}
@Override
public void onDetach() {
if (Build.VERSION.SDK_INT > 17) {
DisplayManager displayManager = (DisplayManager) getContext().getSystemService(Context.DISPLAY_SERVICE);
displayManager.unregisterDisplayListener(mDisplayListener);
}
super.onDetach();
}
@SuppressWarnings({"MissingPermission"})
@Override
public void onStart() {
super.onStart();
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
showCamera();
} else {
showPermissionPrompt();
}
}
@Override
public void onStop() {
mCamera.close();
super.onStop();
}
public void setEnabled(boolean enabled) {
mCapture.setEnabled(enabled);
}
public boolean isEnabled() {
return mCapture.isEnabled();
}
public void setQuality(CameraView.Quality quality) {
mCamera.setQuality(quality);
}
public CameraView.Quality getQuality() {
return mCamera.getQuality();
}
public void setMaxVideoDuration(long duration) {
mCamera.setMaxVideoDuration(duration);
}
public long getMaxVideoDuration() {
return mCamera.getMaxVideoDuration();
}
public void setMaxVideoSize(long size) {
mCamera.setMaxVideoSize(size);
}
public long getMaxVideoSize() {
return mCamera.getMaxVideoSize();
}
protected void onTakePicture() {}
protected void onRecordStart() {}
protected void onRecordStop() {}
@RequiresPermission(allOf = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE
})
private void showCamera() {
mCameraHolder.setVisibility(View.VISIBLE);
mPermissionPrompt.setVisibility(View.GONE);
mCamera.open();
}
private void showPermissionPrompt() {
mCameraHolder.setVisibility(View.GONE);
mPermissionPrompt.setVisibility(View.VISIBLE);
}
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
Formatter formatter = new Formatter(Locale.getDefault());
if (hours > 0) {
return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return formatter.format("%02d:%02d", minutes, seconds).toString();
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mCameraHolder = view.findViewById(R.id.layout_camera);
mPermissionPrompt = view.findViewById(R.id.layout_permissions);
mPermissionRequest = view.findViewById(R.id.request_permissions);
mCamera = (CameraView) view.findViewById(R.id.camera);
mToggle = (CompoundButton) view.findViewById(R.id.toggle);
mCapture = mCameraHolder.findViewById(R.id.capture);
mProgress = (ProgressBar) view.findViewById(R.id.progress);
mDuration = (TextView) view.findViewById(R.id.duration);
mCancel = view.findViewById(R.id.cancel);
mConfirm = view.findViewById(R.id.confirm);
if (mCameraHolder == null) {
throw new IllegalStateException("No View found with id R.id.layout_camera");
}
if (mCamera == null) {
throw new IllegalStateException("No CameraView found with id R.id.camera");
}
if (mCapture == null) {
throw new IllegalStateException("No CameraView found with id R.id.capture");
}
if (mPermissionPrompt == null) {
throw new IllegalStateException("No View found with id R.id.layout_permissions");
}
if (mPermissionRequest == null) {
throw new IllegalStateException("No View found with id R.id.request_permissions");
}
mCamera.setOnImageCapturedListener(this);
mCamera.setOnVideoCapturedListener(this);
mCapture.setOnTouchListener(new OnTouchListener(getContext()));
if (mConfirm != null) {
mConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCamera.confirmPicture();
}
});
mCamera.setImageConfirmationEnabled(true);
mCamera.setVideoConfirmationEnabled(true);
} else {
mCamera.setImageConfirmationEnabled(false);
mCamera.setVideoConfirmationEnabled(false);
}
mPermissionRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(REQUIRED_PERMISSIONS, REQUEST_CODE_REQUIRED_PERMISSIONS);
}
});
if (mToggle != null) {
mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE);
mToggle.setChecked(mCamera.isUsingFrontFacingCamera());
mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCamera.toggleCamera();
}
});
}
if (mProgress != null) {
mProgress.setMax(10000);
}
if (mDuration != null) {
mDuration.setVisibility(View.GONE);
}
if (mCancel != null) {
mCancel.setVisibility(View.GONE);
}
mConfirm.setVisibility(View.GONE);
}
@Override
public void onFailure() {}
@Override
public void onImageConfirmation() {
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (view == mCancel) {
mCamera.rejectPicture();
} else {
mCamera.confirmPicture();
}
// After confirming/rejecting, show our buttons again
mConfirm.setVisibility(View.GONE);
mCapture.setVisibility(View.VISIBLE);
if (mCancel!= null) {
mCancel.setVisibility(View.GONE);
}
if (mToggle != null) {
mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE);
}
}
};
if (mCancel != null) {
mCancel.setVisibility(View.VISIBLE);
mCancel.setOnClickListener(listener);
}
if (mToggle != null) {
mToggle.setVisibility(View.GONE);
}
mCapture.setVisibility(View.GONE);
mConfirm.setVisibility(View.VISIBLE);
mConfirm.setOnClickListener(listener);
}
@Override
public void onVideoConfirmation() {
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (view == mCancel) {
mCamera.rejectVideo();
} else {
mCamera.confirmVideo();
}
// After confirming/rejecting, show our buttons again
mConfirm.setVisibility(View.GONE);
mCapture.setVisibility(View.VISIBLE);
if (mCancel!= null) {
mCancel.setVisibility(View.GONE);
}
if (mToggle != null) {
mToggle.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE);
}
}
};
if (mCancel != null) {
mCancel.setVisibility(View.VISIBLE);
mCancel.setOnClickListener(listener);
}
if (mToggle != null) {
mToggle.setVisibility(View.GONE);
}
mCapture.setVisibility(View.GONE);
mConfirm.setVisibility(View.VISIBLE);
mConfirm.setOnClickListener(listener);
}
/**
* Returns true if all given permissions are available
*/
public static boolean hasPermissions(Context context, String... permissions) {
boolean ok = true;
for (String permission : permissions) {
ok = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
if (!ok) break;
}
return ok;
}
private class ProgressBarAnimator extends ValueAnimator {
private ProgressBarAnimator() {
setInterpolator(new LinearInterpolator());
setFloatValues(0f, 1f);
addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float percent = (float) animation.getAnimatedValue();
onUpdate(percent);
}
});
}
void onUpdate(float percent) {
if (mProgress != null) {
mProgress.setProgress((int) (percent * 10000));
}
if (mDuration != null) {
mDuration.setText(stringForTime((int) (percent * 10000)));
}
}
}
private class OnTouchListener implements View.OnTouchListener {
private final int TAP = 1;
private final int HOLD = 2;
private final int RELEASE = 3;
private final long LONG_PRESS = ViewConfiguration.getLongPressTimeout();
private final Context mContext;
private long mDownEventTimestamp;
private Rect mViewBoundsRect;
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TAP:
onTap();
break;
case HOLD:
onHold();
if (mCamera.getMaxVideoDuration() > 0) {
sendEmptyMessageDelayed(RELEASE, mCamera.getMaxVideoDuration());
}
break;
case RELEASE:
onRelease();
break;
}
}
};
OnTouchListener(Context context) {
mContext = context;
}
Context getContext() {
return mContext;
}
void onTap() {
mCamera.takePicture(new File(getContext().getCacheDir(), DateFormat.format(DESTINATION, new Date()) + PHOTO_EXT));
onTakePicture();
}
void onHold() {
vibrate();
mCamera.startRecording(new File(getContext().getCacheDir(), DateFormat.format(DESTINATION, new Date()) + VIDEO_EXT));
if (mDuration != null) {
mDuration.setVisibility(View.VISIBLE);
}
if (mCamera.getMaxVideoDuration() > 0) {
mAnimator.setDuration(mCamera.getMaxVideoDuration()).start();
}
onRecordStart();
}
void onRelease() {
mCamera.stopRecording();
mAnimator.cancel();
if (mProgress != null) {
mProgress.setProgress(0);
}
if (mDuration != null) {
mDuration.setVisibility(View.GONE);
}
onRecordStop();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownEventTimestamp = System.currentTimeMillis();
mViewBoundsRect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
mHandler.sendEmptyMessageDelayed(HOLD, LONG_PRESS);
v.setPressed(true);
break;
case MotionEvent.ACTION_MOVE:
// If the user moves their finger off the button, trigger RELEASE
if (mViewBoundsRect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())) {
break;
}
// Fall through
case MotionEvent.ACTION_CANCEL:
clearHandler();
if (delta() > LONG_PRESS && (mCamera.getMaxVideoDuration() <= 0 || delta() < mCamera.getMaxVideoDuration())) {
mHandler.sendEmptyMessage(RELEASE);
}
v.setPressed(false);
break;
case MotionEvent.ACTION_UP:
clearHandler();
if (delta() < LONG_PRESS) {
mHandler.sendEmptyMessage(TAP);
} else if ((mCamera.getMaxVideoDuration() <= 0 || delta() < mCamera.getMaxVideoDuration())) {
mHandler.sendEmptyMessage(RELEASE);
}
v.setPressed(false);
break;
}
return true;
}
private long delta() {
return System.currentTimeMillis() - mDownEventTimestamp;
}
private void vibrate() {
Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator.hasVibrator() && hasPermissions(getContext(), Manifest.permission.VIBRATE)) {
vibrator.vibrate(25);
}
}
private void clearHandler() {
mHandler.removeMessages(TAP);
mHandler.removeMessages(HOLD);
mHandler.removeMessages(RELEASE);
}
}
}
| Update CameraFragment.java | camera-view/src/main/java/com/xlythe/fragment/camera/CameraFragment.java | Update CameraFragment.java | <ide><path>amera-view/src/main/java/com/xlythe/fragment/camera/CameraFragment.java
<ide> mPermissionPrompt.setVisibility(View.VISIBLE);
<ide> }
<ide>
<del> private String stringForTime(int timeMs) {
<add> private static String stringForTime(int timeMs) {
<ide> int totalSeconds = timeMs / 1000;
<ide>
<ide> int seconds = totalSeconds % 60; |
|
Java | mit | 5d146c923620523a871a0fe50bdcbc3b7559df8c | 0 | jvd001/android-library,jvd001/android-library,luizpagnez/android-library,noyo/android-library,luizpagnez/android-library,cloudcopy/owncloud-android-library,noyo/android-library,cloudcopy/owncloud-android-library | /* ownCloud Android Library is available under MIT license
* Copyright (C) 2014 ownCloud Inc.
*
* 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.
*
*/
package com.owncloud.android.lib.test_project.test;
import java.io.File;
import java.security.GeneralSecurityException;
import junit.framework.AssertionFailedError;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.network.NetworkUtils;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
import com.owncloud.android.lib.resources.files.MoveRemoteFileOperation;
import com.owncloud.android.lib.test_project.R;
import com.owncloud.android.lib.test_project.SelfSignedConfidentSslSocketFactory;
import com.owncloud.android.lib.test_project.TestActivity;
import android.content.Context;
import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2;
//import android.test.AndroidTestCase;
import android.util.Log;
/**
* Class to test MoveRemoteFileOperation
*
* With this TestCase we are experimenting a bit to improve the test suite design, in two aspects:
*
* - Reduce the dependency from the set of test cases on the "test project" needed to
* have an instrumented APK to install in the device, as required by the testing framework
* provided by Android. To get there, this class avoids calling TestActivity methods in the test
* method.
*
* - Reduce the impact of creating a remote fixture over the Internet, while the structure of the
* TestCase is kept easy to maintain. To get this, all the tests are done in a single test method,
* granting this way that setUp and tearDown are run only once.
*
*
* @author David A. Velasco
*/
//public class MoveFileTest extends AndroidTestCase {
public class MoveFileTest extends ActivityInstrumentationTestCase2<TestActivity> {
private static final String LOG_TAG = MoveFileTest.class.getCanonicalName();
/// Paths to files and folders in fixture
private static final String SRC_BASE_FOLDER = "/src/";
private static final String TARGET_BASE_FOLDER = "/target/";
private static final String NO_FILE = "nofile.txt";
private static final String FILE1 = "file1.txt";
private static final String FILE2 = "file2.txt";
private static final String FILE3 = "file3.txt";
private static final String FILE4 = "file4.txt";
private static final String FILE5 = "file5.txt";
private static final String FILE6 = "file6.txt";
private static final String FILE7 = "file7.txt";
private static final String EMPTY = "empty/";
private static final String NO_FOLDER = "nofolder/";
private static final String FOLDER1 = "folder1/";
private static final String FOLDER2 = "folder2/";
private static final String FOLDER3 = "folder3/";
private static final String FOLDER4 = "folder4/";
private static final String SRC_PATH_TO_FILE_1 = SRC_BASE_FOLDER + FILE1;
private static final String TARGET_PATH_TO_FILE_1 = TARGET_BASE_FOLDER + FILE1;
private static final String SRC_PATH_TO_FILE_2 = SRC_BASE_FOLDER + FILE2;
private static final String TARGET_PATH_TO_FILE_2_RENAMED =
TARGET_BASE_FOLDER + "renamed_" + FILE2;
private static final String SRC_PATH_TO_FILE_3 = SRC_BASE_FOLDER + FILE3;
private static final String SRC_PATH_TO_FILE_3_RENAMED = SRC_BASE_FOLDER + "renamed_" + FILE3;
private static final String SRC_PATH_TO_FILE_4 = SRC_BASE_FOLDER + FILE4;
private static final String SRC_PATH_TO_FILE_5 = SRC_BASE_FOLDER + FILE5;
private static final String SRC_PATH_TO_FILE_6 = SRC_BASE_FOLDER + FILE6;
private static final String SRC_PATH_TO_FILE_7 = SRC_BASE_FOLDER + FILE7;
private static final String SRC_PATH_TO_NON_EXISTENT_FILE = SRC_BASE_FOLDER + NO_FILE;
private static final String SRC_PATH_TO_EMPTY_FOLDER = SRC_BASE_FOLDER + EMPTY;
private static final String TARGET_PATH_TO_EMPTY_FOLDER = TARGET_BASE_FOLDER + EMPTY;
private static final String SRC_PATH_TO_FULL_FOLDER_1 = SRC_BASE_FOLDER + FOLDER1;
private static final String TARGET_PATH_TO_FULL_FOLDER_1 = TARGET_BASE_FOLDER + FOLDER1;
private static final String SRC_PATH_TO_FULL_FOLDER_2 = SRC_BASE_FOLDER + FOLDER2;
private static final String TARGET_PATH_TO_FULL_FOLDER_2_RENAMED =
TARGET_BASE_FOLDER + "renamed_" + FOLDER2;
private static final String SRC_PATH_TO_FULL_FOLDER_3 = SRC_BASE_FOLDER + FOLDER3;
private static final String SRC_PATH_TO_FULL_FOLDER_4 = SRC_BASE_FOLDER + FOLDER4;
private static final String SRC_PATH_TO_FULL_FOLDER_3_RENAMED =
SRC_BASE_FOLDER + "renamed_" + FOLDER3;
private static final String TARGET_PATH_RENAMED_WITH_INVALID_CHARS =
SRC_BASE_FOLDER + "renamed:??_" + FILE6;
private static final String TARGET_PATH_TO_ALREADY_EXISTENT_EMPTY_FOLDER_4 = TARGET_BASE_FOLDER
+ FOLDER4;
private static final String TARGET_PATH_TO_NON_EXISTENT_FILE = TARGET_BASE_FOLDER + NO_FILE;
private static final String TARGET_PATH_TO_FILE_5_INTO_NON_EXISTENT_FOLDER =
TARGET_BASE_FOLDER + NO_FOLDER + FILE5;
private static final String TARGET_PATH_TO_ALREADY_EXISTENT_FILE_7 = TARGET_BASE_FOLDER + FILE7;
private static final String[] FOLDERS_IN_FIXTURE = {
SRC_PATH_TO_EMPTY_FOLDER,
SRC_PATH_TO_FULL_FOLDER_1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_2,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_3,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_4,
SRC_PATH_TO_FULL_FOLDER_4 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FOLDER2,
TARGET_BASE_FOLDER,
TARGET_PATH_TO_ALREADY_EXISTENT_EMPTY_FOLDER_4
};
private static final String[] FILES_IN_FIXTURE = {
SRC_PATH_TO_FILE_1,
SRC_PATH_TO_FILE_2,
SRC_PATH_TO_FILE_3,
SRC_PATH_TO_FILE_4,
SRC_PATH_TO_FILE_5,
SRC_PATH_TO_FULL_FOLDER_1 + FILE1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_3 + FILE1,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_4 + FILE1,
SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FOLDER2 + FILE2,
TARGET_PATH_TO_ALREADY_EXISTENT_FILE_7
};
String mServerUri, mUser, mPass;
OwnCloudClient mClient = null;
public MoveFileTest() {
super(TestActivity.class);
Protocol pr = Protocol.getProtocol("https");
if (pr == null || !(pr.getSocketFactory() instanceof SelfSignedConfidentSslSocketFactory)) {
try {
ProtocolSocketFactory psf = new SelfSignedConfidentSslSocketFactory();
Protocol.registerProtocol(
"https",
new Protocol("https", psf, 443));
} catch (GeneralSecurityException e) {
throw new AssertionFailedError(
"Self-signed confident SSL context could not be loaded");
}
}
}
protected Context getContext() {
return getActivity();
}
@Override
protected void setUp() throws Exception {
super.setUp();
// Next initialization cannot be done in the constructor because getContext() is not
// ready yet, returns NULL.
initAccessToServer(getContext());
Log.v(LOG_TAG, "Setting up the remote fixture...");
RemoteOperationResult result = null;
for (String folderPath : FOLDERS_IN_FIXTURE) {
result = TestActivity.createFolder(folderPath, true, mClient);
if (!result.isSuccess()) {
Utils.logAndThrow(LOG_TAG, result);
}
}
File txtFile = TestActivity.extractAsset(
TestActivity.ASSETS__TEXT_FILE_NAME, getContext()
);
for (String filePath : FILES_IN_FIXTURE) {
result = TestActivity.uploadFile(
txtFile.getAbsolutePath(), filePath, "txt/plain", mClient
);
if (!result.isSuccess()) {
Utils.logAndThrow(LOG_TAG, result);
}
}
Log.v(LOG_TAG, "Remote fixture created.");
}
/**
* Test move folder
*/
public void testMoveRemoteFileOperation() {
Log.v(LOG_TAG, "testMoveFolder in");
/// successful cases
// move file
MoveRemoteFileOperation moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_1,
TARGET_PATH_TO_FILE_1,
false
);
RemoteOperationResult result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move & rename file, different location
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_2,
TARGET_PATH_TO_FILE_2_RENAMED,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move & rename file, same location (rename file)
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_3,
SRC_PATH_TO_FILE_3_RENAMED,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move empty folder
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_EMPTY_FOLDER,
TARGET_PATH_TO_EMPTY_FOLDER,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move non-empty folder
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_1,
TARGET_PATH_TO_FULL_FOLDER_1,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move & rename folder, different location
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_2,
TARGET_PATH_TO_FULL_FOLDER_2_RENAMED,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move & rename folder, same location (rename folder)
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_3,
SRC_PATH_TO_FULL_FOLDER_3_RENAMED,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move for nothing (success, but no interaction with network)
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_4,
SRC_PATH_TO_FILE_4,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move overwriting
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_4,
TARGET_PATH_TO_ALREADY_EXISTENT_EMPTY_FOLDER_4,
true
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
/// Failed cases
// file to move does not exist
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_NON_EXISTENT_FILE,
TARGET_PATH_TO_NON_EXISTENT_FILE,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.FILE_NOT_FOUND);
// folder to move into does no exist
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_5,
TARGET_PATH_TO_FILE_5_INTO_NON_EXISTENT_FOLDER,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getHttpCode() == HttpStatus.SC_CONFLICT);
// target location (renaming) has invalid characters
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_6,
TARGET_PATH_RENAMED_WITH_INVALID_CHARS,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME);
// name collision
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_7,
TARGET_PATH_TO_ALREADY_EXISTENT_FILE_7,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);
// move a folder into a descendant
moveOperation = new MoveRemoteFileOperation(
SRC_BASE_FOLDER,
SRC_PATH_TO_EMPTY_FOLDER,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.INVALID_MOVE_INTO_DESCENDANT);
}
@Override
protected void tearDown() throws Exception {
Log.v(LOG_TAG, "Deleting remote fixture...");
String[] mPathsToCleanUp = {
SRC_BASE_FOLDER,
TARGET_BASE_FOLDER
};
for (String path : mPathsToCleanUp) {
RemoteOperationResult removeResult =
TestActivity.removeFile(path, mClient);
if (!removeResult.isSuccess() && removeResult.getCode() != ResultCode.TIMEOUT ) {
Utils.logAndThrow(LOG_TAG, removeResult);
}
}
super.tearDown();
Log.v(LOG_TAG, "Remote fixture delete.");
}
private void initAccessToServer(Context context) {
Log.v(LOG_TAG, "Setting up client instance to access OC server...");
mServerUri = context.getString(R.string.server_base_url);
mUser = context.getString(R.string.username);
mPass = context.getString(R.string.password);
mClient = new OwnCloudClient(
Uri.parse(mServerUri),
NetworkUtils.getMultiThreadedConnManager()
);
mClient.setDefaultTimeouts(
OwnCloudClientFactory.DEFAULT_DATA_TIMEOUT,
OwnCloudClientFactory.DEFAULT_CONNECTION_TIMEOUT);
mClient.setFollowRedirects(true);
mClient.setCredentials(
OwnCloudCredentialsFactory.newBasicCredentials(
mUser,
mPass
)
);
Log.v(LOG_TAG, "Client instance set up.");
}
}
| test_client/tests/src/com/owncloud/android/lib/test_project/test/MoveFileTest.java | /* ownCloud Android Library is available under MIT license
* Copyright (C) 2014 ownCloud Inc.
*
* 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.
*
*/
package com.owncloud.android.lib.test_project.test;
import java.io.File;
import java.security.GeneralSecurityException;
import junit.framework.AssertionFailedError;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.network.NetworkUtils;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
import com.owncloud.android.lib.resources.files.MoveRemoteFileOperation;
import com.owncloud.android.lib.test_project.R;
import com.owncloud.android.lib.test_project.SelfSignedConfidentSslSocketFactory;
import com.owncloud.android.lib.test_project.TestActivity;
import android.content.Context;
import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2;
//import android.test.AndroidTestCase;
import android.util.Log;
/**
* Class to test MoveRemoteFileOperation
*
* With this TestCase we are experimenting a bit to improve the test suite design, in two aspects:
*
* - Reduce the dependency from the set of test cases on the "test project" needed to
* have an instrumented APK to install in the device, as required by the testing framework
* provided by Android. To get there, this class avoids calling TestActivity methods in the test
* method.
*
* - Reduce the impact of creating a remote fixture over the Internet, while the structure of the
* TestCase is kept easy to maintain. To get this, all the tests are done in a single test method,
* granting this way that setUp and tearDown are run only once.
*
*
* @author David A. Velasco
*/
//public class MoveFileTest extends AndroidTestCase {
public class MoveFileTest extends ActivityInstrumentationTestCase2<TestActivity> {
private static final String LOG_TAG = MoveFileTest.class.getCanonicalName();
/// Paths to files and folders in fixture
private static final String SRC_BASE_FOLDER = "/src/";
private static final String SRC_BASE_FOLDER_NON_CREATED = "/src_non_created/";
private static final String TARGET_BASE_FOLDER = "/target/";
private static final String FILE1 = "file1.txt";
private static final String FILE2 = "file2.txt";
private static final String FILE3 = "file3.txt";
private static final String FILE4 = "file4.txt";
private static final String FILE5 = "file5.txt";
private static final String EMPTY = "empty/";
private static final String FOLDER1 = "folder1/";
private static final String FOLDER2 = "folder2/";
private static final String FOLDER3 = "folder3/";
private static final String FOLDER4 = "folder4/";
private static final String FOLDER5 = "folder5/";
private static final String SRC_PATH_TO_FILE_1 = SRC_BASE_FOLDER + FILE1;
private static final String TARGET_PATH_TO_FILE_1 = TARGET_BASE_FOLDER + FILE1;
private static final String SRC_PATH_TO_FILE_2 = SRC_BASE_FOLDER + FILE2;
private static final String TARGET_PATH_TO_FILE_2_RENAMED =
TARGET_BASE_FOLDER + "renamed_" + FILE2;
private static final String SRC_PATH_TO_FILE_3 = SRC_BASE_FOLDER + FILE3;
private static final String SRC_PATH_TO_FILE_3_RENAMED = SRC_BASE_FOLDER + "renamed_" + FILE3;
private static final String SRC_PATH_TO_FILE_4 = SRC_BASE_FOLDER + FILE4;
private static final String SRC_PATH_TO_FILE_NON_EXISTS = SRC_BASE_FOLDER + FILE5;
private static final String SRC_PATH_TO_EMPTY_FOLDER = SRC_BASE_FOLDER + EMPTY;
private static final String TARGET_PATH_TO_EMPTY_FOLDER = TARGET_BASE_FOLDER + EMPTY;
private static final String SRC_PATH_TO_FULL_FOLDER_1 = SRC_BASE_FOLDER + FOLDER1;
private static final String TARGET_PATH_TO_FULL_FOLDER_1 = TARGET_BASE_FOLDER + FOLDER1;
private static final String SRC_PATH_TO_FULL_FOLDER_2 = SRC_BASE_FOLDER + FOLDER2;
private static final String TARGET_PATH_TO_FULL_FOLDER_2_RENAMED =
TARGET_BASE_FOLDER + "renamed_" + FOLDER2;
private static final String SRC_PATH_TO_FULL_FOLDER_3 = SRC_BASE_FOLDER + FOLDER3;
private static final String SRC_PATH_TO_FULL_FOLDER_4 = SRC_BASE_FOLDER + FOLDER4;
private static final String SRC_PATH_TO_FULL_FOLDER_5 = SRC_BASE_FOLDER + FOLDER5;
private static final String SRC_PATH_TO_FULL_FOLDER_3_RENAMED =
SRC_BASE_FOLDER + "renamed_" + FOLDER3;
private static final String SRC_PATH_TO_FULL_FOLDER_4_RENAMED_INVALID_CHARS =
SRC_BASE_FOLDER + "renamed:??_" + FOLDER4;
private static final String SRC_PATH_TO_FULL_FOLDER_5_INSIDE_FOLDER_4 = SRC_BASE_FOLDER
+ FOLDER4 + FOLDER5;
private static final String[] FOLDERS_IN_FIXTURE = {
SRC_PATH_TO_EMPTY_FOLDER,
SRC_PATH_TO_FULL_FOLDER_1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_2,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_3,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER1,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER2,
SRC_PATH_TO_FULL_FOLDER_5,
SRC_PATH_TO_FULL_FOLDER_5_INSIDE_FOLDER_4,
TARGET_BASE_FOLDER,
};
private static final String[] FILES_IN_FIXTURE = {
SRC_PATH_TO_FILE_1,
SRC_PATH_TO_FILE_2,
SRC_PATH_TO_FILE_3,
SRC_PATH_TO_FILE_4,
SRC_PATH_TO_FULL_FOLDER_1 + FILE1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_2 + FOLDER2 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_3 + FILE1,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FILE1,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FILE2,
SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER2 + FILE2,
};
String mServerUri, mUser, mPass;
OwnCloudClient mClient = null;
public MoveFileTest() {
super(TestActivity.class);
Protocol pr = Protocol.getProtocol("https");
if (pr == null || !(pr.getSocketFactory() instanceof SelfSignedConfidentSslSocketFactory)) {
try {
ProtocolSocketFactory psf = new SelfSignedConfidentSslSocketFactory();
Protocol.registerProtocol(
"https",
new Protocol("https", psf, 443));
} catch (GeneralSecurityException e) {
throw new AssertionFailedError(
"Self-signed confident SSL context could not be loaded");
}
}
}
protected Context getContext() {
return getActivity();
}
@Override
protected void setUp() throws Exception {
super.setUp();
// Next initialization cannot be done in the constructor because getContext() is not
// ready yet, returns NULL.
initAccessToServer(getContext());
Log.v(LOG_TAG, "Setting up the remote fixture...");
RemoteOperationResult result = null;
for (String folderPath : FOLDERS_IN_FIXTURE) {
result = TestActivity.createFolder(folderPath, true, mClient);
if (!result.isSuccess()) {
Utils.logAndThrow(LOG_TAG, result);
}
}
File txtFile = TestActivity.extractAsset(
TestActivity.ASSETS__TEXT_FILE_NAME, getContext()
);
for (String filePath : FILES_IN_FIXTURE) {
result = TestActivity.uploadFile(
txtFile.getAbsolutePath(), filePath, "txt/plain", mClient
);
if (!result.isSuccess()) {
Utils.logAndThrow(LOG_TAG, result);
}
}
Log.v(LOG_TAG, "Remote fixture created.");
}
/**
* Test move folder
*/
public void testMoveRemoteFileOperation() {
Log.v(LOG_TAG, "testMoveFolder in");
/// successful cases
// move file
MoveRemoteFileOperation moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_1,
TARGET_PATH_TO_FILE_1,
false
);
RemoteOperationResult result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move & rename file, different location
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_2,
TARGET_PATH_TO_FILE_2_RENAMED,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move & rename file, same location (rename file)
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_3,
SRC_PATH_TO_FILE_3_RENAMED,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move empty folder
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_EMPTY_FOLDER,
TARGET_PATH_TO_EMPTY_FOLDER,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move non-empty folder
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_1,
TARGET_PATH_TO_FULL_FOLDER_1,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move & rename folder, different location
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_2,
TARGET_PATH_TO_FULL_FOLDER_2_RENAMED,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move & rename folder, same location (rename folder)
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_3,
SRC_PATH_TO_FULL_FOLDER_3_RENAMED,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move for nothing (success, but no interaction with network)
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_4,
SRC_PATH_TO_FILE_4,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// move to the same name folder but overwrite it
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_5,
SRC_PATH_TO_FULL_FOLDER_5_INSIDE_FOLDER_4,
true
);
result = moveOperation.execute(mClient);
assertTrue(result.isSuccess());
// Failed cases
// file to move does not exist
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FILE_NON_EXISTS,
SRC_PATH_TO_FULL_FOLDER_4,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);
// folder to move into does no exist
moveOperation = new MoveRemoteFileOperation(
SRC_BASE_FOLDER_NON_CREATED,
SRC_PATH_TO_FILE_4,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);
// target location (renaming) has invalid characters
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_4,
SRC_PATH_TO_FULL_FOLDER_4_RENAMED_INVALID_CHARS,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME);
// name collision
moveOperation = new MoveRemoteFileOperation(
SRC_PATH_TO_FULL_FOLDER_5,
SRC_PATH_TO_FULL_FOLDER_5_INSIDE_FOLDER_4,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);
// move a folder into a descendant
moveOperation = new MoveRemoteFileOperation(
SRC_BASE_FOLDER,
SRC_PATH_TO_FULL_FOLDER_4,
false
);
result = moveOperation.execute(mClient);
assertTrue(result.getCode() == ResultCode.INVALID_MOVE_INTO_DESCENDANT);
}
@Override
protected void tearDown() throws Exception {
Log.v(LOG_TAG, "Deleting remote fixture...");
String[] mPathsToCleanUp = {
SRC_BASE_FOLDER,
TARGET_BASE_FOLDER
};
for (String path : mPathsToCleanUp) {
RemoteOperationResult removeResult =
TestActivity.removeFile(path, mClient);
if (!removeResult.isSuccess()) {
Utils.logAndThrow(LOG_TAG, removeResult);
}
}
super.tearDown();
Log.v(LOG_TAG, "Remote fixture delete.");
}
private void initAccessToServer(Context context) {
Log.v(LOG_TAG, "Setting up client instance to access OC server...");
mServerUri = context.getString(R.string.server_base_url);
mUser = context.getString(R.string.username);
mPass = context.getString(R.string.password);
mClient = new OwnCloudClient(
Uri.parse(mServerUri),
NetworkUtils.getMultiThreadedConnManager()
);
mClient.setDefaultTimeouts(
OwnCloudClientFactory.DEFAULT_DATA_TIMEOUT,
OwnCloudClientFactory.DEFAULT_CONNECTION_TIMEOUT);
mClient.setFollowRedirects(true);
mClient.setCredentials(
OwnCloudCredentialsFactory.newBasicCredentials(
mUser,
mPass
)
);
Log.v(LOG_TAG, "Client instance set up.");
}
}
| Some improvementes in tests on failed move operations
| test_client/tests/src/com/owncloud/android/lib/test_project/test/MoveFileTest.java | Some improvementes in tests on failed move operations | <ide><path>est_client/tests/src/com/owncloud/android/lib/test_project/test/MoveFileTest.java
<ide>
<ide> import junit.framework.AssertionFailedError;
<ide>
<add>import org.apache.commons.httpclient.HttpStatus;
<ide> import org.apache.commons.httpclient.protocol.Protocol;
<ide> import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
<ide>
<ide> /// Paths to files and folders in fixture
<ide>
<ide> private static final String SRC_BASE_FOLDER = "/src/";
<del> private static final String SRC_BASE_FOLDER_NON_CREATED = "/src_non_created/";
<ide> private static final String TARGET_BASE_FOLDER = "/target/";
<add> private static final String NO_FILE = "nofile.txt";
<ide> private static final String FILE1 = "file1.txt";
<ide> private static final String FILE2 = "file2.txt";
<ide> private static final String FILE3 = "file3.txt";
<ide> private static final String FILE4 = "file4.txt";
<ide> private static final String FILE5 = "file5.txt";
<add> private static final String FILE6 = "file6.txt";
<add> private static final String FILE7 = "file7.txt";
<ide> private static final String EMPTY = "empty/";
<add> private static final String NO_FOLDER = "nofolder/";
<ide> private static final String FOLDER1 = "folder1/";
<ide> private static final String FOLDER2 = "folder2/";
<ide> private static final String FOLDER3 = "folder3/";
<ide> private static final String FOLDER4 = "folder4/";
<del> private static final String FOLDER5 = "folder5/";
<ide>
<ide> private static final String SRC_PATH_TO_FILE_1 = SRC_BASE_FOLDER + FILE1;
<ide> private static final String TARGET_PATH_TO_FILE_1 = TARGET_BASE_FOLDER + FILE1;
<ide>
<ide> private static final String SRC_PATH_TO_FILE_4 = SRC_BASE_FOLDER + FILE4;
<ide>
<del> private static final String SRC_PATH_TO_FILE_NON_EXISTS = SRC_BASE_FOLDER + FILE5;
<add> private static final String SRC_PATH_TO_FILE_5 = SRC_BASE_FOLDER + FILE5;
<add>
<add> private static final String SRC_PATH_TO_FILE_6 = SRC_BASE_FOLDER + FILE6;
<add>
<add> private static final String SRC_PATH_TO_FILE_7 = SRC_BASE_FOLDER + FILE7;
<add>
<add> private static final String SRC_PATH_TO_NON_EXISTENT_FILE = SRC_BASE_FOLDER + NO_FILE;
<ide>
<ide> private static final String SRC_PATH_TO_EMPTY_FOLDER = SRC_BASE_FOLDER + EMPTY;
<ide> private static final String TARGET_PATH_TO_EMPTY_FOLDER = TARGET_BASE_FOLDER + EMPTY;
<ide>
<ide> private static final String SRC_PATH_TO_FULL_FOLDER_3 = SRC_BASE_FOLDER + FOLDER3;
<ide> private static final String SRC_PATH_TO_FULL_FOLDER_4 = SRC_BASE_FOLDER + FOLDER4;
<del> private static final String SRC_PATH_TO_FULL_FOLDER_5 = SRC_BASE_FOLDER + FOLDER5;
<ide>
<ide> private static final String SRC_PATH_TO_FULL_FOLDER_3_RENAMED =
<ide> SRC_BASE_FOLDER + "renamed_" + FOLDER3;
<ide>
<del> private static final String SRC_PATH_TO_FULL_FOLDER_4_RENAMED_INVALID_CHARS =
<del> SRC_BASE_FOLDER + "renamed:??_" + FOLDER4;
<del>
<del> private static final String SRC_PATH_TO_FULL_FOLDER_5_INSIDE_FOLDER_4 = SRC_BASE_FOLDER
<del> + FOLDER4 + FOLDER5;
<del>
<add> private static final String TARGET_PATH_RENAMED_WITH_INVALID_CHARS =
<add> SRC_BASE_FOLDER + "renamed:??_" + FILE6;
<add>
<add> private static final String TARGET_PATH_TO_ALREADY_EXISTENT_EMPTY_FOLDER_4 = TARGET_BASE_FOLDER
<add> + FOLDER4;
<add>
<add> private static final String TARGET_PATH_TO_NON_EXISTENT_FILE = TARGET_BASE_FOLDER + NO_FILE;
<add>
<add> private static final String TARGET_PATH_TO_FILE_5_INTO_NON_EXISTENT_FOLDER =
<add> TARGET_BASE_FOLDER + NO_FOLDER + FILE5;
<add>
<add> private static final String TARGET_PATH_TO_ALREADY_EXISTENT_FILE_7 = TARGET_BASE_FOLDER + FILE7;
<ide>
<ide> private static final String[] FOLDERS_IN_FIXTURE = {
<ide> SRC_PATH_TO_EMPTY_FOLDER,
<ide> SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER1,
<ide> SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER2,
<ide>
<del> SRC_PATH_TO_FULL_FOLDER_5,
<del> SRC_PATH_TO_FULL_FOLDER_5_INSIDE_FOLDER_4,
<add> SRC_PATH_TO_FULL_FOLDER_4,
<add> SRC_PATH_TO_FULL_FOLDER_4 + FOLDER1,
<add> SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2,
<add> SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FOLDER1,
<add> SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FOLDER2,
<ide>
<ide> TARGET_BASE_FOLDER,
<add> TARGET_PATH_TO_ALREADY_EXISTENT_EMPTY_FOLDER_4
<ide> };
<ide>
<ide> private static final String[] FILES_IN_FIXTURE = {
<ide> SRC_PATH_TO_FILE_2,
<ide> SRC_PATH_TO_FILE_3,
<ide> SRC_PATH_TO_FILE_4,
<add> SRC_PATH_TO_FILE_5,
<ide>
<ide> SRC_PATH_TO_FULL_FOLDER_1 + FILE1,
<ide> SRC_PATH_TO_FULL_FOLDER_1 + FOLDER2 + FILE1,
<ide> SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FILE1,
<ide> SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FILE2,
<ide> SRC_PATH_TO_FULL_FOLDER_3 + FOLDER2 + FOLDER2 + FILE2,
<add>
<add> SRC_PATH_TO_FULL_FOLDER_4 + FILE1,
<add> SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FILE1,
<add> SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FILE2,
<add> SRC_PATH_TO_FULL_FOLDER_4 + FOLDER2 + FOLDER2 + FILE2,
<add>
<add> TARGET_PATH_TO_ALREADY_EXISTENT_FILE_7
<ide> };
<ide>
<ide>
<ide> result = moveOperation.execute(mClient);
<ide> assertTrue(result.isSuccess());
<ide>
<del> // move to the same name folder but overwrite it
<del> moveOperation = new MoveRemoteFileOperation(
<del> SRC_PATH_TO_FULL_FOLDER_5,
<del> SRC_PATH_TO_FULL_FOLDER_5_INSIDE_FOLDER_4,
<add> // move overwriting
<add> moveOperation = new MoveRemoteFileOperation(
<add> SRC_PATH_TO_FULL_FOLDER_4,
<add> TARGET_PATH_TO_ALREADY_EXISTENT_EMPTY_FOLDER_4,
<ide> true
<ide> );
<ide> result = moveOperation.execute(mClient);
<ide> assertTrue(result.isSuccess());
<ide>
<ide>
<del> // Failed cases
<add> /// Failed cases
<ide>
<ide> // file to move does not exist
<ide> moveOperation = new MoveRemoteFileOperation(
<del> SRC_PATH_TO_FILE_NON_EXISTS,
<del> SRC_PATH_TO_FULL_FOLDER_4,
<add> SRC_PATH_TO_NON_EXISTENT_FILE,
<add> TARGET_PATH_TO_NON_EXISTENT_FILE,
<ide> false
<ide> );
<ide> result = moveOperation.execute(mClient);
<add> assertTrue(result.getCode() == ResultCode.FILE_NOT_FOUND);
<add>
<add> // folder to move into does no exist
<add> moveOperation = new MoveRemoteFileOperation(
<add> SRC_PATH_TO_FILE_5,
<add> TARGET_PATH_TO_FILE_5_INTO_NON_EXISTENT_FOLDER,
<add> false
<add> );
<add> result = moveOperation.execute(mClient);
<add> assertTrue(result.getHttpCode() == HttpStatus.SC_CONFLICT);
<add>
<add> // target location (renaming) has invalid characters
<add> moveOperation = new MoveRemoteFileOperation(
<add> SRC_PATH_TO_FILE_6,
<add> TARGET_PATH_RENAMED_WITH_INVALID_CHARS,
<add> false
<add> );
<add> result = moveOperation.execute(mClient);
<add> assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME);
<add>
<add> // name collision
<add> moveOperation = new MoveRemoteFileOperation(
<add> SRC_PATH_TO_FILE_7,
<add> TARGET_PATH_TO_ALREADY_EXISTENT_FILE_7,
<add> false
<add> );
<add> result = moveOperation.execute(mClient);
<ide> assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);
<ide>
<del> // folder to move into does no exist
<del> moveOperation = new MoveRemoteFileOperation(
<del> SRC_BASE_FOLDER_NON_CREATED,
<del> SRC_PATH_TO_FILE_4,
<del> false
<del> );
<del> result = moveOperation.execute(mClient);
<del> assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);
<del>
<del> // target location (renaming) has invalid characters
<del> moveOperation = new MoveRemoteFileOperation(
<del> SRC_PATH_TO_FULL_FOLDER_4,
<del> SRC_PATH_TO_FULL_FOLDER_4_RENAMED_INVALID_CHARS,
<del> false
<del> );
<del> result = moveOperation.execute(mClient);
<del> assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME);
<del>
<del> // name collision
<del> moveOperation = new MoveRemoteFileOperation(
<del> SRC_PATH_TO_FULL_FOLDER_5,
<del> SRC_PATH_TO_FULL_FOLDER_5_INSIDE_FOLDER_4,
<del> false
<del> );
<del> result = moveOperation.execute(mClient);
<del> assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);
<del>
<ide> // move a folder into a descendant
<ide> moveOperation = new MoveRemoteFileOperation(
<ide> SRC_BASE_FOLDER,
<del> SRC_PATH_TO_FULL_FOLDER_4,
<add> SRC_PATH_TO_EMPTY_FOLDER,
<ide> false
<ide> );
<ide> result = moveOperation.execute(mClient);
<ide> for (String path : mPathsToCleanUp) {
<ide> RemoteOperationResult removeResult =
<ide> TestActivity.removeFile(path, mClient);
<del> if (!removeResult.isSuccess()) {
<add> if (!removeResult.isSuccess() && removeResult.getCode() != ResultCode.TIMEOUT ) {
<ide> Utils.logAndThrow(LOG_TAG, removeResult);
<ide> }
<ide> } |
|
Java | apache-2.0 | 660dace8ebcbe06693d1e2f8387cdc6a53bd9a85 | 0 | stealthcopter/AndroidNetworkTools,stealthcopter/AndroidNetworkTools | package com.stealthcopter.networktools;
import android.support.annotation.NonNull;
import com.stealthcopter.networktools.portscanning.PortScanTCP;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Created by mat on 14/12/15.
*/
public class PortScan {
public interface PortListener{
void onResult(int portNo, boolean open);
void onFinished(ArrayList<Integer> openPorts);
}
private InetAddress address;
private int timeOutMillis = 1000;
private boolean cancelled = false;
private ArrayList<Integer> ports = new ArrayList<>();
/**
* Set the address to ping
* @param address - Address to be pinged
* @return this object to allow chaining
* @throws UnknownHostException - if no IP address for the
* <code>host</code> could be found, or if a scope_id was specified
* for a global IPv6 address.
*/
public static PortScan onAddress(@NonNull String address) throws UnknownHostException {
PortScan portScan = new PortScan();
InetAddress ia = InetAddress.getByName(address);
portScan.setAddress(ia);
return portScan;
}
/**
* Set the address to ping
* @param ia - Address to be pinged
* @return this object to allow chaining
*/
public static PortScan onAddress(@NonNull InetAddress ia) {
PortScan portScan = new PortScan();
portScan.setAddress(ia);
return portScan;
}
/**
* Set the timeout
* @param timeOutMillis - the timeout for each ping in milliseconds
* @return this object to allow chaining
*/
public PortScan setTimeOutMillis(int timeOutMillis){
if (timeOutMillis<0) throw new IllegalArgumentException("Times cannot be less than 0");
this.timeOutMillis = timeOutMillis;
return this;
}
/**
* Scan the ports to scan
* @param port - the port to scan
* @return this object to allow chaining
*/
public PortScan setPort(int port){
ports.clear();
validatePort(port);
ports.add(port);
return this;
}
/**
* Scan the ports to scan
* @param ports - the ports to scan
* @return this object to allow chaining
*/
public PortScan setPorts(ArrayList<Integer> ports){
// Check all ports are valid
for(Integer port : ports){
validatePort(port);
}
this.ports = ports;
return this;
}
/**
* Scan the ports to scan
* @param portString - the ports to scan (comma separated, hyphen denotes a range). For example:
* "21-23,25,45,53,80"
* @return this object to allow chaining
*/
public PortScan setPorts(String portString){
ports.clear();
ArrayList<Integer> ports = new ArrayList<>();
if (portString==null){
throw new IllegalArgumentException("Empty port string not allowed");
}
portString = portString.substring(portString.indexOf(":")+1, portString.length());
for (String x : portString.split(",")){
if (x.contains("-")){
int start = Integer.parseInt(x.split("-")[0]);
int end = Integer.parseInt(x.split("-")[1]);
validatePort(start);
validatePort(end);
if (end<=start) throw new IllegalArgumentException("Start port cannot be greater than or equal to the end port");
for (int j=start; j<=end;j++){
ports.add(j);
}
}
else{
int start = Integer.parseInt(x);
validatePort(start);
ports.add(start);
}
}
this.ports = ports;
return this;
}
/**
* Checks and throws exception if port is not valid
* @param port - the port to validate
*/
private void validatePort(int port){
if (port<1) throw new IllegalArgumentException("Start port cannot be less than 1");
if (port>65535) throw new IllegalArgumentException("Start cannot be greater than 65535");
}
/**
* Scan all privileged ports
* @return this object to allow chaining
*/
public PortScan setPortsPrivileged(){
ports.clear();
for (int i = 1; i < 1024; i++) {
ports.add(i);
}
return this;
}
/**
* Scan all ports
* @return this object to allow chaining
*/
public PortScan setPortsAll(){
ports.clear();
for (int i = 1; i < 65536; i++) {
ports.add(i);
}
return this;
}
private void setAddress(InetAddress address) {
this.address = address;
}
/**
* Cancel a running ping
*/
public void cancel() {
this.cancelled = true;
}
/**
* Perform a synchrnous port scan and return a list of open ports
* @return - ping result
*/
public ArrayList<Integer> doScan(){
cancelled = false;
ArrayList<Integer> openPorts = new ArrayList<>();
for (int portNo : ports) {
if (PortScanTCP.scanAddress(address, portNo, timeOutMillis)){
openPorts.add(portNo);
}
if (cancelled) break;
}
return openPorts;
}
/**
* Perform an asynchronous port scan
* @param portListener - the listener to fire portscan results to.
* @return - this object so we can cancel the scan if needed
*/
public PortScan doScan(final PortListener portListener){
new Thread(new Runnable() {
@Override
public void run() {
cancelled = false;
ArrayList<Integer> openPorts = new ArrayList<>();
for (int portNo : ports) {
boolean open = PortScanTCP.scanAddress(address, portNo, 1000);
if (portListener!=null){
portListener.onResult(portNo, open);
if (open) openPorts.add(portNo);
}
if (cancelled) break;
}
if (portListener!=null){
portListener.onFinished(openPorts);
}
}
}).start();
return this;
}
}
| library/src/main/java/com/stealthcopter/networktools/PortScan.java | package com.stealthcopter.networktools;
import android.support.annotation.NonNull;
import com.stealthcopter.networktools.portscanning.PortScanTCP;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Created by mat on 14/12/15.
*/
public class PortScan {
public interface PortListener{
void onResult(int portNo, boolean open);
void onFinished(ArrayList<Integer> openPorts);
}
private InetAddress address;
private int timeOutMillis = 1000;
private boolean cancelled = false;
private ArrayList<Integer> ports = new ArrayList<>();
/**
* Set the address to ping
* @param address - Address to be pinged
* @return this object to allow chaining
* @throws UnknownHostException
*/
public static PortScan onAddress(@NonNull String address) throws UnknownHostException {
PortScan portScan = new PortScan();
InetAddress ia = InetAddress.getByName(address);
portScan.setAddress(ia);
return portScan;
}
/**
* Set the address to ping
* @param ia - Address to be pinged
* @return this object to allow chaining
*/
public static PortScan onAddress(@NonNull InetAddress ia) {
PortScan portScan = new PortScan();
portScan.setAddress(ia);
return portScan;
}
/**
* Set the timeout
* @param timeOutMillis - the timeout for each ping in milliseconds
* @return this object to allow chaining
*/
public PortScan setTimeOutMillis(int timeOutMillis){
if (timeOutMillis<0) throw new IllegalArgumentException("Times cannot be less than 0");
this.timeOutMillis = timeOutMillis;
return this;
}
/**
* Scan the ports to scan
* @param port - the port to scan
* @return this object to allow chaining
*/
public PortScan setPort(int port){
ports.clear();
if (port<1) throw new IllegalArgumentException("Port cannot be less than 1");
else if (port>65535) throw new IllegalArgumentException("Port cannot be greater than 65535");
ports.add(port);
return this;
}
/**
* Scan the ports to scan
* @param ports - the ports to scan
* @return this object to allow chaining
*/
public PortScan setPorts(ArrayList<Integer> ports){
ports.clear();
// TODO: Validate / sanitize
this.ports = ports;
return this;
}
/**
* Scan the ports to scan
* @param portString - the ports to scan (comma separated, hyphen denotes a range). For example:
* "21-23,25,45,53,80"
* @return this object to allow chaining
*/
public PortScan setPorts(String portString){
ports.clear();
ArrayList<Integer> ports = new ArrayList<>();
if (portString==null){
throw new IllegalArgumentException("Empty port string not allowed");
}
portString = portString.substring(portString.indexOf(":")+1, portString.length());
for (String x : portString.split(",")){
if (x.contains("-")){
int start = Integer.parseInt(x.split("-")[0]);
int end = Integer.parseInt(x.split("-")[1]);
if (start<1) throw new IllegalArgumentException("Start port cannot be less than 1");
if (start>65535) throw new IllegalArgumentException("Start cannot be greater than 65535");
if (end>65535) throw new IllegalArgumentException("Start cannot be greater than 65535");
if (end<=start) throw new IllegalArgumentException("Start port cannot be greater than or equal to the end port");
for (int j=start; j<=end;j++){
ports.add(j);
}
}
else{
int start = Integer.parseInt(x);
if (start<1) throw new IllegalArgumentException("Start port cannot be less than 1");
if (start>65535) throw new IllegalArgumentException("Start cannot be greater than 65535");
ports.add(start);
}
}
this.ports = ports;
return this;
}
/**
* Scan all privileged ports
* @return this object to allow chaining
*/
public PortScan setPortsPrivileged(){
ports.clear();
for (int i = 1; i < 1024; i++) {
ports.add(i);
}
return this;
}
/**
* Scan all ports
* @return this object to allow chaining
*/
public PortScan setPortsAll(){
ports.clear();
for (int i = 1; i < 65535; i++) {
ports.add(i);
}
return this;
}
private void setAddress(InetAddress address) {
this.address = address;
}
/**
* Cancel a running ping
*/
public void cancel() {
this.cancelled = true;
}
/**
* Perform a synchrnous port scan and return a list of open ports
* @return - ping result
*/
public ArrayList<Integer> doScan(){
cancelled = false;
ArrayList<Integer> openPorts = new ArrayList<>();
for (int portNo : ports) {
if (PortScanTCP.scanAddress(address, portNo, timeOutMillis)){
openPorts.add(portNo);
}
if (cancelled) break;
}
return openPorts;
}
/**
* Perform an asynchronous port scan
* @param portListener - the listener to fire portscan results to.
* @return - this object so we can cancel the scan if needed
*/
public PortScan doScan(final PortListener portListener){
new Thread(new Runnable() {
@Override
public void run() {
cancelled = false;
ArrayList<Integer> openPorts = new ArrayList<>();
for (int portNo : ports) {
boolean open = PortScanTCP.scanAddress(address, portNo, 1000);
if (portListener!=null){
portListener.onResult(portNo, open);
if (open) openPorts.add(portNo);
}
if (cancelled) break;
}
if (portListener!=null){
portListener.onFinished(openPorts);
}
}
}).start();
return this;
}
}
| Fixed missing last port (65535) from a full scan.
Fixed broken setPorts(ArrayList<Integer> ports), clear was causing no ports to be scanned
Seperated validation into it's own method for tidyness
| library/src/main/java/com/stealthcopter/networktools/PortScan.java | Fixed missing last port (65535) from a full scan. Fixed broken setPorts(ArrayList<Integer> ports), clear was causing no ports to be scanned Seperated validation into it's own method for tidyness | <ide><path>ibrary/src/main/java/com/stealthcopter/networktools/PortScan.java
<ide> * Set the address to ping
<ide> * @param address - Address to be pinged
<ide> * @return this object to allow chaining
<del> * @throws UnknownHostException
<add> * @throws UnknownHostException - if no IP address for the
<add> * <code>host</code> could be found, or if a scope_id was specified
<add> * for a global IPv6 address.
<ide> */
<ide> public static PortScan onAddress(@NonNull String address) throws UnknownHostException {
<ide> PortScan portScan = new PortScan();
<ide> */
<ide> public PortScan setPort(int port){
<ide> ports.clear();
<del> if (port<1) throw new IllegalArgumentException("Port cannot be less than 1");
<del> else if (port>65535) throw new IllegalArgumentException("Port cannot be greater than 65535");
<add> validatePort(port);
<ide> ports.add(port);
<ide> return this;
<ide> }
<ide> * @return this object to allow chaining
<ide> */
<ide> public PortScan setPorts(ArrayList<Integer> ports){
<del> ports.clear();
<del> // TODO: Validate / sanitize
<add>
<add> // Check all ports are valid
<add> for(Integer port : ports){
<add> validatePort(port);
<add> }
<add>
<ide> this.ports = ports;
<ide>
<ide> return this;
<ide> if (x.contains("-")){
<ide> int start = Integer.parseInt(x.split("-")[0]);
<ide> int end = Integer.parseInt(x.split("-")[1]);
<del> if (start<1) throw new IllegalArgumentException("Start port cannot be less than 1");
<del> if (start>65535) throw new IllegalArgumentException("Start cannot be greater than 65535");
<del> if (end>65535) throw new IllegalArgumentException("Start cannot be greater than 65535");
<add> validatePort(start);
<add> validatePort(end);
<ide> if (end<=start) throw new IllegalArgumentException("Start port cannot be greater than or equal to the end port");
<ide>
<ide> for (int j=start; j<=end;j++){
<ide> }
<ide> else{
<ide> int start = Integer.parseInt(x);
<del> if (start<1) throw new IllegalArgumentException("Start port cannot be less than 1");
<del> if (start>65535) throw new IllegalArgumentException("Start cannot be greater than 65535");
<add> validatePort(start);
<ide> ports.add(start);
<ide> }
<ide> }
<ide> this.ports = ports;
<ide>
<ide> return this;
<add> }
<add>
<add> /**
<add> * Checks and throws exception if port is not valid
<add> * @param port - the port to validate
<add> */
<add> private void validatePort(int port){
<add> if (port<1) throw new IllegalArgumentException("Start port cannot be less than 1");
<add> if (port>65535) throw new IllegalArgumentException("Start cannot be greater than 65535");
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public PortScan setPortsAll(){
<ide> ports.clear();
<del> for (int i = 1; i < 65535; i++) {
<add> for (int i = 1; i < 65536; i++) {
<ide> ports.add(i);
<ide> }
<ide> return this; |
|
JavaScript | apache-2.0 | 69fe513cc9a57f4ac231db4bf64a358bd76f4d89 | 0 | mpouttuclarke/cdap,hsaputra/cdap,anthcp/cdap,mpouttuclarke/cdap,hsaputra/cdap,caskdata/cdap,chtyim/cdap,chtyim/cdap,chtyim/cdap,hsaputra/cdap,hsaputra/cdap,mpouttuclarke/cdap,chtyim/cdap,mpouttuclarke/cdap,caskdata/cdap,chtyim/cdap,caskdata/cdap,hsaputra/cdap,caskdata/cdap,anthcp/cdap,anthcp/cdap,caskdata/cdap,chtyim/cdap,anthcp/cdap,mpouttuclarke/cdap,anthcp/cdap,caskdata/cdap | var http = require('http'),
thrift = require('thrift'),
fs = require('fs'),
log4js = require('log4js');
/**
* Configure thrift.
*/
var AppFabricService = require('./thrift_bindings/AppFabricService.js'),
MetricsFrontendService = require('./thrift_bindings/MetricsFrontendService.js'),
MetadataService = require('./thrift_bindings/MetadataService.js');
var metadataservice_types = require('./thrift_bindings/metadataservice_types.js'),
metricsservice_types = require('./thrift_bindings/metricsservice_types.js'),
appfabricservice_types = require('./thrift_bindings/app-fabric_types.js');
var SubscriptionService;
var ttransport, tprotocol;
try {
ttransport = require('thrift/lib/thrift/transport');
} catch (e) {
ttransport = require('thrift/transport');
}
try {
tprotocol = require('thrift/lib/thrift/protocol');
} catch (e) {
tprotocol = require('thrift/protocol');
}
/**
* Configure logger.
*/
const LOG_LEVEL = 'TRACE';
log4js.configure({
appenders: [
{ type : 'console' }
]
});
var logger = process.logger = log4js.getLogger('Reactor UI API');
logger.setLevel(LOG_LEVEL);
/**
* Export API.
*/
(function () {
this.auth = null;
this.config = null;
this.configure = function (config) {
this.config = config;
};
this.metadata = function (accountID, method, params, done) {
params = params || [];
var conn = thrift.createConnection(
this.config['metadata.server.address'],
this.config['metadata.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
done('Could not connect to MetadataService.');
});
var MetaData = thrift.createClient(MetadataService, conn);
if (params.length === 2) {
var entityType = params.shift();
params[0] = new metadataservice_types[entityType](params[0]);
}
if (method.indexOf('ByApplication') !== -1 || method === 'getFlows' || method === 'getFlow' ||
method === 'getFlowsByStream' || method === 'getFlowsByDataset') {
params.unshift(accountID);
} else {
params.unshift(new metadataservice_types.Account({
id: accountID
}));
}
if (method in MetaData) {
try {
MetaData[method].apply(MetaData, params.concat(done));
} catch (e) {
done(e);
}
} else {
done('Unknown method for MetadataService: ' + method, null);
}
},
this.manager = function (accountID, method, params, done) {
params = params || [];
params.unshift(accountID);
var auth_token = new appfabricservice_types.AuthToken({ token: null });
var conn = thrift.createConnection(
this.config['resource.manager.server.address'],
this.config['resource.manager.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
done('Could not connect to FlowMonitor.');
});
var Manager = thrift.createClient(AppFabricService, conn);
var identifier = new appfabricservice_types.FlowIdentifier({
applicationId: params[1],
flowId: params[2],
version: params[3] ? parseInt(params[3], 10) : -1,
accountId: params[0],
type: appfabricservice_types.EntityType[params[4] || 'FLOW']
});
switch (method) {
case 'start':
identifier = new appfabricservice_types.FlowDescriptor({
identifier: new appfabricservice_types.FlowIdentifier({
applicationId: params[1],
flowId: params[2],
version: parseInt(params[3], 10),
accountId: accountID,
type: appfabricservice_types.EntityType[params[4] || 'FLOW']
}),
"arguments": []
});
Manager.start(auth_token, identifier, done);
break;
case 'stop':
Manager.stop(auth_token, identifier, done);
break;
case 'status':
Manager.status(auth_token, identifier, done);
break;
case 'getFlowDefinition':
Manager.getFlowDefinition(identifier, done);
break;
case 'getFlowHistory':
Manager.getFlowHistory(identifier, done);
break;
case 'setInstances':
var flowlet_id = params[4];
var instances = params[5];
var identifier = new appfabricservice_types.FlowIdentifier({
accountId: params[0],
applicationId: params[1],
flowId: params[2],
version: params[3] || -1
});
Manager.setInstances(auth_token, identifier, flowlet_id, instances, done);
break;
default:
if (method in Manager) {
try {
Manager[method].apply(Manager, params.concat(done));
} catch (e) {
done(e);
}
} else {
done('Unknown method for service Manager: ' + method, null);
}
}
conn.end();
};
this.far = function (accountID, method, params, done) {
var identifier, conn, FAR,
accountId = accountID,
auth_token = new appfabricservice_types.AuthToken({ token: null });
conn = thrift.createConnection(
this.config['resource.manager.server.address'],
this.config['resource.manager.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
done('Could not connect to AppFabricService');
});
FAR = thrift.createClient(AppFabricService, conn);
switch (method) {
case 'remove':
identifier = new appfabricservice_types.FlowIdentifier({
applicationId: params[0],
flowId: params[1],
version: params[2],
accountId: accountID
});
FAR.remove(auth_token, identifier, done);
break;
case 'promote':
identifier = new appfabricservice_types.FlowIdentifier({
applicationId: params[0],
flowId: params[1],
version: params[2],
accountId: accountID
});
FAR.promote(auth_token, identifier, done);
break;
case 'reset':
FAR.reset(auth_token, accountId, done);
break;
}
conn.end();
};
this.monitor = function (accountID, method, params, done) {
params = params || [];
var conn = thrift.createConnection(
this.config['flow.monitor.server.address'],
this.config['flow.monitor.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
done('Could not connect to FlowMonitor.');
});
conn.on('connect', function (response) {
var Monitor = thrift.createClient(MetricsFrontendService, conn);
switch (method) {
case 'getLog':
params.unshift(accountID);
Monitor.getLog.apply(Monitor, params.concat(done));
break;
case 'getCounters':
var flow = new metricsservice_types.FlowArgument({
accountId: (params[0] === '-' ? '-' : accountID),
applicationId: params[0],
flowId: params[1],
runId: params[2]
});
var names = params[3] || [];
var request = new metricsservice_types.CounterRequest({
argument: flow,
name: names
});
Monitor.getCounters(request, done);
break;
case 'getTimeSeries':
var level = params[5] || 'FLOW_LEVEL';
var flow = new metricsservice_types.FlowArgument({
accountId: (params[0] === '-' ? '-' : accountID),
applicationId: params[0],
flowId: params[1],
flowletId: params[6] || null
});
var request = new metricsservice_types.TimeseriesRequest({
argument: flow,
metrics: params[2],
level: metricsservice_types.MetricTimeseriesLevel[level],
startts: params[3]
});
Monitor.getTimeSeries(request, function (error, response) {
if (error) {
done(true, false);
return;
}
// Nukes timestamps since they're in Buffer format
for (var metric in response.points) {
var res = response.points[metric];
if (res) {
var j = res.length;
while(j--) {
res[j].timestamp = 0;
}
response.points[metric] = res;
}
}
done(error, response);
});
break;
}
conn.end();
});
};
this.gateway = function (apiKey, method, params, done) {
var post_data = params.payload || "";
var post_options = {};
switch (method) {
case 'inject':
post_options = {
host: this.config['gateway.hostname'],
port: this.config['gateway.port']
};
post_options.method = 'POST';
post_options.path = '/rest-stream' + (params.stream ? '/' + params.stream : '');
post_options.headers = {
'X-Continuuity-ApiKey': apiKey,
'Content-Length': post_data.length
};
break;
case 'query':
post_options = {
host: this.config['gateway.hostname'],
port: 10003
};
post_options.method = 'GET';
post_options.path = '/rest-query/' + params.service +
'/' + params.method + (params.query ? '?' + params.query : '');
break;
}
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
var data = [];
res.on('data', function (chunk) {
data.push(chunk);
});
res.on('end', function () {
data = data.join('');
done(res.statusCode !== 200 ? {
statusCode: res.statusCode,
response: data
} : false, {
statusCode: res.statusCode,
response: data
});
});
});
post_req.on('error', function (e) {
done(e, null);
});
if (method === 'inject') {
post_req.write(post_data);
}
post_req.end();
};
this.upload = function (accountID, req, res, file, socket) {
var self = this;
var auth_token = new appfabricservice_types.AuthToken({ token: null });
var length = req.header('Content-length');
var data = new Buffer(parseInt(length, 10));
var idx = 0;
req.on('data', function(raw) {
raw.copy(data, idx);
idx += raw.length;
});
req.on('end', function() {
console.log("Upload ended");
res.redirect('back');
res.end();
var conn = thrift.createConnection(
self.config['resource.manager.server.address'],
self.config['resource.manager.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
socket.emit('upload', {'error': 'Could not connect to AppFabricService'});
});
var FAR = thrift.createClient(AppFabricService, conn);
FAR.init(auth_token, new appfabricservice_types.ResourceInfo({
'accountId': accountID,
'applicationId': 'nil',
'filename': file,
'size': data.length,
'modtime': new Date().getTime()
}), function (error, resource_identifier) {
if (error) {
logger.warn('AppFabric Init', error);
} else {
socket.emit('upload', {'status': 'Initialized...', 'resource_identifier': resource_identifier});
var send_deploy = function () {
socket.emit('upload', {'status': 'Deploying...'});
FAR.deploy(auth_token, resource_identifier, function (error, result) {
if (error) {
logger.warn('FARManager deploy', error);
} else {
socket.emit('upload', {step: 0, 'status': 'Verifying...', result: arguments});
var current_status = -1;
var status_interval = setInterval(function () {
FAR.dstatus(auth_token, resource_identifier, function (error, result) {
if (error) {
logger.warn('FARManager verify', error);
} else {
if (current_status !== result.overall) {
socket.emit('upload', {'status': 'verifying', 'step': result.overall, 'message': result.message, 'flows': result.verification});
current_status = result.overall;
}
if (result.overall === 0 || // Not Found
result.overall === 4 || // Failed
result.overall === 5 || // Success
result.overall === 6 || // Undeployed
result.overall === 7) {
clearInterval(status_interval);
} // 1 (Registered), 2 (Uploading), 3 (Verifying)
}
});
}, 500);
}
});
};
var send_chunk = function (index, size) {
FAR.chunk(auth_token, resource_identifier, data.slice(index, index + size), function () {
if (error) {
socket.emit('Chunk error');
} else {
if (index + size === data.length) {
send_deploy();
} else {
var length = size;
if (index + (size * 2) > data.length) {
length = data.length % size;
}
send_chunk(index + size, length);
}
}
});
};
var CHUNK_SIZE = 102400;
send_chunk(0, CHUNK_SIZE > data.length ? data.length : CHUNK_SIZE);
}
});
});
};
}).call(exports);
| server/common/api.js | var http = require('http'),
thrift = require('thrift'),
fs = require('fs'),
log4js = require('log4js');
/**
* Configure thrift.
*/
var AppFabricService = require('./thrift_bindings/AppFabricService.js'),
MetricsFrontendService = require('./thrift_bindings/MetricsFrontendService.js'),
MetadataService = require('./thrift_bindings/MetadataService.js');
var metadataservice_types = require('./thrift_bindings/metadataservice_types.js'),
metricsservice_types = require('./thrift_bindings/metricsservice_types.js'),
appfabricservice_types = require('./thrift_bindings/app-fabric_types.js');
var SubscriptionService;
var ttransport, tprotocol;
try {
ttransport = require('thrift/lib/thrift/transport');
} catch (e) {
ttransport = require('thrift/transport');
}
try {
tprotocol = require('thrift/lib/thrift/protocol');
} catch (e) {
tprotocol = require('thrift/protocol');
}
/**
* Configure logger.
*/
const LOG_LEVEL = 'TRACE';
log4js.configure({
appenders: [
{ type : 'console' }
]
});
var logger = process.logger = log4js.getLogger('Reactor UI API');
logger.setLevel(LOG_LEVEL);
/**
* Export API.
*/
(function () {
this.auth = null;
this.config = null;
this.configure = function (config) {
this.config = config;
};
this.metadata = function (accountID, method, params, done) {
params = params || [];
var conn = thrift.createConnection(
this.config['metadata.server.address'],
this.config['metadata.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
done('Could not connect to MetadataService.');
});
var MetaData = thrift.createClient(MetadataService, conn);
if (params.length === 2) {
var entityType = params.shift();
params[0] = new metadataservice_types[entityType](params[0]);
}
if (method.indexOf('ByApplication') !== -1 || method === 'getFlows' || method === 'getFlow' ||
method === 'getFlowsByStream' || method === 'getFlowsByDataset') {
params.unshift(accountID);
} else {
params.unshift(new metadataservice_types.Account({
id: accountID
}));
}
if (method in MetaData) {
try {
MetaData[method].apply(MetaData, params.concat(done));
} catch (e) {
done(e);
}
} else {
done('Unknown method for MetadataService: ' + method, null);
}
},
this.manager = function (accountID, method, params, done) {
params = params || [];
params.unshift(accountID);
var auth_token = new appfabricservices_types.AuthToken({ token: null });
var conn = thrift.createConnection(
this.config['resource.manager.server.address'],
this.config['resource.manager.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
done('Could not connect to FlowMonitor.');
});
var Manager = thrift.createClient(AppFabricService, conn);
var identifier = new appfabricservice_types.FlowIdentifier({
applicationId: params[1],
flowId: params[2],
version: params[3] ? parseInt(params[3], 10) : -1,
accountId: params[0],
type: appfabricservice_types.EntityType[params[4] || 'FLOW']
});
switch (method) {
case 'start':
identifier = new appfabricservice_types.FlowDescriptor({
identifier: new appfabricservice_types.FlowIdentifier({
applicationId: params[1],
flowId: params[2],
version: parseInt(params[3], 10),
accountId: accountID,
type: appfabricservice_types.EntityType[params[4] || 'FLOW']
}),
"arguments": []
});
Manager.start(auth_token, identifier, done);
break;
case 'stop':
Manager.stop(auth_token, identifier, done);
break;
case 'status':
Manager.status(auth_token, identifier, done);
break;
case 'getFlowDefinition':
Manager.getFlowDefinition(identifier, done);
break;
case 'getFlowHistory':
Manager.getFlowHistory(identifier, done);
break;
case 'setInstances':
var flowlet_id = params[4];
var instances = params[5];
var identifier = new appfabricservice_types.FlowIdentifier({
accountId: params[0],
applicationId: params[1],
flowId: params[2],
version: params[3] || -1
});
Manager.setInstances(auth_token, identifier, flowlet_id, instances, done);
break;
default:
if (method in Manager) {
try {
Manager[method].apply(Manager, params.concat(done));
} catch (e) {
done(e);
}
} else {
done('Unknown method for service Manager: ' + method, null);
}
}
conn.end();
};
this.far = function (accountID, method, params, done) {
var identifier, conn, FAR,
accountId = accountID,
auth_token = new appfabricservice_types.AuthToken({ token: null });
conn = thrift.createConnection(
this.config['resource.manager.server.address'],
this.config['resource.manager.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
done('Could not connect to AppFabricService');
});
FAR = thrift.createClient(AppFabricService, conn);
switch (method) {
case 'remove':
identifier = new appfabricservice_types.FlowIdentifier({
applicationId: params[0],
flowId: params[1],
version: params[2],
accountId: accountID
});
FAR.remove(auth_token, identifier, done);
break;
case 'promote':
identifier = new appfabricservice_types.FlowIdentifier({
applicationId: params[0],
flowId: params[1],
version: params[2],
accountId: accountID
});
FAR.promote(auth_token, identifier, done);
break;
case 'reset':
FAR.reset(auth_token, accountId, done);
break;
}
conn.end();
};
this.monitor = function (accountID, method, params, done) {
params = params || [];
var conn = thrift.createConnection(
this.config['flow.monitor.server.address'],
this.config['flow.monitor.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
done('Could not connect to FlowMonitor.');
});
conn.on('connect', function (response) {
var Monitor = thrift.createClient(MetricsFrontendService, conn);
switch (method) {
case 'getLog':
params.unshift(accountID);
Monitor.getLog.apply(Monitor, params.concat(done));
break;
case 'getCounters':
var flow = new metricsservice_types.FlowArgument({
accountId: (params[0] === '-' ? '-' : accountID),
applicationId: params[0],
flowId: params[1],
runId: params[2]
});
var names = params[3] || [];
var request = new metricsservice_types.CounterRequest({
argument: flow,
name: names
});
Monitor.getCounters(request, done);
break;
case 'getTimeSeries':
var level = params[5] || 'FLOW_LEVEL';
var flow = new metricsservice_types.FlowArgument({
accountId: (params[0] === '-' ? '-' : accountID),
applicationId: params[0],
flowId: params[1],
flowletId: params[6] || null
});
var request = new metricsservice_types.TimeseriesRequest({
argument: flow,
metrics: params[2],
level: metricsservice_types.MetricTimeseriesLevel[level],
startts: params[3]
});
Monitor.getTimeSeries(request, function (error, response) {
if (error) {
done(true, false);
return;
}
// Nukes timestamps since they're in Buffer format
for (var metric in response.points) {
var res = response.points[metric];
if (res) {
var j = res.length;
while(j--) {
res[j].timestamp = 0;
}
response.points[metric] = res;
}
}
done(error, response);
});
break;
}
conn.end();
});
};
this.gateway = function (apiKey, method, params, done) {
var post_data = params.payload || "";
var post_options = {};
switch (method) {
case 'inject':
post_options = {
host: this.config['gateway.hostname'],
port: this.config['gateway.port']
};
post_options.method = 'POST';
post_options.path = '/rest-stream' + (params.stream ? '/' + params.stream : '');
post_options.headers = {
'X-Continuuity-ApiKey': apiKey,
'Content-Length': post_data.length
};
break;
case 'query':
post_options = {
host: this.config['gateway.hostname'],
port: 10003
};
post_options.method = 'GET';
post_options.path = '/rest-query/' + params.service +
'/' + params.method + (params.query ? '?' + params.query : '');
break;
}
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
var data = [];
res.on('data', function (chunk) {
data.push(chunk);
});
res.on('end', function () {
data = data.join('');
done(res.statusCode !== 200 ? {
statusCode: res.statusCode,
response: data
} : false, {
statusCode: res.statusCode,
response: data
});
});
});
post_req.on('error', function (e) {
done(e, null);
});
if (method === 'inject') {
post_req.write(post_data);
}
post_req.end();
};
this.upload = function (accountID, req, res, file, socket) {
var self = this;
var auth_token = new appfabricservice_types.AuthToken({ token: null });
var length = req.header('Content-length');
var data = new Buffer(parseInt(length, 10));
var idx = 0;
req.on('data', function(raw) {
raw.copy(data, idx);
idx += raw.length;
});
req.on('end', function() {
console.log("Upload ended");
res.redirect('back');
res.end();
var conn = thrift.createConnection(
self.config['resource.manager.server.address'],
self.config['resource.manager.server.port'], {
transport: ttransport.TFramedTransport,
protocol: tprotocol.TBinaryProtocol
});
conn.on('error', function (error) {
socket.emit('upload', {'error': 'Could not connect to AppFabricService'});
});
var FAR = thrift.createClient(AppFabricService, conn);
FAR.init(auth_token, new appfabricservice_types.ResourceInfo({
'accountId': accountID,
'applicationId': 'nil',
'filename': file,
'size': data.length,
'modtime': new Date().getTime()
}), function (error, resource_identifier) {
if (error) {
logger.warn('AppFabric Init', error);
} else {
socket.emit('upload', {'status': 'Initialized...', 'resource_identifier': resource_identifier});
var send_deploy = function () {
socket.emit('upload', {'status': 'Deploying...'});
FAR.deploy(auth_token, resource_identifier, function (error, result) {
if (error) {
logger.warn('FARManager deploy', error);
} else {
socket.emit('upload', {step: 0, 'status': 'Verifying...', result: arguments});
var current_status = -1;
var status_interval = setInterval(function () {
FAR.dstatus(auth_token, resource_identifier, function (error, result) {
if (error) {
logger.warn('FARManager verify', error);
} else {
if (current_status !== result.overall) {
socket.emit('upload', {'status': 'verifying', 'step': result.overall, 'message': result.message, 'flows': result.verification});
current_status = result.overall;
}
if (result.overall === 0 || // Not Found
result.overall === 4 || // Failed
result.overall === 5 || // Success
result.overall === 6 || // Undeployed
result.overall === 7) {
clearInterval(status_interval);
} // 1 (Registered), 2 (Uploading), 3 (Verifying)
}
});
}, 500);
}
});
};
var send_chunk = function (index, size) {
FAR.chunk(auth_token, resource_identifier, data.slice(index, index + size), function () {
if (error) {
socket.emit('Chunk error');
} else {
if (index + size === data.length) {
send_deploy();
} else {
var length = size;
if (index + (size * 2) > data.length) {
length = data.length % size;
}
send_chunk(index + size, length);
}
}
});
};
var CHUNK_SIZE = 102400;
send_chunk(0, CHUNK_SIZE > data.length ? data.length : CHUNK_SIZE);
}
});
});
};
}).call(exports);
| fixing a typo
| server/common/api.js | fixing a typo | <ide><path>erver/common/api.js
<ide> params = params || [];
<ide> params.unshift(accountID);
<ide>
<del> var auth_token = new appfabricservices_types.AuthToken({ token: null });
<add> var auth_token = new appfabricservice_types.AuthToken({ token: null });
<ide>
<ide> var conn = thrift.createConnection(
<ide> this.config['resource.manager.server.address'], |
|
Java | mit | 0e96ea0b4a1fec42a46cff33465fe31892c62977 | 0 | Siroring/projecteuler | package answers;
/**
* Created by seok on 2017. 2. 9..
*
* Problem 5
* 2520 is the smallest number that can be divided by each of the numbers
* from 1 to 10 without any remainder.
* What is the smallest positive number
* that is evenly divisible by all of the numbers from 1 to 20?
*/
public class Problem5 {
public static void main(String[] args) {
int result = 20;
boolean isAnswer = false;
while (!isAnswer) {
result++;
isAnswer = true;
for (int i = 2; i <= 20; i++) {
if (result % i != 0) {
isAnswer = false;
break;
}
}
}
System.out.println(result);
}
}
| answers/src/answers/Problem5.java | package answers;
/**
* Created by seok on 2017. 2. 9..
*
* Problem 5
* 2520 is the smallest number that can be divided by each of the numbers
* from 1 to 10 without any remainder.
* What is the smallest positive number
* that is evenly divisible by all of the numbers from 1 to 20?
*/
public class Problem5 {
public static void main(String[] args) {
int result = 20;
boolean isAnswer = false;
while (isAnswer == false) {
result++;
isAnswer = true;
for (int i = 1; i <= 20; i++) {
if (result % i != 0) {
isAnswer = false;
break;
}
}
}
System.out.println(result);
}
}
| problem 5 answers fix
- ==false -> !
- for sentence start point
| answers/src/answers/Problem5.java | problem 5 answers fix - ==false -> ! - for sentence start point | <ide><path>nswers/src/answers/Problem5.java
<ide> public static void main(String[] args) {
<ide> int result = 20;
<ide> boolean isAnswer = false;
<del> while (isAnswer == false) {
<add> while (!isAnswer) {
<ide> result++;
<ide> isAnswer = true;
<del> for (int i = 1; i <= 20; i++) {
<add> for (int i = 2; i <= 20; i++) {
<ide> if (result % i != 0) {
<ide> isAnswer = false;
<ide> break; |
|
Java | lgpl-2.1 | 2503ea81a9d644d3ac3c7988467185fb013dda00 | 0 | pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package org.xwiki.container.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.xwiki.component.embed.EmbeddableComponentManager;
import org.xwiki.component.internal.StackingComponentEventManager;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.container.ApplicationContextListenerManager;
import org.xwiki.container.Container;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.ApplicationStartedEvent;
import org.xwiki.observation.event.ApplicationStoppedEvent;
public class XWikiServletContextListener implements ServletContextListener
{
/**
* The component manager used to lookup for other components.
*/
private ComponentManager componentManager;
/**
* {@inheritDoc}
*
* @see ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent servletContextEvent)
{
// Initializes the Embeddable Component Manager
EmbeddableComponentManager ecm = new EmbeddableComponentManager();
ecm.initialize(this.getClass().getClassLoader());
this.componentManager = ecm;
// Use a Component Event Manager that stacks Component instance creation events till we tell it to flush them.
// The reason is that the Observation Manager used to send the events but we need the Application Context to
// be set up before we start sending events since there can be Observation Listener components that require
// the Application Context (this is the case for example for the Office Importer Lifecycle Listener).
StackingComponentEventManager eventManager = new StackingComponentEventManager();
ecm.setComponentEventManager(eventManager);
// Initializes XWiki's Container with the Servlet Context.
try {
ServletContainerInitializer containerInitializer =
this.componentManager.lookup(ServletContainerInitializer.class);
containerInitializer.initializeApplicationContext(servletContextEvent.getServletContext());
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to initialize the Application Context", e);
}
// Send an Observation event to signal the XWiki application is started. This allows components who need to do
// something on startup to do it.
ObservationManager observationManager;
try {
observationManager = this.componentManager.lookup(ObservationManager.class);
observationManager.notify(new ApplicationStartedEvent(), this);
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to find the Observation Manager component", e);
}
// Now that the Application Context is set up, send the Component instance creation events we had stacked up.
eventManager.setObservationManager(observationManager);
eventManager.shouldStack(false);
eventManager.flushEvents();
// This is a temporary bridge to allow non XWiki components to lookup XWiki components.
// We're putting the XWiki Component Manager instance in the Servlet Context so that it's
// available in the XWikiAction class which in turn puts it into the XWikiContext instance.
// Class that need to lookup then just need to get it from the XWikiContext instance.
// This is of course not necessary for XWiki components since they just need to implement
// the Composable interface to get access to the Component Manager or better they simply
// need to define the Components they require as field members and configure the Plexus
// deployment descriptors (components.xml) so that they are automatically injected.
servletContextEvent.getServletContext().setAttribute(
org.xwiki.component.manager.ComponentManager.class.getName(), this.componentManager);
}
/**
* {@inheritDoc}
*/
public void contextDestroyed(ServletContextEvent sce)
{
// Send an Observation event to signal the XWiki application is stopped. This allows components who need to do
// something on stop to do it.
try {
ObservationManager observationManager = this.componentManager.lookup(ObservationManager.class);
observationManager.notify(new ApplicationStoppedEvent(), this);
} catch (ComponentLookupException e) {
// Nothing to do here.
// TODO: Log a warning
}
try {
ApplicationContextListenerManager applicationContextListenerManager =
this.componentManager.lookup(ApplicationContextListenerManager.class);
Container container = this.componentManager.lookup(Container.class);
applicationContextListenerManager.destroyApplicationContext(container.getApplicationContext());
} catch (ComponentLookupException ex) {
// Nothing to do here.
// TODO: Log a warning
}
}
}
| xwiki-containers/xwiki-container-servlet/src/main/java/org/xwiki/container/servlet/XWikiServletContextListener.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package org.xwiki.container.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.xwiki.component.embed.EmbeddableComponentManager;
import org.xwiki.component.internal.StackingComponentEventManager;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.container.ApplicationContextListenerManager;
import org.xwiki.container.Container;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.ApplicationStartedEvent;
import org.xwiki.observation.event.ApplicationStoppedEvent;
public class XWikiServletContextListener implements ServletContextListener
{
/**
* The component manager used to lookup for other components.
*/
private ComponentManager componentManager;
/**
* {@inheritDoc}
*
* @see ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent servletContextEvent)
{
// Initializes the Embeddable Component Manager
EmbeddableComponentManager ecm = new EmbeddableComponentManager();
ecm.initialize(this.getClass().getClassLoader());
this.componentManager = ecm;
// Use a Component Event Manager that stacks Component instance creation events till we tell it to flush them.
// The reason is that the Observation Manager used to send the events is a component itself and we need the
// Application Context to be set up before we start sending events since there can be Observation Listener
// components that require the Application Context (this is the case for example for the Office Importer
// Lifecycle Listener).
StackingComponentEventManager eventManager = new StackingComponentEventManager();
ecm.setComponentEventManager(eventManager);
// Initializes XWiki's Container with the Servlet Context.
try {
ServletContainerInitializer containerInitializer =
this.componentManager.lookup(ServletContainerInitializer.class);
containerInitializer.initializeApplicationContext(servletContextEvent.getServletContext());
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to initialize the Application Context", e);
}
// Send an Observation event to signal the XWiki application is started. This allows components who need to do
// something on startup to do it.
ObservationManager observationManager;
try {
observationManager = this.componentManager.lookup(ObservationManager.class);
observationManager.notify(new ApplicationStartedEvent(), this);
} catch (ComponentLookupException e) {
throw new RuntimeException("Failed to find the Observation Manager component", e);
}
// Now that the Application Context is set up, send the Component instance creation events we had stacked up.
eventManager.setObservationManager(observationManager);
eventManager.shouldStack(false);
eventManager.flushEvents();
// This is a temporary bridge to allow non XWiki components to lookup XWiki components.
// We're putting the XWiki Component Manager instance in the Servlet Context so that it's
// available in the XWikiAction class which in turn puts it into the XWikiContext instance.
// Class that need to lookup then just need to get it from the XWikiContext instance.
// This is of course not necessary for XWiki components since they just need to implement
// the Composable interface to get access to the Component Manager or better they simply
// need to define the Components they require as field members and configure the Plexus
// deployment descriptors (components.xml) so that they are automatically injected.
servletContextEvent.getServletContext().setAttribute(
org.xwiki.component.manager.ComponentManager.class.getName(), this.componentManager);
}
/**
* {@inheritDoc}
*/
public void contextDestroyed(ServletContextEvent sce)
{
// Send an Observation event to signal the XWiki application is stopped. This allows components who need to do
// something on stop to do it.
try {
ObservationManager observationManager = this.componentManager.lookup(ObservationManager.class);
observationManager.notify(new ApplicationStoppedEvent(), this);
} catch (ComponentLookupException e) {
// Nothing to do here.
// TODO: Log a warning
}
try {
ApplicationContextListenerManager applicationContextListenerManager =
this.componentManager.lookup(ApplicationContextListenerManager.class);
Container container = this.componentManager.lookup(Container.class);
applicationContextListenerManager.destroyApplicationContext(container.getApplicationContext());
} catch (ComponentLookupException ex) {
// Nothing to do here.
// TODO: Log a warning
}
}
}
| Fixed doc typo
git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@25287 f329d543-caf0-0310-9063-dda96c69346f
| xwiki-containers/xwiki-container-servlet/src/main/java/org/xwiki/container/servlet/XWikiServletContextListener.java | Fixed doc typo | <ide><path>wiki-containers/xwiki-container-servlet/src/main/java/org/xwiki/container/servlet/XWikiServletContextListener.java
<ide> this.componentManager = ecm;
<ide>
<ide> // Use a Component Event Manager that stacks Component instance creation events till we tell it to flush them.
<del> // The reason is that the Observation Manager used to send the events is a component itself and we need the
<del> // Application Context to be set up before we start sending events since there can be Observation Listener
<del> // components that require the Application Context (this is the case for example for the Office Importer
<del> // Lifecycle Listener).
<add> // The reason is that the Observation Manager used to send the events but we need the Application Context to
<add> // be set up before we start sending events since there can be Observation Listener components that require
<add> // the Application Context (this is the case for example for the Office Importer Lifecycle Listener).
<ide> StackingComponentEventManager eventManager = new StackingComponentEventManager();
<ide> ecm.setComponentEventManager(eventManager);
<ide> |
|
JavaScript | bsd-2-clause | 0c7aa3b2aca79ffdcacd3d590068dba093a72b0e | 0 | hichameyessou/blip,tidepool-org/blip,hichameyessou/blip,hichameyessou/blip,tidepool-org/blip,tidepool-org/blip | /*
* == BSD2 LICENSE ==
* Copyright (c) 2014, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
var _ = require('lodash');
var bows = require('bows');
var d3 = window.d3;
var React = require('react');
var ReactDOM = require('react-dom');
var sundial = require('sundial');
var Header = require('./header');
var SubNav = require('./modalsubnav');
var Footer = require('./footer');
import SMBGTrends from './smbgtrends';
import * as viz from '@tidepool/viz';
const FocusedCBGSliceHTMLLabels = viz.components.FocusedCBGSliceHTMLLabels;
const FocusedCBGSliceTime = viz.components.FocusedCBGSliceTime;
const TrendsContainer = viz.containers.TrendsContainer;
var Modal = React.createClass({
chartType: 'modal',
log: bows('Modal Day'),
propTypes: {
bgPrefs: React.PropTypes.object.isRequired,
chartPrefs: React.PropTypes.object.isRequired,
currentPatientInViewId: React.PropTypes.string.isRequired,
timePrefs: React.PropTypes.object.isRequired,
initialDatetimeLocation: React.PropTypes.string,
patientData: React.PropTypes.object.isRequired,
trendsState: React.PropTypes.object.isRequired,
// refresh handler
onClickRefresh: React.PropTypes.func.isRequired,
onSwitchToBasics: React.PropTypes.func.isRequired,
onSwitchToDaily: React.PropTypes.func.isRequired,
onSwitchToModal: React.PropTypes.func.isRequired,
onSwitchToSettings: React.PropTypes.func.isRequired,
onSwitchToWeekly: React.PropTypes.func.isRequired,
trackMetric: React.PropTypes.func.isRequired,
updateChartPrefs: React.PropTypes.func.isRequired,
updateDatetimeLocation: React.PropTypes.func.isRequired,
uploadUrl: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
atMostRecent: true,
inTransition: false,
title: '',
visibleDays: 0
};
},
componentDidMount: function() {
if (this.refs.chart) {
// necessary to get a ref from the redux connect()ed TrendsContainer
this.chart = this.refs.chart.getWrappedInstance();
}
},
render: function() {
return (
<div id="tidelineMain">
{this.renderHeader()}
{this.renderSubNav()}
<div className="container-box-outer patient-data-content-outer">
<div className="container-box-inner patient-data-content-inner">
<div className="patient-data-content">
<div id="tidelineContainer" className="patient-data-chart-modal">
{this.renderChart()}
</div>
{this.renderFocusedCBGTime()}
{this.renderFocusedCBGHTMLLabels()}
</div>
</div>
</div>
<Footer
chartType={this.chartType}
onClickBoxOverlay={this.toggleBoxOverlay}
onClickGroup={this.toggleGroup}
onClickLines={this.toggleLines}
onClickRefresh={this.props.onClickRefresh}
onClickBgDataToggle={this.toggleBgDataSource}
boxOverlay={this.props.chartPrefs.modal.smbgRangeOverlay}
grouped={this.props.chartPrefs.modal.smbgGrouped}
showingLines={this.props.chartPrefs.modal.smbgLines}
showingCbg={this.props.chartPrefs.modal.showingCbg}
showingSmbg={this.props.chartPrefs.modal.showingSmbg}
ref="footer" />
</div>
);
},
renderHeader: function() {
return (
<Header
chartType={this.chartType}
inTransition={this.state.inTransition}
atMostRecent={this.state.atMostRecent}
title={this.state.title}
iconBack={'icon-back'}
iconNext={'icon-next'}
iconMostRecent={'icon-most-recent'}
onClickBack={this.handleClickBack}
onClickBasics={this.props.onSwitchToBasics}
onClickModal={this.handleClickModal}
onClickMostRecent={this.handleClickMostRecent}
onClickNext={this.handleClickForward}
onClickOneDay={this.handleClickDaily}
onClickTwoWeeks={this.handleClickWeekly}
onClickSettings={this.handleClickSettings}
ref="header" />
);
},
renderSubNav: function() {
return (
<SubNav
activeDays={this.props.chartPrefs.modal.activeDays}
activeDomain={this.props.chartPrefs.modal.activeDomain}
extentSize={this.props.chartPrefs.modal.extentSize}
domainClickHandlers={{
'1 week': this.handleClickOneWeek,
'2 weeks': this.handleClickTwoWeeks,
'4 weeks': this.handleClickFourWeeks
}}
onClickDay={this.toggleDay}
toggleWeekdays={this.toggleWeekdays}
toggleWeekends={this.toggleWeekends}
ref="subnav" />
);
},
renderChart: function() {
const { bgPrefs: { bgClasses, bgUnits } } = this.props;
let bgBounds = {
veryHighThreshold: bgClasses.high.boundary,
targetUpperBound: bgClasses.target.boundary,
targetLowerBound: bgClasses.low.boundary,
veryLowThreshold: bgClasses['very-low'].boundary,
};
return (
<TrendsContainer
activeDays={this.props.chartPrefs.modal.activeDays}
bgBounds={bgBounds}
bgClasses={this.props.bgPrefs.bgClasses}
bgUnits={this.props.bgPrefs.bgUnits}
currentPatientInViewId={this.props.currentPatientInViewId}
extentSize={this.props.chartPrefs.modal.extentSize}
initialDatetimeLocation={this.props.initialDatetimeLocation}
showingSmbg={this.props.chartPrefs.modal.showingSmbg}
showingCbg={this.props.chartPrefs.modal.showingCbg}
smbgRangeOverlay={this.props.chartPrefs.modal.smbgRangeOverlay}
smbgGrouped={this.props.chartPrefs.modal.smbgGrouped}
smbgLines={this.props.chartPrefs.modal.smbgLines}
smbgTrendsComponent={SMBGTrends}
timePrefs={this.props.timePrefs}
// data
cbgByDate={this.props.patientData.cbgByDate}
cbgByDayOfWeek={this.props.patientData.cbgByDayOfWeek}
smbgByDate={this.props.patientData.smbgByDate}
smbgByDayOfWeek={this.props.patientData.smbgByDayOfWeek}
// handlers
onDatetimeLocationChange={this.handleDatetimeLocationChange}
onSelectDay={this.handleSelectDay}
onSwitchBgDataSource={this.toggleBgDataSource}
ref="chart" />
);
},
renderFocusedCBGHTMLLabels: function() {
if (!this.props.chartPrefs.modal.showingCbg) {
return null;
}
const { currentPatientInViewId } = this.props;
return (
<FocusedCBGSliceHTMLLabels
bgUnits={this.props.bgPrefs.bgUnits}
focusedKeys={this.props.trendsState[currentPatientInViewId].focusedCbgSliceKeys}
focusedSlice={this.props.trendsState[currentPatientInViewId].focusedCbgSlice} />
);
},
renderFocusedCBGTime: function() {
if (!this.props.chartPrefs.modal.showingCbg) {
return null;
}
const { currentPatientInViewId } = this.props;
return (
<FocusedCBGSliceTime
focusedSlice={this.props.trendsState[currentPatientInViewId].focusedCbgSlice} />
);
},
renderMissingSMBGHeader: function() {
return (
<Header
chartType={this.chartType}
atMostRecent={this.state.atMostRecent}
inTransition={this.state.inTransition}
title={''}
onClickOneDay={this.handleClickDaily}
onClickSettings={this.handleClickSettings}
onClickTwoWeeks={this.handleClickWeekly}
ref="header" />
);
},
formatDate: function(datetime) {
var timePrefs = this.props.timePrefs, timezone;
if (!timePrefs.timezoneAware) {
timezone = 'UTC';
}
else {
timezone = timePrefs.timezoneName || 'UTC';
}
return sundial.formatInTimezone(datetime, timezone, 'MMM D, YYYY');
},
getTitle: function(datetimeLocationEndpoints) {
// endpoint is exclusive, so need to subtract a day
var end = d3.time.day.utc.offset(new Date(datetimeLocationEndpoints[1]), -1);
return this.formatDate(datetimeLocationEndpoints[0]) + ' - ' + this.formatDate(end);
},
getNewDomain: function(current, extent) {
var timePrefs = this.props.timePrefs, timezone;
if (!timePrefs.timezoneAware) {
timezone = 'UTC';
}
else {
timezone = timePrefs.timezoneName || 'UTC';
}
current = sundial.ceil(current, 'day', timezone);
return [d3.time.day.utc.offset(current, -extent).toISOString(), current.toISOString()];
},
updateVisibleDays: function() {
this.setState({
visibleDays: d3.select('#modalDays').selectAll('g.modalDay').size()
});
},
// handlers
handleClickBack: function(e) {
if (e) {
e.preventDefault();
}
this.chart.goBack();
},
handleClickForward: function(e) {
if (e) {
e.preventDefault();
}
if (this.state.atMostRecent) {
return;
}
this.chart.goForward();
},
handleClickMostRecent: function(e) {
if (e) {
e.preventDefault();
}
if (this.state.atMostRecent) {
return;
}
this.chart.goToMostRecent();
},
handleClickDaily: function(e) {
if (e) {
e.preventDefault();
}
var datetime = this.chart ? this.chart.getCurrentDay() : this.props.initialDatetimeLocation;
this.props.onSwitchToDaily(datetime);
},
handleClickModal: function(e) {
if (e) {
e.preventDefault();
}
// when you're on modal view, clicking modal does nothing
return;
},
handleClickOneWeek: function(e) {
if (e) {
e.preventDefault();
}
var prefs = _.cloneDeep(this.props.chartPrefs);
// no change, return early
if (prefs.activeDomain === '1 week' && prefs.extentSize === 7) {
return;
}
prefs.modal.activeDomain = '1 week';
prefs.modal.extentSize = 7;
this.props.updateChartPrefs(prefs);
var current = new Date(this.chart.getCurrentDay());
var newDomain = this.getNewDomain(current, 7);
this.chart.setExtent(newDomain);
},
handleClickTwoWeeks: function(e) {
if (e) {
e.preventDefault();
}
var prefs = _.cloneDeep(this.props.chartPrefs);
// no change, return early
if (prefs.activeDomain === '2 weeks' && prefs.extentSize === 14) {
return;
}
prefs.modal.activeDomain = '2 weeks';
prefs.modal.extentSize = 14;
this.props.updateChartPrefs(prefs);
var current = new Date(this.chart.getCurrentDay());
var newDomain = this.getNewDomain(current, 14);
this.chart.setExtent(newDomain);
},
handleClickFourWeeks: function(e) {
if (e) {
e.preventDefault();
}
var prefs = _.cloneDeep(this.props.chartPrefs);
// no change, return early
if (prefs.activeDomain === '4 weeks' && prefs.extentSize === 28) {
return;
}
prefs.modal.activeDomain = '4 weeks';
prefs.modal.extentSize = 28;
this.props.updateChartPrefs(prefs);
var current = new Date(this.chart.getCurrentDay());
var newDomain = this.getNewDomain(current, 28);
this.chart.setExtent(newDomain);
},
handleClickWeekly: function(e) {
if (e) {
e.preventDefault();
}
var datetime = this.chart ? this.chart.getCurrentDay() : this.props.initialDatetimeLocation;
this.props.onSwitchToWeekly(datetime);
},
handleClickSettings: function(e) {
if (e) {
e.preventDefault();
}
this.props.onSwitchToSettings();
},
handleDatetimeLocationChange: function(datetimeLocationEndpoints, atMostRecent) {
if (this.isMounted()) {
this.setState({
atMostRecent: atMostRecent,
title: this.getTitle(datetimeLocationEndpoints)
});
this.props.updateDatetimeLocation(datetimeLocationEndpoints[1]);
}
},
handleSelectDay: function(date) {
this.props.onSwitchToDaily(date);
},
toggleDay: function(day) {
var self = this;
return function(e) {
e.stopPropagation();
var prefs = _.cloneDeep(self.props.chartPrefs);
prefs.modal.activeDays[day] = prefs.modal.activeDays[day] ? false : true;
self.props.updateChartPrefs(prefs);
};
},
toggleBgDataSource: function(e) {
if (e) {
e.preventDefault();
}
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.showingCbg = !prefs.modal.showingCbg;
prefs.modal.showingSmbg = !prefs.modal.showingSmbg;
this.props.updateChartPrefs(prefs);
},
toggleBoxOverlay: function(e) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.smbgRangeOverlay = prefs.modal.smbgRangeOverlay ? false : true;
this.props.updateChartPrefs(prefs);
},
toggleGroup: function(e) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.smbgGrouped = prefs.modal.smbgGrouped ? false : true;
this.props.updateChartPrefs(prefs);
},
toggleLines: function(e) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.smbgLines = prefs.modal.smbgLines ? false : true;
this.props.updateChartPrefs(prefs);
},
toggleWeekdays: function(allActive) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.activeDays = {
'monday': !allActive,
'tuesday': !allActive,
'wednesday': !allActive,
'thursday': !allActive,
'friday': !allActive,
'saturday': prefs.modal.activeDays.saturday,
'sunday': prefs.modal.activeDays.sunday
};
this.props.updateChartPrefs(prefs);
},
toggleWeekends: function(allActive) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.activeDays = {
'monday': prefs.modal.activeDays.monday,
'tuesday': prefs.modal.activeDays.tuesday,
'wednesday': prefs.modal.activeDays.wednesday,
'thursday': prefs.modal.activeDays.thursday,
'friday': prefs.modal.activeDays.friday,
'saturday': !allActive,
'sunday': !allActive
};
this.props.updateChartPrefs(prefs);
}
});
module.exports = Modal; | app/components/chart/modal.js | /*
* == BSD2 LICENSE ==
* Copyright (c) 2014, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
var _ = require('lodash');
var bows = require('bows');
var d3 = window.d3;
var React = require('react');
var ReactDOM = require('react-dom');
var sundial = require('sundial');
var Header = require('./header');
var SubNav = require('./modalsubnav');
var Footer = require('./footer');
import SMBGTrends from './smbgtrends';
import * as viz from '@tidepool/viz';
const FocusedCBGSliceHTMLLabels = viz.components.FocusedCBGSliceHTMLLabels;
const FocusedCBGSliceTime = viz.components.FocusedCBGSliceTime;
const TrendsContainer = viz.containers.TrendsContainer;
var Modal = React.createClass({
chartType: 'modal',
log: bows('Modal Day'),
propTypes: {
bgPrefs: React.PropTypes.object.isRequired,
chartPrefs: React.PropTypes.object.isRequired,
currentPatientInViewId: React.PropTypes.string.isRequired,
timePrefs: React.PropTypes.object.isRequired,
initialDatetimeLocation: React.PropTypes.string,
patientData: React.PropTypes.object.isRequired,
trendsState: React.PropTypes.object.isRequired,
// refresh handler
onClickRefresh: React.PropTypes.func.isRequired,
onSwitchToBasics: React.PropTypes.func.isRequired,
onSwitchToDaily: React.PropTypes.func.isRequired,
onSwitchToModal: React.PropTypes.func.isRequired,
onSwitchToSettings: React.PropTypes.func.isRequired,
onSwitchToWeekly: React.PropTypes.func.isRequired,
trackMetric: React.PropTypes.func.isRequired,
updateChartPrefs: React.PropTypes.func.isRequired,
updateDatetimeLocation: React.PropTypes.func.isRequired,
uploadUrl: React.PropTypes.string.isRequired
},
getInitialState: function() {
return {
atMostRecent: true,
inTransition: false,
title: '',
visibleDays: 0
};
},
componentDidMount: function() {
if (this.refs.chart) {
// necessary to get a ref from the redux connect()ed TrendsContainer
this.chart = this.refs.chart.getWrappedInstance();
}
},
render: function() {
return (
<div id="tidelineMain">
{this.renderHeader()}
{this.renderSubNav()}
<div className="container-box-outer patient-data-content-outer">
<div className="container-box-inner patient-data-content-inner">
<div className="patient-data-content">
<div id="tidelineContainer" className="patient-data-chart-modal">
{this.renderChart()}
</div>
{this.renderFocusedCBGTime()}
{this.renderFocusedCBGHTMLLabels()}
</div>
</div>
</div>
<Footer
chartType={this.chartType}
onClickBoxOverlay={this.toggleBoxOverlay}
onClickGroup={this.toggleGroup}
onClickLines={this.toggleLines}
onClickRefresh={this.props.onClickRefresh}
onClickBgDataToggle={this.toggleBgDataSource}
boxOverlay={this.props.chartPrefs.modal.smbgRangeOverlay}
grouped={this.props.chartPrefs.modal.smbgGrouped}
showingLines={this.props.chartPrefs.modal.smbgLines}
showingCbg={this.props.chartPrefs.modal.showingCbg}
showingSmbg={this.props.chartPrefs.modal.showingSmbg}
ref="footer" />
</div>
);
},
renderHeader: function() {
return (
<Header
chartType={this.chartType}
inTransition={this.state.inTransition}
atMostRecent={this.state.atMostRecent}
title={this.state.title}
iconBack={'icon-back'}
iconNext={'icon-next'}
iconMostRecent={'icon-most-recent'}
onClickBack={this.handleClickBack}
onClickBasics={this.props.onSwitchToBasics}
onClickModal={this.handleClickModal}
onClickMostRecent={this.handleClickMostRecent}
onClickNext={this.handleClickForward}
onClickOneDay={this.handleClickDaily}
onClickTwoWeeks={this.handleClickWeekly}
onClickSettings={this.handleClickSettings}
ref="header" />
);
},
renderSubNav: function() {
return (
<SubNav
activeDays={this.props.chartPrefs.modal.activeDays}
activeDomain={this.props.chartPrefs.modal.activeDomain}
extentSize={this.props.chartPrefs.modal.extentSize}
domainClickHandlers={{
'1 week': this.handleClickOneWeek,
'2 weeks': this.handleClickTwoWeeks,
'4 weeks': this.handleClickFourWeeks
}}
onClickDay={this.toggleDay}
toggleWeekdays={this.toggleWeekdays}
toggleWeekends={this.toggleWeekends}
ref="subnav" />
);
},
renderChart: function() {
const { bgPrefs: { bgClasses, bgUnits } } = this.props;
let bgBounds = {
veryHighThreshold: bgClasses.high.boundary,
targetUpperBound: bgClasses.target.boundary,
targetLowerBound: bgClasses.low.boundary,
veryLowThreshold: bgClasses['very-low'].boundary,
};
return (
<TrendsContainer
activeDays={this.props.chartPrefs.modal.activeDays}
bgBounds={bgBounds}
bgClasses={this.props.bgPrefs.bgClasses}
bgUnits={this.props.bgPrefs.bgUnits}
currentPatientInViewId={this.props.currentPatientInViewId}
extentSize={this.props.chartPrefs.modal.extentSize}
initialDatetimeLocation={this.props.initialDatetimeLocation}
showingSmbg={this.props.chartPrefs.modal.showingSmbg}
showingCbg={this.props.chartPrefs.modal.showingCbg}
smbgRangeOverlay={this.props.chartPrefs.modal.smbgRangeOverlay}
smbgGrouped={this.props.chartPrefs.modal.smbgGrouped}
smbgLines={this.props.chartPrefs.modal.smbgLines}
smbgTrendsComponent={SMBGTrends}
timePrefs={this.props.timePrefs}
// data
cbgByDate={this.props.patientData.cbgByDate}
cbgByDayOfWeek={this.props.patientData.cbgByDayOfWeek}
smbgByDate={this.props.patientData.smbgByDate}
smbgByDayOfWeek={this.props.patientData.smbgByDayOfWeek}
// handlers
onDatetimeLocationChange={this.handleDatetimeLocationChange}
onSelectDay={this.handleSelectDay}
onSwitchBgDataSource={this.toggleBgDataSource}
ref="chart" />
);
},
renderFocusedCBGHTMLLabels: function() {
if (!this.props.chartPrefs.modal.showingCbg) {
return null;
}
return (
<FocusedCBGSliceHTMLLabels
bgUnits={this.props.bgPrefs.bgUnits}
focusedKeys={this.props.trendsState.focusedCbgSliceKeys}
focusedSlice={this.props.trendsState.focusedCbgSlice} />
);
},
renderFocusedCBGTime: function() {
if (!this.props.chartPrefs.modal.showingCbg) {
return null;
}
return (
<FocusedCBGSliceTime
focusedSlice={this.props.trendsState.focusedCbgSlice} />
);
},
renderMissingSMBGHeader: function() {
return (
<Header
chartType={this.chartType}
atMostRecent={this.state.atMostRecent}
inTransition={this.state.inTransition}
title={''}
onClickOneDay={this.handleClickDaily}
onClickSettings={this.handleClickSettings}
onClickTwoWeeks={this.handleClickWeekly}
ref="header" />
);
},
formatDate: function(datetime) {
var timePrefs = this.props.timePrefs, timezone;
if (!timePrefs.timezoneAware) {
timezone = 'UTC';
}
else {
timezone = timePrefs.timezoneName || 'UTC';
}
return sundial.formatInTimezone(datetime, timezone, 'MMM D, YYYY');
},
getTitle: function(datetimeLocationEndpoints) {
// endpoint is exclusive, so need to subtract a day
var end = d3.time.day.utc.offset(new Date(datetimeLocationEndpoints[1]), -1);
return this.formatDate(datetimeLocationEndpoints[0]) + ' - ' + this.formatDate(end);
},
getNewDomain: function(current, extent) {
var timePrefs = this.props.timePrefs, timezone;
if (!timePrefs.timezoneAware) {
timezone = 'UTC';
}
else {
timezone = timePrefs.timezoneName || 'UTC';
}
current = sundial.ceil(current, 'day', timezone);
return [d3.time.day.utc.offset(current, -extent).toISOString(), current.toISOString()];
},
updateVisibleDays: function() {
this.setState({
visibleDays: d3.select('#modalDays').selectAll('g.modalDay').size()
});
},
// handlers
handleClickBack: function(e) {
if (e) {
e.preventDefault();
}
this.chart.goBack();
},
handleClickForward: function(e) {
if (e) {
e.preventDefault();
}
if (this.state.atMostRecent) {
return;
}
this.chart.goForward();
},
handleClickMostRecent: function(e) {
if (e) {
e.preventDefault();
}
if (this.state.atMostRecent) {
return;
}
this.chart.goToMostRecent();
},
handleClickDaily: function(e) {
if (e) {
e.preventDefault();
}
var datetime = this.chart ? this.chart.getCurrentDay() : this.props.initialDatetimeLocation;
this.props.onSwitchToDaily(datetime);
},
handleClickModal: function(e) {
if (e) {
e.preventDefault();
}
// when you're on modal view, clicking modal does nothing
return;
},
handleClickOneWeek: function(e) {
if (e) {
e.preventDefault();
}
var prefs = _.cloneDeep(this.props.chartPrefs);
// no change, return early
if (prefs.activeDomain === '1 week' && prefs.extentSize === 7) {
return;
}
prefs.modal.activeDomain = '1 week';
prefs.modal.extentSize = 7;
this.props.updateChartPrefs(prefs);
var current = new Date(this.chart.getCurrentDay());
var newDomain = this.getNewDomain(current, 7);
this.chart.setExtent(newDomain);
},
handleClickTwoWeeks: function(e) {
if (e) {
e.preventDefault();
}
var prefs = _.cloneDeep(this.props.chartPrefs);
// no change, return early
if (prefs.activeDomain === '2 weeks' && prefs.extentSize === 14) {
return;
}
prefs.modal.activeDomain = '2 weeks';
prefs.modal.extentSize = 14;
this.props.updateChartPrefs(prefs);
var current = new Date(this.chart.getCurrentDay());
var newDomain = this.getNewDomain(current, 14);
this.chart.setExtent(newDomain);
},
handleClickFourWeeks: function(e) {
if (e) {
e.preventDefault();
}
var prefs = _.cloneDeep(this.props.chartPrefs);
// no change, return early
if (prefs.activeDomain === '4 weeks' && prefs.extentSize === 28) {
return;
}
prefs.modal.activeDomain = '4 weeks';
prefs.modal.extentSize = 28;
this.props.updateChartPrefs(prefs);
var current = new Date(this.chart.getCurrentDay());
var newDomain = this.getNewDomain(current, 28);
this.chart.setExtent(newDomain);
},
handleClickWeekly: function(e) {
if (e) {
e.preventDefault();
}
var datetime = this.chart ? this.chart.getCurrentDay() : this.props.initialDatetimeLocation;
this.props.onSwitchToWeekly(datetime);
},
handleClickSettings: function(e) {
if (e) {
e.preventDefault();
}
this.props.onSwitchToSettings();
},
handleDatetimeLocationChange: function(datetimeLocationEndpoints, atMostRecent) {
if (this.isMounted()) {
this.setState({
atMostRecent: atMostRecent,
title: this.getTitle(datetimeLocationEndpoints)
});
this.props.updateDatetimeLocation(datetimeLocationEndpoints[1]);
}
},
handleSelectDay: function(date) {
this.props.onSwitchToDaily(date);
},
toggleDay: function(day) {
var self = this;
return function(e) {
e.stopPropagation();
var prefs = _.cloneDeep(self.props.chartPrefs);
prefs.modal.activeDays[day] = prefs.modal.activeDays[day] ? false : true;
self.props.updateChartPrefs(prefs);
};
},
toggleBgDataSource: function(e) {
if (e) {
e.preventDefault();
}
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.showingCbg = !prefs.modal.showingCbg;
prefs.modal.showingSmbg = !prefs.modal.showingSmbg;
this.props.updateChartPrefs(prefs);
},
toggleBoxOverlay: function(e) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.smbgRangeOverlay = prefs.modal.smbgRangeOverlay ? false : true;
this.props.updateChartPrefs(prefs);
},
toggleGroup: function(e) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.smbgGrouped = prefs.modal.smbgGrouped ? false : true;
this.props.updateChartPrefs(prefs);
},
toggleLines: function(e) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.smbgLines = prefs.modal.smbgLines ? false : true;
this.props.updateChartPrefs(prefs);
},
toggleWeekdays: function(allActive) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.activeDays = {
'monday': !allActive,
'tuesday': !allActive,
'wednesday': !allActive,
'thursday': !allActive,
'friday': !allActive,
'saturday': prefs.modal.activeDays.saturday,
'sunday': prefs.modal.activeDays.sunday
};
this.props.updateChartPrefs(prefs);
},
toggleWeekends: function(allActive) {
var prefs = _.cloneDeep(this.props.chartPrefs);
prefs.modal.activeDays = {
'monday': prefs.modal.activeDays.monday,
'tuesday': prefs.modal.activeDays.tuesday,
'wednesday': prefs.modal.activeDays.wednesday,
'thursday': prefs.modal.activeDays.thursday,
'friday': prefs.modal.activeDays.friday,
'saturday': !allActive,
'sunday': !allActive
};
this.props.updateChartPrefs(prefs);
}
});
module.exports = Modal; | retrieve focusedSlice info via currentPatientInViewId
| app/components/chart/modal.js | retrieve focusedSlice info via currentPatientInViewId | <ide><path>pp/components/chart/modal.js
<ide> if (!this.props.chartPrefs.modal.showingCbg) {
<ide> return null;
<ide> }
<add> const { currentPatientInViewId } = this.props;
<ide> return (
<ide> <FocusedCBGSliceHTMLLabels
<ide> bgUnits={this.props.bgPrefs.bgUnits}
<del> focusedKeys={this.props.trendsState.focusedCbgSliceKeys}
<del> focusedSlice={this.props.trendsState.focusedCbgSlice} />
<add> focusedKeys={this.props.trendsState[currentPatientInViewId].focusedCbgSliceKeys}
<add> focusedSlice={this.props.trendsState[currentPatientInViewId].focusedCbgSlice} />
<ide> );
<ide> },
<ide> renderFocusedCBGTime: function() {
<ide> if (!this.props.chartPrefs.modal.showingCbg) {
<ide> return null;
<ide> }
<add> const { currentPatientInViewId } = this.props;
<ide> return (
<ide> <FocusedCBGSliceTime
<del> focusedSlice={this.props.trendsState.focusedCbgSlice} />
<add> focusedSlice={this.props.trendsState[currentPatientInViewId].focusedCbgSlice} />
<ide> );
<ide> },
<ide> renderMissingSMBGHeader: function() { |
|
Java | apache-2.0 | b7aa0fe70c8d6b77216c25502e29f135f48d7f83 | 0 | pradyutsarma/autosleep,Orange-OpenSource/autosleep,pradyutsarma/autosleep,pradyutsarma/autosleep,Orange-OpenSource/autosleep,Orange-OpenSource/autosleep | package org.cloudfoundry.autosleep.repositories;
import lombok.extern.slf4j.Slf4j;
import org.cloudfoundry.autosleep.config.Config;
import org.cloudfoundry.autosleep.repositories.ram.RamServiceRepository;
import org.cloudfoundry.autosleep.servicebroker.model.AutoSleepServiceInstance;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceDoesNotExistException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceRequest;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
@Slf4j
public class ServiceRepositoryTest {
private static final String ORG_TEST = "orgTest";
private static final String SPACE_TEST = "spaceTest";
private static final String SERVICE_DEFINITION_ID = "TESTS";
private static final String SERVICE_PLAN_ID = "PLAN";
private ServiceRepository dao;
private enum InsertedInstanceIds {
testInsertServiceFail, testGetServiceSuccess, testUpdateServiceSuccess,
testDeleteServiceByIdSuccess,
testDeleteServiceByInstanceSuccess,
testDeleteMass01,
testDeleteMass02,
testBinding
}
private CreateServiceInstanceRequest createRequestTemplate;
private long nbServicesInit;
/**
* Init DAO with test data.
*
* @throws ServiceInstanceDoesNotExistException when no correspondance in db
*/
@Before
public void populateDao() throws ServiceInstanceDoesNotExistException {
dao = new RamServiceRepository();
createRequestTemplate = new CreateServiceInstanceRequest(SERVICE_DEFINITION_ID, SERVICE_PLAN_ID, ORG_TEST, SPACE_TEST);
dao.deleteAll();
Arrays.asList(InsertedInstanceIds.values()).forEach(serviceInstanceId -> {
dao.save(new AutoSleepServiceInstance(createRequestTemplate.withServiceInstanceId(serviceInstanceId
.name())));
});
nbServicesInit = countServices();
}
@Test
public void testInsert() throws ServiceInstanceExistsException, ServiceBrokerException {
dao.save(new AutoSleepServiceInstance(createRequestTemplate.withServiceInstanceId("testInsertServiceSuccess")));
assertThat(countServices(), is(equalTo(nbServicesInit + 1)));
}
@Test
public void testMultipleInsertsAndRetrieves() throws ServiceInstanceExistsException, ServiceBrokerException {
List<String> ids = Arrays.asList("testInsertServiceSuccess1", "testInsertServiceSuccess2");
List<AutoSleepServiceInstance> initialList = new ArrayList<>();
ids.forEach(id -> initialList.add(new AutoSleepServiceInstance(createRequestTemplate.withServiceInstanceId
(id))));
//test save all
dao.save(initialList);
assertThat("Count should be equal to the initial amount plus inserted", countServices(), is(equalTo
(nbServicesInit + initialList.size())));
//test "exist"
ids.forEach(id -> assertThat("Each element should exist in DAO", dao.exists(id), is(true)));
//test that retrieving all elements give the same amount
Iterable<AutoSleepServiceInstance> storedElement = dao.findAll();
int count = 0;
for (AutoSleepServiceInstance object : storedElement) {
count++;
}
assertTrue("Retrieving all elements should return the same quantity", count == nbServicesInit + initialList
.size());
//test find with all inserted ids
storedElement = dao.findAll(ids);
for (AutoSleepServiceInstance object : storedElement) {
assertTrue("Retrieved element should be the same as initial element", initialList.contains(object));
}
}
@Test
public void testGetService() {
AutoSleepServiceInstance serviceInstance = dao.findOne(InsertedInstanceIds.testGetServiceSuccess.name());
assertFalse("Service should have been found", serviceInstance == null);
assertThat(serviceInstance.getServiceInstanceId(), is(
equalTo(InsertedInstanceIds.testGetServiceSuccess.name())));
assertThat(serviceInstance.getPlanId(), is(equalTo(createRequestTemplate.getPlanId())));
assertThat(serviceInstance.getServiceDefinitionId(),
is(equalTo(createRequestTemplate.getServiceDefinitionId())));
assertThat(serviceInstance.getOrganizationGuid(), is(equalTo(ORG_TEST)));
assertThat(serviceInstance.getSpaceGuid(), is(equalTo(SPACE_TEST)));
assertThat(serviceInstance.getInterval(), is(equalTo(Config.defaultInactivityPeriod)));
assertTrue("Succeed in getting a service that does not exist", dao.findOne("testGetServiceFail") == null);
}
@Test
public void testListServices() {
assertThat(countServices(), is(equalTo(nbServicesInit)));
}
@Test
public void testDelete() {
//wrong id shouldn't raise anything
dao.delete("testDeleteServiceFail");
//delete a service by id
dao.delete(InsertedInstanceIds.testDeleteServiceByIdSuccess.name());
assertThat(countServices(), is(equalTo(nbServicesInit - 1)));
//delete a service by name
dao.delete(dao.findOne(InsertedInstanceIds.testDeleteServiceByInstanceSuccess.name()));
assertThat(countServices(), is(equalTo(nbServicesInit - 2)));
//delete multiple services
Iterable<AutoSleepServiceInstance> services = dao.findAll(Arrays.asList(InsertedInstanceIds.testDeleteMass01
.name(), InsertedInstanceIds.testDeleteMass02.name()));
dao.delete(services);
assertThat(countServices(), is(equalTo(nbServicesInit - 4)));
//delete all services
dao.deleteAll();
assertTrue(countServices() == 0);
}
private long countServices() {
return dao.count();
}
} | src/test/java/org/cloudfoundry/autosleep/repositories/ServiceRepositoryTest.java | package org.cloudfoundry.autosleep.repositories;
import lombok.extern.slf4j.Slf4j;
import org.cloudfoundry.autosleep.config.Config;
import org.cloudfoundry.autosleep.repositories.ram.RamServiceRepository;
import org.cloudfoundry.autosleep.servicebroker.configuration.CatalogConfiguration;
import org.cloudfoundry.autosleep.servicebroker.model.AutoSleepServiceInstance;
import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceDoesNotExistException;
import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
import org.cloudfoundry.community.servicebroker.model.Catalog;
import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceRequest;
import org.cloudfoundry.community.servicebroker.model.ServiceDefinition;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@Slf4j
@ActiveProfiles("in-memory")
@ContextConfiguration(classes = {CatalogConfiguration.class, RamServiceRepository.class}) //TODO investigate
public class ServiceRepositoryTest {
private static final String ORG_TEST = "orgTest";
private static final String SPACE_TEST = "spaceTest";
private static final String APP_TEST = "appTest";
@Autowired
private Catalog catalog;
@Autowired
private ServiceRepository dao;
private enum InsertedInstanceIds {
testInsertServiceFail, testGetServiceSuccess, testUpdateServiceSuccess,
testDeleteServiceByIdSuccess,
testDeleteServiceByInstanceSuccess,
testDeleteMass01,
testDeleteMass02,
testBinding
}
private enum InsertedBindingIds {
testRemoveBindingSuccess
}
private final InsertedInstanceIds idForBindingTest = InsertedInstanceIds.testBinding;
private CreateServiceInstanceRequest createRequestTemplate;
private long nbServicesInit;
/**
* Init DAO with test data.
*
* @throws ServiceInstanceDoesNotExistException when no correspondance in db
*/
@Before
public void populateDao() throws ServiceInstanceDoesNotExistException {
assertTrue("Catalog must a least contain a catalog definition", catalog.getServiceDefinitions().size() > 0);
ServiceDefinition serviceDefinition = catalog.getServiceDefinitions().get(0);
assertTrue("Service definition " + serviceDefinition.getId() + " must at least contain a plan",
serviceDefinition.getPlans().size() > 0);
createRequestTemplate = new CreateServiceInstanceRequest(serviceDefinition.getId(), serviceDefinition
.getPlans().get(0).getId(), ORG_TEST, SPACE_TEST);
dao.deleteAll();
Arrays.asList(InsertedInstanceIds.values()).forEach(serviceInstanceId -> {
dao.save(new AutoSleepServiceInstance(createRequestTemplate.withServiceInstanceId(serviceInstanceId
.name())));
});
nbServicesInit = countServices();
}
@Test
public void testInsert() throws ServiceInstanceExistsException, ServiceBrokerException {
dao.save(new AutoSleepServiceInstance(createRequestTemplate.withServiceInstanceId("testInsertServiceSuccess")));
assertThat(countServices(), is(equalTo(nbServicesInit + 1)));
}
@Test
public void testMultipleInsertsAndRetrieves() throws ServiceInstanceExistsException, ServiceBrokerException {
List<String> ids = Arrays.asList("testInsertServiceSuccess1", "testInsertServiceSuccess2");
List<AutoSleepServiceInstance> initialList = new ArrayList<>();
ids.forEach(id -> initialList.add(new AutoSleepServiceInstance(createRequestTemplate.withServiceInstanceId
(id))));
//test save all
dao.save(initialList);
assertThat("Count should be equal to the initial amount plus inserted", countServices(), is(equalTo
(nbServicesInit + initialList.size())));
//test "exist"
ids.forEach(id -> assertThat("Each element should exist in DAO", dao.exists(id), is(true)));
//test that retrieving all elements give the same amount
Iterable<AutoSleepServiceInstance> storedElement = dao.findAll();
int count = 0;
for (AutoSleepServiceInstance object : storedElement) {
count++;
}
assertTrue("Retrieving all elements should return the same quantity", count == nbServicesInit + initialList
.size());
//test find with all inserted ids
storedElement = dao.findAll(ids);
for (AutoSleepServiceInstance object : storedElement) {
assertTrue("Retrieved element should be the same as initial element", initialList.contains(object));
}
}
@Test
public void testGetService() {
AutoSleepServiceInstance serviceInstance = dao.findOne(InsertedInstanceIds.testGetServiceSuccess.name());
assertFalse("Service should have been found", serviceInstance == null);
assertThat(serviceInstance.getServiceInstanceId(), is(
equalTo(InsertedInstanceIds.testGetServiceSuccess.name())));
assertThat(serviceInstance.getPlanId(), is(equalTo(createRequestTemplate.getPlanId())));
assertThat(serviceInstance.getServiceDefinitionId(),
is(equalTo(createRequestTemplate.getServiceDefinitionId())));
assertThat(serviceInstance.getOrganizationGuid(), is(equalTo(ORG_TEST)));
assertThat(serviceInstance.getSpaceGuid(), is(equalTo(SPACE_TEST)));
assertThat(serviceInstance.getInterval(), is(equalTo(Config.defaultInactivityPeriod)));
assertTrue("Succeed in getting a service that does not exist", dao.findOne("testGetServiceFail") == null);
}
@Test
public void testListServices() {
assertThat(countServices(), is(equalTo(nbServicesInit)));
}
@Test
public void testDelete() {
//wrong id shouldn't raise anything
dao.delete("testDeleteServiceFail");
//delete a service by id
dao.delete(InsertedInstanceIds.testDeleteServiceByIdSuccess.name());
assertThat(countServices(), is(equalTo(nbServicesInit - 1)));
//delete a service by name
dao.delete(dao.findOne(InsertedInstanceIds.testDeleteServiceByInstanceSuccess.name()));
assertThat(countServices(), is(equalTo(nbServicesInit - 2)));
//delete multiple services
Iterable<AutoSleepServiceInstance> services = dao.findAll(Arrays.asList(InsertedInstanceIds.testDeleteMass01
.name(), InsertedInstanceIds.testDeleteMass02.name()));
dao.delete(services);
assertThat(countServices(), is(equalTo(nbServicesInit - 4)));
//delete all services
dao.deleteAll();
assertTrue(countServices() == 0);
}
private long countServices() {
return dao.count();
}
} | remove Spring dependency in DAO test
| src/test/java/org/cloudfoundry/autosleep/repositories/ServiceRepositoryTest.java | remove Spring dependency in DAO test | <ide><path>rc/test/java/org/cloudfoundry/autosleep/repositories/ServiceRepositoryTest.java
<ide> import lombok.extern.slf4j.Slf4j;
<ide> import org.cloudfoundry.autosleep.config.Config;
<ide> import org.cloudfoundry.autosleep.repositories.ram.RamServiceRepository;
<del>import org.cloudfoundry.autosleep.servicebroker.configuration.CatalogConfiguration;
<ide> import org.cloudfoundry.autosleep.servicebroker.model.AutoSleepServiceInstance;
<ide> import org.cloudfoundry.community.servicebroker.exception.ServiceBrokerException;
<ide> import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceDoesNotExistException;
<ide> import org.cloudfoundry.community.servicebroker.exception.ServiceInstanceExistsException;
<del>import org.cloudfoundry.community.servicebroker.model.Catalog;
<ide> import org.cloudfoundry.community.servicebroker.model.CreateServiceInstanceRequest;
<del>import org.cloudfoundry.community.servicebroker.model.ServiceDefinition;
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<del>import org.junit.runner.RunWith;
<del>import org.springframework.beans.factory.annotation.Autowired;
<del>import org.springframework.test.context.ActiveProfiles;
<del>import org.springframework.test.context.ContextConfiguration;
<del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import static org.hamcrest.CoreMatchers.is;
<ide> import static org.junit.Assert.*;
<ide>
<del>@RunWith(SpringJUnit4ClassRunner.class)
<add>
<ide> @Slf4j
<del>@ActiveProfiles("in-memory")
<del>@ContextConfiguration(classes = {CatalogConfiguration.class, RamServiceRepository.class}) //TODO investigate
<add>
<ide> public class ServiceRepositoryTest {
<ide>
<ide> private static final String ORG_TEST = "orgTest";
<add> private static final String SPACE_TEST = "spaceTest";
<add> private static final String SERVICE_DEFINITION_ID = "TESTS";
<add> private static final String SERVICE_PLAN_ID = "PLAN";
<ide>
<del> private static final String SPACE_TEST = "spaceTest";
<del>
<del> private static final String APP_TEST = "appTest";
<del>
<del> @Autowired
<del> private Catalog catalog;
<del>
<del> @Autowired
<ide> private ServiceRepository dao;
<ide>
<ide> private enum InsertedInstanceIds {
<ide> testBinding
<ide> }
<ide>
<del> private enum InsertedBindingIds {
<del> testRemoveBindingSuccess
<del> }
<del>
<del> private final InsertedInstanceIds idForBindingTest = InsertedInstanceIds.testBinding;
<del>
<ide> private CreateServiceInstanceRequest createRequestTemplate;
<ide>
<ide> private long nbServicesInit;
<add>
<ide>
<ide>
<ide> /**
<ide> */
<ide> @Before
<ide> public void populateDao() throws ServiceInstanceDoesNotExistException {
<del> assertTrue("Catalog must a least contain a catalog definition", catalog.getServiceDefinitions().size() > 0);
<del> ServiceDefinition serviceDefinition = catalog.getServiceDefinitions().get(0);
<del> assertTrue("Service definition " + serviceDefinition.getId() + " must at least contain a plan",
<del> serviceDefinition.getPlans().size() > 0);
<del> createRequestTemplate = new CreateServiceInstanceRequest(serviceDefinition.getId(), serviceDefinition
<del> .getPlans().get(0).getId(), ORG_TEST, SPACE_TEST);
<del>
<add> dao = new RamServiceRepository();
<add> createRequestTemplate = new CreateServiceInstanceRequest(SERVICE_DEFINITION_ID, SERVICE_PLAN_ID, ORG_TEST, SPACE_TEST);
<ide>
<ide> dao.deleteAll();
<ide> |
|
Java | mit | 8cdb8a7c77a3c7dda01db5a3cf47aed1f969bfda | 0 | HungryAnt/yecai-web-server,HungryAnt/yecai-web-server,HungryAnt/yecai-web-server,HungryAnt/yecai-web-server | package com.antsoft.yecai.model;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Size;
/**
* Created by ant on 2015/10/18.
*/
public class UserLoginInfo {
@NotBlank
@Size(min = 3, max = 16)
private String loginName;
@NotBlank
@Size(min = 3, max = 20)
private String password;
private String sign;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
}
| src/main/java/com/antsoft/yecai/model/UserLoginInfo.java | package com.antsoft.yecai.model;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Size;
/**
* Created by ant on 2015/10/18.
*/
public class UserLoginInfo {
@NotBlank
@Size(min = 3, max = 12)
private String loginName;
@NotBlank
@Size(min = 3, max = 20)
private String password;
private String sign;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
}
| userInfo loginName validation bugfix
| src/main/java/com/antsoft/yecai/model/UserLoginInfo.java | userInfo loginName validation bugfix | <ide><path>rc/main/java/com/antsoft/yecai/model/UserLoginInfo.java
<ide> */
<ide> public class UserLoginInfo {
<ide> @NotBlank
<del> @Size(min = 3, max = 12)
<add> @Size(min = 3, max = 16)
<ide> private String loginName;
<ide>
<ide> @NotBlank |
|
Java | apache-2.0 | 1305e51817ca164eaa6fc601dcaaab23f0171e9e | 0 | apache/streams,apache/streams,apache/streams,jfrazee/incubator-streams | /*
* 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
*
* 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.
*/
package org.apache.streams.monitoring.persist.impl;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
public class BroadcastMessagePersisterTest {
@Test
public void testFailedPersist() {
BroadcastMessagePersister persister = new BroadcastMessagePersister("http://fake.url.noturldotcom.com/fake_endpointasdfasdf");
List<String> messages = new ArrayList<>();
for (int x = 0; x < 10; x++) {
messages.add("Fake_message #" + x);
}
int statusCode = persister.persistMessages(messages);
assertNotNull(statusCode);
assertNotEquals(statusCode, 200);
}
@Test
public void testInvalidUrl() {
BroadcastMessagePersister persister = new BroadcastMessagePersister("h");
List<String> messages = new ArrayList<>();
for (int x = 0; x < 10; x++) {
messages.add("Fake_message #" + x);
}
int statusCode = persister.persistMessages(messages);
assertNotNull(statusCode);
assertEquals(statusCode, -1);
}
}
| streams-monitoring/src/test/java/org/apache/streams/monitoring/persist/impl/BroadcastMessagePersisterTest.java | /*
* 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
*
* 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.
*/
package org.apache.streams.monitoring.persist.impl;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
public class BroadcastMessagePersisterTest {
@Test
public void testFailedPersist() {
BroadcastMessagePersister persister = new BroadcastMessagePersister("http://fake.url.com/fake_endpointasdfasdfas");
List<String> messages = new ArrayList<>();
for (int x = 0; x < 10; x++) {
messages.add("Fake_message #" + x);
}
int statusCode = persister.persistMessages(messages);
assertNotNull(statusCode);
assertNotEquals(statusCode, 200);
}
@Test
public void testInvalidUrl() {
BroadcastMessagePersister persister = new BroadcastMessagePersister("h");
List<String> messages = new ArrayList<>();
for (int x = 0; x < 10; x++) {
messages.add("Fake_message #" + x);
}
int statusCode = persister.persistMessages(messages);
assertNotNull(statusCode);
assertEquals(statusCode, -1);
}
}
| resolves STREAMS-607
| streams-monitoring/src/test/java/org/apache/streams/monitoring/persist/impl/BroadcastMessagePersisterTest.java | resolves STREAMS-607 | <ide><path>treams-monitoring/src/test/java/org/apache/streams/monitoring/persist/impl/BroadcastMessagePersisterTest.java
<ide>
<ide> @Test
<ide> public void testFailedPersist() {
<del> BroadcastMessagePersister persister = new BroadcastMessagePersister("http://fake.url.com/fake_endpointasdfasdfas");
<add> BroadcastMessagePersister persister = new BroadcastMessagePersister("http://fake.url.noturldotcom.com/fake_endpointasdfasdf");
<ide>
<ide> List<String> messages = new ArrayList<>();
<ide> for (int x = 0; x < 10; x++) { |
|
Java | apache-2.0 | 00f55f8e3bebf70de1d5497c40e0950b8bd6cbdd | 0 | charlesccychen/incubator-beam,rangadi/beam,chamikaramj/beam,markflyhigh/incubator-beam,RyanSkraba/beam,amarouni/incubator-beam,apache/beam,lukecwik/incubator-beam,vikkyrk/incubator-beam,rangadi/incubator-beam,staslev/beam,robertwb/incubator-beam,manuzhang/beam,manuzhang/beam,robertwb/incubator-beam,xsm110/Apache-Beam,lukecwik/incubator-beam,amitsela/beam,robertwb/incubator-beam,manuzhang/incubator-beam,chamikaramj/beam,staslev/beam,vikkyrk/incubator-beam,apache/beam,charlesccychen/beam,lukecwik/incubator-beam,tgroh/beam,xsm110/Apache-Beam,rangadi/beam,robertwb/incubator-beam,jbonofre/incubator-beam,sammcveety/incubator-beam,jbonofre/incubator-beam,sammcveety/incubator-beam,tgroh/beam,rangadi/beam,markflyhigh/incubator-beam,RyanSkraba/beam,lukecwik/incubator-beam,mxm/incubator-beam,apache/beam,wangyum/beam,dhalperi/beam,tgroh/beam,xsm110/Apache-Beam,rangadi/beam,yk5/beam,rangadi/incubator-beam,yk5/beam,amitsela/beam,wangyum/beam,markflyhigh/incubator-beam,charlesccychen/beam,peihe/incubator-beam,chamikaramj/beam,markflyhigh/incubator-beam,lukecwik/incubator-beam,amitsela/beam,manuzhang/incubator-beam,apache/beam,staslev/beam,charlesccychen/beam,RyanSkraba/beam,staslev/incubator-beam,amitsela/incubator-beam,lukecwik/incubator-beam,apache/beam,chamikaramj/beam,rangadi/beam,jbonofre/beam,RyanSkraba/beam,robertwb/incubator-beam,robertwb/incubator-beam,eljefe6a/incubator-beam,vikkyrk/incubator-beam,lukecwik/incubator-beam,wangyum/beam,chamikaramj/beam,dhalperi/incubator-beam,jbonofre/beam,tgroh/incubator-beam,apache/beam,apache/beam,chamikaramj/beam,tgroh/incubator-beam,RyanSkraba/beam,markflyhigh/incubator-beam,dhalperi/beam,robertwb/incubator-beam,markflyhigh/incubator-beam,rangadi/beam,markflyhigh/incubator-beam,apache/beam,rangadi/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,rangadi/beam,chamikaramj/beam,amitsela/incubator-beam,iemejia/incubator-beam,apache/beam,RyanSkraba/beam,charlesccychen/beam,tgroh/beam,lukecwik/incubator-beam,manuzhang/beam,robertwb/incubator-beam,apache/beam,charlesccychen/beam,apache/beam,wtanaka/beam,wangyum/beam,charlesccychen/incubator-beam,dhalperi/beam,peihe/incubator-beam,lukecwik/incubator-beam,charlesccychen/beam,iemejia/incubator-beam,robertwb/incubator-beam,wtanaka/beam,eljefe6a/incubator-beam,wtanaka/beam,chamikaramj/beam,yk5/beam,charlesccychen/beam,mxm/incubator-beam,amarouni/incubator-beam,charlesccychen/incubator-beam,chamikaramj/beam,peihe/incubator-beam,jbonofre/beam,robertwb/incubator-beam,RyanSkraba/beam,dhalperi/incubator-beam,jbonofre/beam,eljefe6a/incubator-beam,sammcveety/incubator-beam,staslev/incubator-beam | /*
* 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.
*/
package org.apache.beam.runners.core;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.CoderException;
import org.apache.beam.sdk.coders.ListCoder;
import org.apache.beam.sdk.coders.NullableCoder;
import org.apache.beam.sdk.coders.SerializableCoder;
import org.apache.beam.sdk.coders.StandardCoder;
import org.apache.beam.sdk.io.BoundedSource;
import org.apache.beam.sdk.io.BoundedSource.BoundedReader;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.io.UnboundedSource;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.display.DisplayData;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.util.NameUtils;
import org.apache.beam.sdk.util.PropertyNames;
import org.apache.beam.sdk.values.PBegin;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TimestampedValue;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link PTransform} that converts a {@link BoundedSource} as an {@link UnboundedSource}.
*
* <p>{@link BoundedSource} is read directly without calling {@link BoundedSource#splitIntoBundles},
* and element timestamps are propagated. While any elements remain, the watermark is the beginning
* of time {@link BoundedWindow#TIMESTAMP_MIN_VALUE}, and after all elements have been produced
* the watermark goes to the end of time {@link BoundedWindow#TIMESTAMP_MAX_VALUE}.
*
* <p>Checkpoints are created by calling {@link BoundedReader#splitAtFraction} on inner
* {@link BoundedSource}.
* Sources that cannot be split are read entirely into memory, so this transform does not work well
* with large, unsplittable sources.
*
* <p>This transform is intended to be used by a runner during pipeline translation to convert
* a Read.Bounded into a Read.Unbounded.
*/
public class UnboundedReadFromBoundedSource<T> extends PTransform<PBegin, PCollection<T>> {
private static final Logger LOG = LoggerFactory.getLogger(UnboundedReadFromBoundedSource.class);
private final BoundedSource<T> source;
/**
* Constructs a {@link PTransform} that performs an unbounded read from a {@link BoundedSource}.
*/
public UnboundedReadFromBoundedSource(BoundedSource<T> source) {
this.source = source;
}
@Override
public PCollection<T> expand(PBegin input) {
return input.getPipeline().apply(
Read.from(new BoundedToUnboundedSourceAdapter<>(source)));
}
@Override
protected Coder<T> getDefaultOutputCoder() {
return source.getDefaultOutputCoder();
}
@Override
public String getKindString() {
return String.format("Read(%s)", NameUtils.approximateSimpleName(source));
}
@Override
public void populateDisplayData(DisplayData.Builder builder) {
// We explicitly do not register base-class data, instead we use the delegate inner source.
builder
.add(DisplayData.item("source", source.getClass()))
.include("source", source);
}
/**
* A {@code BoundedSource} to {@code UnboundedSource} adapter.
*/
@VisibleForTesting
public static class BoundedToUnboundedSourceAdapter<T>
extends UnboundedSource<T, BoundedToUnboundedSourceAdapter.Checkpoint<T>> {
private BoundedSource<T> boundedSource;
public BoundedToUnboundedSourceAdapter(BoundedSource<T> boundedSource) {
this.boundedSource = boundedSource;
}
@Override
public void validate() {
boundedSource.validate();
}
@Override
public List<BoundedToUnboundedSourceAdapter<T>> generateInitialSplits(
int desiredNumSplits, PipelineOptions options) throws Exception {
try {
long desiredBundleSize = boundedSource.getEstimatedSizeBytes(options) / desiredNumSplits;
if (desiredBundleSize <= 0) {
LOG.warn("BoundedSource {} cannot estimate its size, skips the initial splits.",
boundedSource);
return ImmutableList.of(this);
}
List<? extends BoundedSource<T>> splits =
boundedSource.splitIntoBundles(desiredBundleSize, options);
if (splits == null) {
LOG.warn("BoundedSource cannot split {}, skips the initial splits.", boundedSource);
return ImmutableList.of(this);
}
return Lists.transform(
splits,
new Function<BoundedSource<T>, BoundedToUnboundedSourceAdapter<T>>() {
@Override
public BoundedToUnboundedSourceAdapter<T> apply(BoundedSource<T> input) {
return new BoundedToUnboundedSourceAdapter<>(input);
}});
} catch (Exception e) {
LOG.warn("Exception while splitting {}, skips the initial splits.", boundedSource, e);
return ImmutableList.of(this);
}
}
@Override
public Reader createReader(PipelineOptions options, Checkpoint<T> checkpoint)
throws IOException {
if (checkpoint == null) {
return new Reader(null /* residualElements */, boundedSource, options);
} else {
return new Reader(checkpoint.residualElements, checkpoint.residualSource, options);
}
}
@Override
public Coder<T> getDefaultOutputCoder() {
return boundedSource.getDefaultOutputCoder();
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Coder<Checkpoint<T>> getCheckpointMarkCoder() {
return new CheckpointCoder<>(boundedSource.getDefaultOutputCoder());
}
@VisibleForTesting
static class Checkpoint<T> implements UnboundedSource.CheckpointMark {
private final @Nullable List<TimestampedValue<T>> residualElements;
private final @Nullable BoundedSource<T> residualSource;
public Checkpoint(
@Nullable List<TimestampedValue<T>> residualElements,
@Nullable BoundedSource<T> residualSource) {
this.residualElements = residualElements;
this.residualSource = residualSource;
}
@Override
public void finalizeCheckpoint() {}
@VisibleForTesting
@Nullable List<TimestampedValue<T>> getResidualElements() {
return residualElements;
}
@VisibleForTesting
@Nullable BoundedSource<T> getResidualSource() {
return residualSource;
}
}
@VisibleForTesting
static class CheckpointCoder<T> extends StandardCoder<Checkpoint<T>> {
@JsonCreator
public static CheckpointCoder<?> of(
@JsonProperty(PropertyNames.COMPONENT_ENCODINGS)
List<Coder<?>> components) {
checkArgument(components.size() == 1,
"Expecting 1 components, got %s", components.size());
return new CheckpointCoder<>(components.get(0));
}
// The coder for a list of residual elements and their timestamps
private final Coder<List<TimestampedValue<T>>> elemsCoder;
// The coder from the BoundedReader for coding each element
private final Coder<T> elemCoder;
// The nullable and serializable coder for the BoundedSource.
@SuppressWarnings("rawtypes")
private final Coder<BoundedSource> sourceCoder;
CheckpointCoder(Coder<T> elemCoder) {
this.elemsCoder = NullableCoder.of(
ListCoder.of(TimestampedValue.TimestampedValueCoder.of(elemCoder)));
this.elemCoder = elemCoder;
this.sourceCoder = NullableCoder.of(SerializableCoder.of(BoundedSource.class));
}
@Override
public void encode(Checkpoint<T> value, OutputStream outStream, Context context)
throws CoderException, IOException {
elemsCoder.encode(value.residualElements, outStream, context.nested());
sourceCoder.encode(value.residualSource, outStream, context);
}
@SuppressWarnings("unchecked")
@Override
public Checkpoint<T> decode(InputStream inStream, Context context)
throws CoderException, IOException {
return new Checkpoint<>(
elemsCoder.decode(inStream, context.nested()),
sourceCoder.decode(inStream, context));
}
@Override
public List<Coder<?>> getCoderArguments() {
return Arrays.<Coder<?>>asList(elemCoder);
}
@Override
public void verifyDeterministic() throws NonDeterministicException {
throw new NonDeterministicException(this,
"CheckpointCoder uses Java Serialization, which may be non-deterministic.");
}
}
/**
* An {@code UnboundedReader<T>} that wraps a {@code BoundedSource<T>} into
* {@link ResidualElements} and {@link ResidualSource}.
*
* <p>In the initial state, {@link ResidualElements} is null and {@link ResidualSource} contains
* the {@code BoundedSource<T>}. After the first checkpoint, the {@code BoundedSource<T>} will
* be split into {@link ResidualElements} and {@link ResidualSource}.
*/
@VisibleForTesting
class Reader extends UnboundedReader<T> {
private ResidualElements residualElements;
private @Nullable ResidualSource residualSource;
private final PipelineOptions options;
private boolean done;
Reader(
@Nullable List<TimestampedValue<T>> residualElementsList,
@Nullable BoundedSource<T> residualSource,
PipelineOptions options) {
init(residualElementsList, residualSource, options);
this.options = checkNotNull(options, "options");
this.done = false;
}
private void init(
@Nullable List<TimestampedValue<T>> residualElementsList,
@Nullable BoundedSource<T> residualSource,
PipelineOptions options) {
this.residualElements = residualElementsList == null
? new ResidualElements(Collections.<TimestampedValue<T>>emptyList())
: new ResidualElements(residualElementsList);
this.residualSource =
residualSource == null ? null : new ResidualSource(residualSource, options);
}
@Override
public boolean start() throws IOException {
return advance();
}
@Override
public boolean advance() throws IOException {
if (residualElements.advance()) {
return true;
} else if (residualSource != null && residualSource.advance()) {
return true;
} else {
done = true;
return false;
}
}
@Override
public void close() throws IOException {
if (residualSource != null) {
residualSource.close();
}
}
@Override
public T getCurrent() throws NoSuchElementException {
if (residualElements.hasCurrent()) {
return residualElements.getCurrent();
} else if (residualSource != null) {
return residualSource.getCurrent();
} else {
throw new NoSuchElementException();
}
}
@Override
public Instant getCurrentTimestamp() throws NoSuchElementException {
if (residualElements.hasCurrent()) {
return residualElements.getCurrentTimestamp();
} else if (residualSource != null) {
return residualSource.getCurrentTimestamp();
} else {
throw new NoSuchElementException();
}
}
@Override
public Instant getWatermark() {
return done ? BoundedWindow.TIMESTAMP_MAX_VALUE : BoundedWindow.TIMESTAMP_MIN_VALUE;
}
/**
* {@inheritDoc}
*
* <p>If only part of the {@link ResidualElements} is consumed, the new
* checkpoint will contain the remaining elements in {@link ResidualElements} and
* the {@link ResidualSource}.
*
* <p>If all {@link ResidualElements} and part of the
* {@link ResidualSource} are consumed, the new checkpoint is done by splitting
* {@link ResidualSource} into new {@link ResidualElements} and {@link ResidualSource}.
* {@link ResidualSource} is the source split from the current source,
* and {@link ResidualElements} contains rest elements from the current source after
* the splitting. For unsplittable source, it will put all remaining elements into
* the {@link ResidualElements}.
*/
@Override
public Checkpoint<T> getCheckpointMark() {
Checkpoint<T> newCheckpoint;
if (!residualElements.done()) {
// Part of residualElements are consumed.
// Checkpoints the remaining elements and residualSource.
newCheckpoint = new Checkpoint<>(
residualElements.getRestElements(),
residualSource == null ? null : residualSource.getSource());
} else if (residualSource != null) {
newCheckpoint = residualSource.getCheckpointMark();
} else {
newCheckpoint = new Checkpoint<>(null /* residualElements */, null /* residualSource */);
}
// Re-initialize since the residualElements and the residualSource might be
// consumed or split by checkpointing.
init(newCheckpoint.residualElements, newCheckpoint.residualSource, options);
return newCheckpoint;
}
@Override
public BoundedToUnboundedSourceAdapter<T> getCurrentSource() {
return BoundedToUnboundedSourceAdapter.this;
}
}
private class ResidualElements {
private final List<TimestampedValue<T>> elementsList;
private @Nullable Iterator<TimestampedValue<T>> elementsIterator;
private @Nullable TimestampedValue<T> currentT;
private boolean hasCurrent;
private boolean done;
ResidualElements(List<TimestampedValue<T>> residualElementsList) {
this.elementsList = checkNotNull(residualElementsList, "residualElementsList");
this.elementsIterator = null;
this.currentT = null;
this.hasCurrent = false;
this.done = false;
}
public boolean advance() {
if (elementsIterator == null) {
elementsIterator = elementsList.iterator();
}
if (elementsIterator.hasNext()) {
currentT = elementsIterator.next();
hasCurrent = true;
return true;
} else {
done = true;
hasCurrent = false;
return false;
}
}
boolean hasCurrent() {
return hasCurrent;
}
boolean done() {
return done;
}
TimestampedValue<T> getCurrentTimestampedValue() {
if (!hasCurrent) {
throw new NoSuchElementException();
}
return currentT;
}
T getCurrent() {
return getCurrentTimestampedValue().getValue();
}
Instant getCurrentTimestamp() {
return getCurrentTimestampedValue().getTimestamp();
}
List<TimestampedValue<T>> getRestElements() {
if (elementsIterator == null) {
return elementsList;
} else {
List<TimestampedValue<T>> newResidualElements = Lists.newArrayList();
while (elementsIterator.hasNext()) {
newResidualElements.add(elementsIterator.next());
}
return newResidualElements;
}
}
}
private class ResidualSource {
private BoundedSource<T> residualSource;
private PipelineOptions options;
private @Nullable BoundedReader<T> reader;
private boolean closed;
private boolean readerDone;
public ResidualSource(BoundedSource<T> residualSource, PipelineOptions options) {
this.residualSource = checkNotNull(residualSource, "residualSource");
this.options = checkNotNull(options, "options");
this.reader = null;
this.closed = false;
this.readerDone = false;
}
private boolean advance() throws IOException {
checkArgument(!closed, "advance() call on closed %s", getClass().getName());
if (readerDone) {
return false;
}
if (reader == null) {
reader = residualSource.createReader(options);
readerDone = !reader.start();
} else {
readerDone = !reader.advance();
}
return !readerDone;
}
T getCurrent() throws NoSuchElementException {
if (reader == null) {
throw new NoSuchElementException();
}
return reader.getCurrent();
}
Instant getCurrentTimestamp() throws NoSuchElementException {
if (reader == null) {
throw new NoSuchElementException();
}
return reader.getCurrentTimestamp();
}
void close() throws IOException {
if (reader != null) {
reader.close();
reader = null;
}
closed = true;
}
BoundedSource<T> getSource() {
return residualSource;
}
Checkpoint<T> getCheckpointMark() {
if (reader == null) {
// Reader hasn't started, checkpoint the residualSource.
return new Checkpoint<>(null /* residualElements */, residualSource);
} else {
// Part of residualSource are consumed.
// Splits the residualSource and tracks the new residualElements in current source.
BoundedSource<T> residualSplit = null;
Double fractionConsumed = reader.getFractionConsumed();
if (fractionConsumed != null && 0 <= fractionConsumed && fractionConsumed <= 1) {
double fractionRest = 1 - fractionConsumed;
int splitAttempts = 8;
for (int i = 0; i < 8 && residualSplit == null; ++i) {
double fractionToSplit = fractionConsumed + fractionRest * i / splitAttempts;
residualSplit = reader.splitAtFraction(fractionToSplit);
}
}
List<TimestampedValue<T>> newResidualElements = Lists.newArrayList();
try {
while (advance()) {
newResidualElements.add(
TimestampedValue.of(reader.getCurrent(), reader.getCurrentTimestamp()));
}
} catch (IOException e) {
throw new RuntimeException("Failed to read elements from the bounded reader.", e);
}
return new Checkpoint<>(newResidualElements, residualSplit);
}
}
}
}
}
| runners/core-java/src/main/java/org/apache/beam/runners/core/UnboundedReadFromBoundedSource.java | /*
* 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.
*/
package org.apache.beam.runners.core;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.CoderException;
import org.apache.beam.sdk.coders.ListCoder;
import org.apache.beam.sdk.coders.NullableCoder;
import org.apache.beam.sdk.coders.SerializableCoder;
import org.apache.beam.sdk.coders.StandardCoder;
import org.apache.beam.sdk.io.BoundedSource;
import org.apache.beam.sdk.io.BoundedSource.BoundedReader;
import org.apache.beam.sdk.io.Read;
import org.apache.beam.sdk.io.UnboundedSource;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.display.DisplayData;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.util.NameUtils;
import org.apache.beam.sdk.util.PropertyNames;
import org.apache.beam.sdk.values.PBegin;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TimestampedValue;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link PTransform} that converts a {@link BoundedSource} as an {@link UnboundedSource}.
*
* <p>{@link BoundedSource} is read directly without calling {@link BoundedSource#splitIntoBundles},
* and element timestamps are propagated. While any elements remain, the watermark is the beginning
* of time {@link BoundedWindow#TIMESTAMP_MIN_VALUE}, and after all elements have been produced
* the watermark goes to the end of time {@link BoundedWindow#TIMESTAMP_MAX_VALUE}.
*
* <p>Checkpoints are created by calling {@link BoundedReader#splitAtFraction} on inner
* {@link BoundedSource}.
* Sources that cannot be split are read entirely into memory, so this transform does not work well
* with large, unsplittable sources.
*
* <p>This transform is intended to be used by a runner during pipeline translation to convert
* a Read.Bounded into a Read.Unbounded.
*/
public class UnboundedReadFromBoundedSource<T> extends PTransform<PBegin, PCollection<T>> {
private static final Logger LOG = LoggerFactory.getLogger(UnboundedReadFromBoundedSource.class);
private final BoundedSource<T> source;
/**
* Constructs a {@link PTransform} that performs an unbounded read from a {@link BoundedSource}.
*/
public UnboundedReadFromBoundedSource(BoundedSource<T> source) {
this.source = source;
}
@Override
public PCollection<T> expand(PBegin input) {
return input.getPipeline().apply(
Read.from(new BoundedToUnboundedSourceAdapter<>(source)));
}
@Override
protected Coder<T> getDefaultOutputCoder() {
return source.getDefaultOutputCoder();
}
@Override
public String getKindString() {
return String.format("Read(%s)", NameUtils.approximateSimpleName(source));
}
@Override
public void populateDisplayData(DisplayData.Builder builder) {
// We explicitly do not register base-class data, instead we use the delegate inner source.
builder
.add(DisplayData.item("source", source.getClass()))
.include("source", source);
}
/**
* A {@code BoundedSource} to {@code UnboundedSource} adapter.
*/
@VisibleForTesting
public static class BoundedToUnboundedSourceAdapter<T>
extends UnboundedSource<T, BoundedToUnboundedSourceAdapter.Checkpoint<T>> {
private BoundedSource<T> boundedSource;
public BoundedToUnboundedSourceAdapter(BoundedSource<T> boundedSource) {
this.boundedSource = boundedSource;
}
@Override
public void validate() {
boundedSource.validate();
}
@Override
public List<BoundedToUnboundedSourceAdapter<T>> generateInitialSplits(
int desiredNumSplits, PipelineOptions options) throws Exception {
try {
long desiredBundleSize = boundedSource.getEstimatedSizeBytes(options) / desiredNumSplits;
if (desiredBundleSize <= 0) {
LOG.warn("BoundedSource {} cannot estimate its size, skips the initial splits.",
boundedSource);
return ImmutableList.of(this);
}
List<? extends BoundedSource<T>> splits =
boundedSource.splitIntoBundles(desiredBundleSize, options);
if (splits == null) {
LOG.warn("BoundedSource cannot split {}, skips the initial splits.", boundedSource);
return ImmutableList.of(this);
}
return Lists.transform(
splits,
new Function<BoundedSource<T>, BoundedToUnboundedSourceAdapter<T>>() {
@Override
public BoundedToUnboundedSourceAdapter<T> apply(BoundedSource<T> input) {
return new BoundedToUnboundedSourceAdapter<>(input);
}});
} catch (Exception e) {
LOG.warn("Exception while splitting {}, skips the initial splits.", boundedSource, e);
return ImmutableList.of(this);
}
}
@Override
public Reader createReader(PipelineOptions options, Checkpoint<T> checkpoint)
throws IOException {
if (checkpoint == null) {
return new Reader(null /* residualElements */, boundedSource, options);
} else {
return new Reader(checkpoint.residualElements, checkpoint.residualSource, options);
}
}
@Override
public Coder<T> getDefaultOutputCoder() {
return boundedSource.getDefaultOutputCoder();
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Coder<Checkpoint<T>> getCheckpointMarkCoder() {
return new CheckpointCoder<>(boundedSource.getDefaultOutputCoder());
}
@VisibleForTesting
static class Checkpoint<T> implements UnboundedSource.CheckpointMark {
private final @Nullable List<TimestampedValue<T>> residualElements;
private final @Nullable BoundedSource<T> residualSource;
public Checkpoint(
@Nullable List<TimestampedValue<T>> residualElements,
@Nullable BoundedSource<T> residualSource) {
this.residualElements = residualElements;
this.residualSource = residualSource;
}
@Override
public void finalizeCheckpoint() {}
@VisibleForTesting
@Nullable List<TimestampedValue<T>> getResidualElements() {
return residualElements;
}
@VisibleForTesting
@Nullable BoundedSource<T> getResidualSource() {
return residualSource;
}
}
@VisibleForTesting
static class CheckpointCoder<T> extends StandardCoder<Checkpoint<T>> {
@JsonCreator
public static CheckpointCoder<?> of(
@JsonProperty(PropertyNames.COMPONENT_ENCODINGS)
List<Coder<?>> components) {
checkArgument(components.size() == 1,
"Expecting 1 components, got %s", components.size());
return new CheckpointCoder<>(components.get(0));
}
// The coder for a list of residual elements and their timestamps
private final Coder<List<TimestampedValue<T>>> elemsCoder;
// The coder from the BoundedReader for coding each element
private final Coder<T> elemCoder;
// The nullable and serializable coder for the BoundedSource.
@SuppressWarnings("rawtypes")
private final Coder<BoundedSource> sourceCoder;
CheckpointCoder(Coder<T> elemCoder) {
this.elemsCoder = NullableCoder.of(
ListCoder.of(TimestampedValue.TimestampedValueCoder.of(elemCoder)));
this.elemCoder = elemCoder;
this.sourceCoder = NullableCoder.of(SerializableCoder.of(BoundedSource.class));
}
@Override
public void encode(Checkpoint<T> value, OutputStream outStream, Context context)
throws CoderException, IOException {
elemsCoder.encode(value.residualElements, outStream, context.nested());
sourceCoder.encode(value.residualSource, outStream, context);
}
@SuppressWarnings("unchecked")
@Override
public Checkpoint<T> decode(InputStream inStream, Context context)
throws CoderException, IOException {
return new Checkpoint<>(
elemsCoder.decode(inStream, context.nested()),
sourceCoder.decode(inStream, context));
}
@Override
public List<Coder<?>> getCoderArguments() {
return Arrays.<Coder<?>>asList(elemCoder);
}
@Override
public void verifyDeterministic() throws NonDeterministicException {
throw new NonDeterministicException(this,
"CheckpointCoder uses Java Serialization, which may be non-deterministic.");
}
}
/**
* An {@code UnboundedReader<T>} that wraps a {@code BoundedSource<T>} into
* {@link ResidualElements} and {@link ResidualSource}.
*
* <p>In the initial state, {@link ResidualElements} is null and {@link ResidualSource} contains
* the {@code BoundedSource<T>}. After the first checkpoint, the {@code BoundedSource<T>} will
* be split into {@link ResidualElements} and {@link ResidualSource}.
*/
@VisibleForTesting
class Reader extends UnboundedReader<T> {
private ResidualElements residualElements;
private @Nullable ResidualSource residualSource;
private final PipelineOptions options;
private boolean done;
Reader(
@Nullable List<TimestampedValue<T>> residualElementsList,
@Nullable BoundedSource<T> residualSource,
PipelineOptions options) {
init(residualElementsList, residualSource, options);
this.options = checkNotNull(options, "options");
this.done = false;
}
private void init(
@Nullable List<TimestampedValue<T>> residualElementsList,
@Nullable BoundedSource<T> residualSource,
PipelineOptions options) {
this.residualElements = residualElementsList == null
? new ResidualElements(Collections.<TimestampedValue<T>>emptyList())
: new ResidualElements(residualElementsList);
this.residualSource =
residualSource == null ? null : new ResidualSource(residualSource, options);
}
@Override
public boolean start() throws IOException {
return advance();
}
@Override
public boolean advance() throws IOException {
if (residualElements.advance()) {
return true;
} else if (residualSource != null && residualSource.advance()) {
return true;
} else {
done = true;
return false;
}
}
@Override
public void close() throws IOException {
if (residualSource != null) {
residualSource.close();
}
}
@Override
public T getCurrent() throws NoSuchElementException {
if (residualElements.hasCurrent()) {
return residualElements.getCurrent();
} else if (residualSource != null) {
return residualSource.getCurrent();
} else {
throw new NoSuchElementException();
}
}
@Override
public Instant getCurrentTimestamp() throws NoSuchElementException {
if (residualElements.hasCurrent()) {
return residualElements.getCurrentTimestamp();
} else if (residualSource != null) {
return residualSource.getCurrentTimestamp();
} else {
throw new NoSuchElementException();
}
}
@Override
public Instant getWatermark() {
return done ? BoundedWindow.TIMESTAMP_MAX_VALUE : BoundedWindow.TIMESTAMP_MIN_VALUE;
}
/**
* {@inheritDoc}
*
* <p>If only part of the {@link ResidualElements} is consumed, the new
* checkpoint will contain the remaining elements in {@link ResidualElements} and
* the {@link ResidualSource}.
*
* <p>If all {@link ResidualElements} and part of the
* {@link ResidualSource} are consumed, the new checkpoint is done by splitting
* {@link ResidualSource} into new {@link ResidualElements} and {@link ResidualSource}.
* {@link ResidualSource} is the source split from the current source,
* and {@link ResidualElements} contains rest elements from the current source after
* the splitting. For unsplittable source, it will put all remaining elements into
* the {@link ResidualElements}.
*/
@Override
public Checkpoint<T> getCheckpointMark() {
Checkpoint<T> newCheckpoint;
if (!residualElements.done()) {
// Part of residualElements are consumed.
// Checkpoints the remaining elements and residualSource.
newCheckpoint = new Checkpoint<>(
residualElements.getRestElements(),
residualSource == null ? null : residualSource.getSource());
} else if (residualSource != null) {
newCheckpoint = residualSource.getCheckpointMark();
} else {
newCheckpoint = new Checkpoint<>(null /* residualElements */, null /* residualSource */);
}
// Re-initialize since the residualElements and the residualSource might be
// consumed or split by checkpointing.
init(newCheckpoint.residualElements, newCheckpoint.residualSource, options);
return newCheckpoint;
}
@Override
public BoundedToUnboundedSourceAdapter<T> getCurrentSource() {
return BoundedToUnboundedSourceAdapter.this;
}
}
private class ResidualElements {
private final List<TimestampedValue<T>> elementsList;
private @Nullable Iterator<TimestampedValue<T>> elementsIterator;
private @Nullable TimestampedValue<T> currentT;
private boolean hasCurrent;
private boolean done;
ResidualElements(List<TimestampedValue<T>> residualElementsList) {
this.elementsList = checkNotNull(residualElementsList, "residualElementsList");
this.elementsIterator = null;
this.currentT = null;
this.hasCurrent = false;
this.done = false;
}
public boolean advance() {
if (elementsIterator == null) {
elementsIterator = elementsList.iterator();
}
if (elementsIterator.hasNext()) {
currentT = elementsIterator.next();
hasCurrent = true;
return true;
} else {
done = true;
hasCurrent = false;
return false;
}
}
boolean hasCurrent() {
return hasCurrent;
}
boolean done() {
return done;
}
TimestampedValue<T> getCurrentTimestampedValue() {
if (!hasCurrent) {
throw new NoSuchElementException();
}
return currentT;
}
T getCurrent() {
return getCurrentTimestampedValue().getValue();
}
Instant getCurrentTimestamp() {
return getCurrentTimestampedValue().getTimestamp();
}
List<TimestampedValue<T>> getRestElements() {
if (elementsIterator == null) {
return elementsList;
} else {
List<TimestampedValue<T>> newResidualElements = Lists.newArrayList();
while (elementsIterator.hasNext()) {
newResidualElements.add(elementsIterator.next());
}
return newResidualElements;
}
}
}
private class ResidualSource {
private BoundedSource<T> residualSource;
private PipelineOptions options;
private @Nullable BoundedReader<T> reader;
private boolean closed;
public ResidualSource(BoundedSource<T> residualSource, PipelineOptions options) {
this.residualSource = checkNotNull(residualSource, "residualSource");
this.options = checkNotNull(options, "options");
this.reader = null;
this.closed = false;
}
private boolean advance() throws IOException {
checkArgument(!closed, "advance() call on closed %s", getClass().getName());
if (reader == null) {
reader = residualSource.createReader(options);
return reader.start();
} else {
return reader.advance();
}
}
T getCurrent() throws NoSuchElementException {
if (reader == null) {
throw new NoSuchElementException();
}
return reader.getCurrent();
}
Instant getCurrentTimestamp() throws NoSuchElementException {
if (reader == null) {
throw new NoSuchElementException();
}
return reader.getCurrentTimestamp();
}
void close() throws IOException {
if (reader != null) {
reader.close();
reader = null;
}
closed = true;
}
BoundedSource<T> getSource() {
return residualSource;
}
Checkpoint<T> getCheckpointMark() {
if (reader == null) {
// Reader hasn't started, checkpoint the residualSource.
return new Checkpoint<>(null /* residualElements */, residualSource);
} else {
// Part of residualSource are consumed.
// Splits the residualSource and tracks the new residualElements in current source.
BoundedSource<T> residualSplit = null;
Double fractionConsumed = reader.getFractionConsumed();
if (fractionConsumed != null && 0 <= fractionConsumed && fractionConsumed <= 1) {
double fractionRest = 1 - fractionConsumed;
int splitAttempts = 8;
for (int i = 0; i < 8 && residualSplit == null; ++i) {
double fractionToSplit = fractionConsumed + fractionRest * i / splitAttempts;
residualSplit = reader.splitAtFraction(fractionToSplit);
}
}
List<TimestampedValue<T>> newResidualElements = Lists.newArrayList();
try {
while (advance()) {
newResidualElements.add(
TimestampedValue.of(reader.getCurrent(), reader.getCurrentTimestamp()));
}
} catch (IOException e) {
throw new RuntimeException("Failed to read elements from the bounded reader.", e);
}
return new Checkpoint<>(newResidualElements, residualSplit);
}
}
}
}
}
| Do not call advance when all elements are consumed
This prevents UnboundedReadFromBoundedSource from attempting to read
elements from a reader where elements are known to not exist. This
defends against bounded readers which expect to be discarded the first
time they return false from advance().
| runners/core-java/src/main/java/org/apache/beam/runners/core/UnboundedReadFromBoundedSource.java | Do not call advance when all elements are consumed | <ide><path>unners/core-java/src/main/java/org/apache/beam/runners/core/UnboundedReadFromBoundedSource.java
<ide> private PipelineOptions options;
<ide> private @Nullable BoundedReader<T> reader;
<ide> private boolean closed;
<add> private boolean readerDone;
<ide>
<ide> public ResidualSource(BoundedSource<T> residualSource, PipelineOptions options) {
<ide> this.residualSource = checkNotNull(residualSource, "residualSource");
<ide> this.options = checkNotNull(options, "options");
<ide> this.reader = null;
<ide> this.closed = false;
<add> this.readerDone = false;
<ide> }
<ide>
<ide> private boolean advance() throws IOException {
<ide> checkArgument(!closed, "advance() call on closed %s", getClass().getName());
<add> if (readerDone) {
<add> return false;
<add> }
<ide> if (reader == null) {
<ide> reader = residualSource.createReader(options);
<del> return reader.start();
<del> } else {
<del> return reader.advance();
<del> }
<add> readerDone = !reader.start();
<add> } else {
<add> readerDone = !reader.advance();
<add> }
<add> return !readerDone;
<ide> }
<ide>
<ide> T getCurrent() throws NoSuchElementException { |
|
Java | apache-2.0 | error: pathspec 'src/main/packagefolder/Div.java' did not match any file(s) known to git
| 2546cee27ff25954d0d4e243c633f9f256c1266f | 1 | Kivitoe/Turtle-Calculator | package main.packagefolder;
import java.awt.EventQueue;
import javax.swing.JFrame;
import folder.contains.New.methoids.*;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.Format;
import java.awt.event.ActionEvent;
import javax.swing.JFormattedTextField;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Toolkit;
public class Div {
private JFrame frmTurtleCalculator;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Div window = new Div();
window.frmTurtleCalculator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Div() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
frmTurtleCalculator = new JFrame();
frmTurtleCalculator.setIconImage(Toolkit.getDefaultToolkit().getImage(Div.class.getResource("/com/sun/javafx/scene/control/skin/modena/HTMLEditor-Break.png")));
frmTurtleCalculator.setResizable(false);
frmTurtleCalculator.setTitle("Turtle Calculator");
frmTurtleCalculator.setBounds(100, 100, 376, 202);
frmTurtleCalculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//TODO Main
textField = new JTextField();
textField.setColumns(10);
JLabel lblTypeInThe = new JLabel("Type in the numbers in the following text boxes:");
JLabel label = new JLabel("/");
textField_1 = new JTextField();
textField_1.setColumns(10);
JLabel label_1 = new JLabel("=");
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JLabel lblErrorNoNumbers = new JLabel("Error: Incorrect character/no numbers found!");
lblErrorNoNumbers.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblErrorNoNumbers.setForeground(Color.RED);
lblErrorNoNumbers.setVisible(false);
JButton btnAdd = new JButton("Divide");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
String hi2 = textField.getText();
String hi1 = textField_1.getText();
double x = Double.parseDouble(hi1);
double o = Double.parseDouble(hi2);
double p = o - x;
String hi4 = "" + p;
textField_2.setText(hi4);
} catch(Exception i){
i.printStackTrace();
lblErrorNoNumbers.setVisible(true);
}
}
});
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_2.setColumns(10);
//TODO Group layout
GroupLayout groupLayout = new GroupLayout(frmTurtleCalculator.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblTypeInThe)
.addGroup(groupLayout.createSequentialGroup()
.addGap(14)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(label)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField_1, 107, 107, 107)))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(label_1)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField_2, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnCancel)
.addPreferredGap(ComponentPlacement.RELATED, 236, Short.MAX_VALUE)
.addComponent(btnAdd))
.addComponent(lblErrorNoNumbers))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblTypeInThe)
.addGap(18)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(label)
.addComponent(label_1)
.addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
.addComponent(lblErrorNoNumbers)
.addGap(18)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnCancel)
.addComponent(btnAdd))
.addContainerGap())
);
frmTurtleCalculator.getContentPane().setLayout(groupLayout);
//TODO Menu Bar
JMenuBar menuBar = new JMenuBar();
frmTurtleCalculator.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmClearHistory = new JMenuItem("Clear History");
mntmClearHistory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
mnFile.add(mntmClearHistory);
mnFile.addSeparator();
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
mnFile.add(mntmExit);
}
}
| src/main/packagefolder/Div.java | Divide Part | src/main/packagefolder/Div.java | Divide Part | <ide><path>rc/main/packagefolder/Div.java
<add>package main.packagefolder;
<add>
<add>import java.awt.EventQueue;
<add>
<add>import javax.swing.JFrame;
<add>import folder.contains.New.methoids.*;
<add>import javax.swing.GroupLayout;
<add>import javax.swing.GroupLayout.Alignment;
<add>import javax.swing.JLabel;
<add>import javax.swing.JTextField;
<add>import javax.swing.LayoutStyle.ComponentPlacement;
<add>import javax.swing.UIManager;
<add>import javax.swing.UnsupportedLookAndFeelException;
<add>import javax.swing.JButton;
<add>import java.awt.event.ActionListener;
<add>import java.io.IOException;
<add>import java.net.MalformedURLException;
<add>import java.net.URI;
<add>import java.net.URISyntaxException;
<add>import java.net.URL;
<add>import java.text.Format;
<add>import java.awt.event.ActionEvent;
<add>import javax.swing.JFormattedTextField;
<add>import javax.swing.JMenuBar;
<add>import javax.swing.JMenu;
<add>import javax.swing.JMenuItem;
<add>import javax.swing.JSeparator;
<add>import java.awt.Color;
<add>import java.awt.Desktop;
<add>import java.awt.Font;
<add>import java.awt.Toolkit;
<add>
<add>public class Div {
<add>
<add> private JFrame frmTurtleCalculator;
<add> private JTextField textField_1;
<add> private JTextField textField_2;
<add> private JTextField textField;
<add>
<add> /**
<add> * Launch the application.
<add> */
<add> public static void main(String[] args) {
<add> EventQueue.invokeLater(new Runnable() {
<add> public void run() {
<add> try {
<add> Div window = new Div();
<add> window.frmTurtleCalculator.setVisible(true);
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> }
<add> }
<add> });
<add> }
<add>
<add> /**
<add> * Create the application.
<add> */
<add> public Div() {
<add> initialize();
<add> }
<add>
<add> /**
<add> * Initialize the contents of the frame.
<add> */
<add> private void initialize() {
<add> try {
<add> UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
<add> } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
<add> e.printStackTrace();
<add> }
<add> frmTurtleCalculator = new JFrame();
<add> frmTurtleCalculator.setIconImage(Toolkit.getDefaultToolkit().getImage(Div.class.getResource("/com/sun/javafx/scene/control/skin/modena/HTMLEditor-Break.png")));
<add> frmTurtleCalculator.setResizable(false);
<add> frmTurtleCalculator.setTitle("Turtle Calculator");
<add> frmTurtleCalculator.setBounds(100, 100, 376, 202);
<add> frmTurtleCalculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
<add>
<add>
<add>
<add> //TODO Main
<add> textField = new JTextField();
<add> textField.setColumns(10);
<add>
<add>
<add>
<add>
<add> JLabel lblTypeInThe = new JLabel("Type in the numbers in the following text boxes:");
<add>
<add>
<add> JLabel label = new JLabel("/");
<add>
<add> textField_1 = new JTextField();
<add> textField_1.setColumns(10);
<add>
<add>
<add>
<add>
<add> JLabel label_1 = new JLabel("=");
<add>
<add>
<add> JButton btnCancel = new JButton("Cancel");
<add> btnCancel.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> System.exit(0);
<add> }
<add> });
<add>
<add> JLabel lblErrorNoNumbers = new JLabel("Error: Incorrect character/no numbers found!");
<add> lblErrorNoNumbers.setFont(new Font("Tahoma", Font.PLAIN, 13));
<add> lblErrorNoNumbers.setForeground(Color.RED);
<add> lblErrorNoNumbers.setVisible(false);
<add>
<add> JButton btnAdd = new JButton("Divide");
<add> btnAdd.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> try{
<add> String hi2 = textField.getText();
<add> String hi1 = textField_1.getText();
<add> double x = Double.parseDouble(hi1);
<add> double o = Double.parseDouble(hi2);
<add> double p = o - x;
<add> String hi4 = "" + p;
<add> textField_2.setText(hi4);
<add> } catch(Exception i){
<add> i.printStackTrace();
<add> lblErrorNoNumbers.setVisible(true);
<add> }
<add> }
<add> });
<add>
<add>
<add>
<add> textField_2 = new JTextField();
<add> textField_2.setEditable(false);
<add> textField_2.setColumns(10);
<add>
<add> //TODO Group layout
<add> GroupLayout groupLayout = new GroupLayout(frmTurtleCalculator.getContentPane());
<add> groupLayout.setHorizontalGroup(
<add> groupLayout.createParallelGroup(Alignment.LEADING)
<add> .addGroup(groupLayout.createSequentialGroup()
<add> .addContainerGap()
<add> .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
<add> .addGroup(groupLayout.createSequentialGroup()
<add> .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
<add> .addComponent(lblTypeInThe)
<add> .addGroup(groupLayout.createSequentialGroup()
<add> .addGap(14)
<add> .addComponent(textField, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
<add> .addPreferredGap(ComponentPlacement.RELATED)
<add> .addComponent(label)
<add> .addPreferredGap(ComponentPlacement.RELATED)
<add> .addComponent(textField_1, 107, 107, 107)))
<add> .addPreferredGap(ComponentPlacement.RELATED)
<add> .addComponent(label_1)
<add> .addPreferredGap(ComponentPlacement.RELATED)
<add> .addComponent(textField_2, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE))
<add> .addGroup(groupLayout.createSequentialGroup()
<add> .addComponent(btnCancel)
<add> .addPreferredGap(ComponentPlacement.RELATED, 236, Short.MAX_VALUE)
<add> .addComponent(btnAdd))
<add> .addComponent(lblErrorNoNumbers))
<add> .addContainerGap())
<add> );
<add> groupLayout.setVerticalGroup(
<add> groupLayout.createParallelGroup(Alignment.LEADING)
<add> .addGroup(groupLayout.createSequentialGroup()
<add> .addContainerGap()
<add> .addComponent(lblTypeInThe)
<add> .addGap(18)
<add> .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
<add> .addComponent(label)
<add> .addComponent(label_1)
<add> .addComponent(textField_2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
<add> .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
<add> .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
<add> .addPreferredGap(ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
<add> .addComponent(lblErrorNoNumbers)
<add> .addGap(18)
<add> .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
<add> .addComponent(btnCancel)
<add> .addComponent(btnAdd))
<add> .addContainerGap())
<add> );
<add> frmTurtleCalculator.getContentPane().setLayout(groupLayout);
<add>
<add> //TODO Menu Bar
<add> JMenuBar menuBar = new JMenuBar();
<add> frmTurtleCalculator.setJMenuBar(menuBar);
<add>
<add> JMenu mnFile = new JMenu("File");
<add> menuBar.add(mnFile);
<add>
<add>
<add>
<add>
<add>
<add> JMenuItem mntmClearHistory = new JMenuItem("Clear History");
<add> mntmClearHistory.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> }
<add> });
<add> mnFile.add(mntmClearHistory);
<add>
<add> mnFile.addSeparator();
<add>
<add> JMenuItem mntmExit = new JMenuItem("Exit");
<add> mntmExit.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> System.exit(0);
<add> }
<add> });
<add> mnFile.add(mntmExit);
<add>
<add> }
<add>} |
|
Java | apache-2.0 | 9c299b9cdfc3b35c967f0f73b041d550f702cded | 0 | remkop/picocli,remkop/picocli,remkop/picocli,remkop/picocli | /*
* 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.
*/
package picocli;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* Demonstrates some of picoCLI's capabilities.
*/
public class Demo {
@CommandLine.Command(name = "git", sortOptions = false, showDefaultValues = false,
description = "Git is a fast, scalable, distributed revision control " +
"system with an unusually rich command set that provides both " +
"high-level operations and full access to internals.",
commandListHeading = "%nCommands:%n%nThe most commonly used git commands are:%n")
class Git {
@CommandLine.Option(names = {"-V", "--version"}, help = true, description = "Prints version information and exits")
boolean isVersionRequested;
@CommandLine.Option(names = {"-h", "--help"}, help = true, description = "Prints this help message and exits")
boolean isHelpRequested;
@CommandLine.Option(names = "--git-dir", description = "Set the path to the repository")
File gitDir;
}
// the "status" subcommand's has an option "mode" with a fixed number of values, modeled by this enum
enum GitStatusMode {all, no, normal};
@CommandLine.Command(name = "git-status",
header = "Show the working tree status",
customSynopsis = "git-status [<options>...] [--] [<pathspec>...]",
description = "Displays paths that have differences between the index file and the current HEAD commit, " +
"paths that have differences between the working tree and the index file, and paths in the " +
"working tree that are not tracked by Git (and are not ignored by gitignore(5)). The first " +
"are what you would commit by running git commit; the second and third are what you could " +
"commit by running git add before running git commit.")
class GitStatus {
@CommandLine.Option(names = {"-s", "--short"}, description = "Give the output in the short-format")
boolean shortFormat;
@CommandLine.Option(names = {"-b", "--branch"}, description = "Show the branch and tracking info even in short-format")
boolean branchInfo;
@CommandLine.Option(names = "--ignored", description = "Show ignored files as well") boolean showIgnored;
@CommandLine.Option(names = {"-u", "--untracked"}, valueLabel = "<mode>", description = {
"Show untracked files.",
"The mode parameter is optional (defaults to `all`), and is used to specify the handling of untracked files.",
"The possible options are:",
" · no - Show no untracked files.",
" · normal - Shows untracked files and directories.",
" · all - Also shows individual files in untracked directories."
})
GitStatusMode mode = GitStatusMode.all;
}
@CommandLine.Command(name = "git-commit", sortOptions = false, header = "Record changes to the repository",
description = "Stores the current contents of the index in a new commit along with a " +
"log message from the user describing the changes.")
class GitCommit {
@CommandLine.Option(names = {"-a", "--all"},
description = "Tell the command to automatically stage files that have been modified " +
"and deleted, but new files you have not told Git about are not affected.")
boolean all;
@CommandLine.Option(names = {"-p", "--patch"}, description = "Use the interactive patch selection interface to chose which changes to commit")
boolean patch;
@CommandLine.Option(names = {"-C", "--reuse-message"}, valueLabel = "<commit>",
description = "Take an existing commit object, and reuse the log message and the " +
"authorship information (including the timestamp) when creating the commit.")
String reuseMessageCommit;
@CommandLine.Option(names = {"-c", "--reedit-message"}, valueLabel = "<commit>",
description = "Like -C, but with -c the editor is invoked, so that the user can" +
"further edit the commit message.\n")
String reEditMessageCommit;
@CommandLine.Option(names = "--fixup", valueLabel = "<commit>",
description = "Construct a commit message for use with rebase --autosquash.")
String fixupCommit;
@CommandLine.Option(names = "--squash", valueLabel = "<commit>",
description = " Construct a commit message for use with rebase --autosquash. The commit" +
"message subject line is taken from the specified commit with a prefix of " +
"\"squash! \". Can be used with additional commit message options (-m/-c/-C/-F).")
String squashCommit;
@CommandLine.Option(names = {"-F", "--file"}, valueLabel = "<file>",
description = "Take the commit message from the given file. Use - to read the message from the standard input.")
File file;
@CommandLine.Option(names = {"-m", "--message"}, valueLabel = "<msg>",
description = " Use the given <msg> as the commit message. If multiple -m options" +
" are given, their values are concatenated as separate paragraphs.")
List<String> message = new ArrayList<String>();
@CommandLine.Parameters(valueLabel = "<files>", description = "the files to commit")
List<File> files = new ArrayList<File>();
}
// defines some commands to show in the list (option/parameters fields omitted for this demo)
@CommandLine.Command(name = "git-add", header = "Add file contents to the index") class GitAdd {}
@CommandLine.Command(name = "git-branch", header = "List, create, or delete branches") class GitBranch {}
@CommandLine.Command(name = "git-checkout", header = "Checkout a branch or paths to the working tree") class GitCheckout{}
@CommandLine.Command(name = "git-clone", header = "Clone a repository into a new directory") class GitClone{}
@CommandLine.Command(name = "git-diff", header = "Show changes between commits, commit and working tree, etc") class GitDiff{}
@CommandLine.Command(name = "git-merge", header = "Join two or more development histories together") class GitMerge{}
@CommandLine.Command(name = "git-push", header = "Update remote refs along with associated objects") class GitPush{}
@CommandLine.Command(name = "git-rebase", header = "Forward-port local commits to the updated upstream head") class GitRebase{}
@CommandLine.Command(name = "git-tag", header = "Create, list, delete or verify a tag object signed with GPG") class GitTag{}
@Test
public void testParseSubCommands() {
CommandLine commandLine = new CommandLine(new Git());
commandLine.addCommand("status", new GitStatus());
commandLine.addCommand("commit", new GitCommit());
commandLine.addCommand("add", new GitAdd());
commandLine.addCommand("branch", new GitBranch());
commandLine.addCommand("checkout", new GitCheckout());
commandLine.addCommand("clone", new GitClone());
commandLine.addCommand("diff", new GitDiff());
commandLine.addCommand("merge", new GitMerge());
commandLine.addCommand("push", new GitPush());
commandLine.addCommand("rebase", new GitRebase());
commandLine.addCommand("tag", new GitTag());
List<Object> parsed = commandLine.parse("--git-dir=/home/rpopma/picocli status -sbuno".split(" "));
assertEquals("command count", 2, parsed.size());
assertEquals(Git.class, parsed.get(0).getClass());
assertEquals(GitStatus.class, parsed.get(1).getClass());
Git git = (Git) parsed.get(0);
assertEquals(new File("/home/rpopma/picocli"), git.gitDir);
GitStatus status = (GitStatus) parsed.get(1);
assertTrue("status -s", status.shortFormat);
assertTrue("status -b", status.branchInfo);
assertFalse("NOT status --showIgnored", status.showIgnored);
assertEquals("status -u=no", GitStatusMode.no, status.mode);
}
@Test
public void testUsageMainCommand() throws Exception {
CommandLine commandLine = new CommandLine(new Git());
commandLine.addCommand("status", new GitStatus());
commandLine.addCommand("commit", new GitCommit());
commandLine.addCommand("add", new GitAdd());
commandLine.addCommand("branch", new GitBranch());
commandLine.addCommand("checkout", new GitCheckout());
commandLine.addCommand("clone", new GitClone());
commandLine.addCommand("diff", new GitDiff());
commandLine.addCommand("merge", new GitMerge());
commandLine.addCommand("push", new GitPush());
commandLine.addCommand("rebase", new GitRebase());
commandLine.addCommand("tag", new GitTag());
String expected = "Usage: git [-hV] [--git-dir=<gitDir>]%n" +
"Git is a fast, scalable, distributed revision control system with an unusually%n" +
"rich command set that provides both high-level operations and full access to%n" +
"internals.%n" +
" -V, --version Prints version information and exits%n" +
" -h, --help Prints this help message and exits%n" +
" --git-dir=<gitDir> Set the path to the repository%n" +
"%n" +
"Commands:%n" +
"%n" +
"The most commonly used git commands are:%n" +
" status Show the working tree status%n" +
" commit Record changes to the repository%n" +
" add Add file contents to the index%n" +
" branch List, create, or delete branches%n" +
" checkout Checkout a branch or paths to the working tree%n" +
" clone Clone a repository into a new directory%n" +
" diff Show changes between commits, commit and working tree, etc%n" +
" merge Join two or more development histories together%n" +
" push Update remote refs along with associated objects%n" +
" rebase Forward-port local commits to the updated upstream head%n" +
" tag Create, list, delete or verify a tag object signed with GPG%n";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
commandLine.usage(new PrintStream(baos, true, "UTF8"));
String result = baos.toString("UTF8");
assertEquals(String.format(expected), result);
}
@Test
public void testUsageSubCommand() throws Exception {
String expected = "Show the working tree status%n" +
"Usage: git-status [<options>...] [--] [<pathspec>...]%n" +
"Displays paths that have differences between the index file and the current%n" +
"HEAD commit, paths that have differences between the working tree and the index%n" +
"file, and paths in the working tree that are not tracked by Git (and are not%n" +
"ignored by gitignore(5)). The first are what you would commit by running git%n" +
"commit; the second and third are what you could commit by running git add%n" +
"before running git commit.%n" +
" --ignored Show ignored files as well%n" +
" -b, --branch Show the branch and tracking info even in%n" +
" short-format%n" +
" -s, --short Give the output in the short-format%n" +
" -u, --untracked=<mode> Show untracked files.%n" +
" The mode parameter is optional (defaults to%n" +
" `all`), and is used to specify the handling of%n" +
" untracked files.%n" +
" The possible options are:%n" +
" · no - Show no untracked files.%n" +
" · normal - Shows untracked files and directories.%n" +
" · all - Also shows individual files in untracked%n" +
" directories.%n" +
" Default: all%n";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CommandLine.usage(new GitStatus(), new PrintStream(baos, true, "UTF8"));
String result = baos.toString("UTF8");
assertEquals(String.format(expected), result);
}
}
| src/test/java/picocli/Demo.java | /*
* 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.
*/
package picocli;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
/**
* Demonstrates some of picoCLI's capabilities.
*/
public class Demo {
@CommandLine.Command(name = "git", sortOptions = false, showDefaultValues = false,
description = "Git is a fast, scalable, distributed revision control " +
"system with an unusually rich command set that provides both high-level operations " +
"and full access to internals.")
class Git {
@CommandLine.Option(names = {"-V", "--version"}, help = true, description = "Prints version information and exits")
boolean isVersionRequested;
@CommandLine.Option(names = {"-h", "--help"}, help = true, description = "Prints this help message and exits")
boolean isHelpRequested;
@CommandLine.Option(names = "--git-dir", description = "Set the path to the repository")
File gitDir;
}
// the "status" subcommand's has an option "mode" with a fixed number of values, modeled by this enum
enum GitStatusMode {all, no, normal};
@CommandLine.Command(name = "git-status",
header = "Show the working tree status",
customSynopsis = "status [<options>...] [--] [<pathspec>...]",
description = "Displays paths that have differences between the index file and the current HEAD commit," +
"paths that have differences between the working tree and the index file, and paths in the" +
"working tree that are not tracked by Git (and are not ignored by gitignore(5)). The first" +
"are what you would commit by running git commit; the second and third are what you could" +
"commit by running git add before running git commit.")
class GitStatus {
@CommandLine.Option(names = {"-s", "--short"}, description = "Give the output in the short-format")
boolean shortFormat;
@CommandLine.Option(names = {"-b", "--branch"}, description = "Show the branch and tracking info even in short-format")
boolean branchInfo;
@CommandLine.Option(names = "--ignored", description = "Show ignored files as well") boolean showIgnored;
@CommandLine.Option(names = {"-u", "--untracked"}, valueLabel = "<mode>", description = {
"Show untracked files.",
"The mode parameter is optional (defaults to `all`), and is used to specify the handling of untracked files.",
"The possible options are:",
" · no - Show no untracked files.",
" · normal - Shows untracked files and directories.",
" · all - Also shows individual files in untracked directories."
})
GitStatusMode mode = GitStatusMode.all;
}
@CommandLine.Command(name = "git-commit", sortOptions = false, header = "Record changes to the repository",
description = "Stores the current contents of the index in a new commit along with a " +
"log message from the user describing the changes.")
class GitCommit {
@CommandLine.Option(names = {"-a", "--all"},
description = "Tell the command to automatically stage files that have been modified " +
"and deleted, but new files you have not told Git about are not affected.")
boolean all;
@CommandLine.Option(names = {"-p", "--patch"}, description = "Use the interactive patch selection interface to chose which changes to commit")
boolean patch;
@CommandLine.Option(names = {"-C", "--reuse-message"}, valueLabel = "<commit>",
description = "Take an existing commit object, and reuse the log message and the " +
"authorship information (including the timestamp) when creating the commit.")
String reuseMessageCommit;
@CommandLine.Option(names = {"-c", "--reedit-message"}, valueLabel = "<commit>",
description = "Like -C, but with -c the editor is invoked, so that the user can" +
"further edit the commit message.\n")
String reEditMessageCommit;
@CommandLine.Option(names = "--fixup", valueLabel = "<commit>",
description = "Construct a commit message for use with rebase --autosquash.")
String fixupCommit;
@CommandLine.Option(names = "--squash", valueLabel = "<commit>",
description = " Construct a commit message for use with rebase --autosquash. The commit" +
"message subject line is taken from the specified commit with a prefix of " +
"\"squash! \". Can be used with additional commit message options (-m/-c/-C/-F).")
String squashCommit;
@CommandLine.Option(names = {"-F", "--file"}, valueLabel = "<file>",
description = "Take the commit message from the given file. Use - to read the message from the standard input.")
File file;
@CommandLine.Option(names = {"-m", "--message"}, valueLabel = "<msg>",
description = " Use the given <msg> as the commit message. If multiple -m options" +
" are given, their values are concatenated as separate paragraphs.")
List<String> message = new ArrayList<String>();
@CommandLine.Parameters(valueLabel = "<files>", description = "the files to commit")
List<File> files = new ArrayList<File>();
}
// defines some commands to show in the list (option/parameters fields omitted for this demo)
@CommandLine.Command(name = "git-add", header = "Add file contents to the index") class GitAdd {}
@CommandLine.Command(name = "git-branch", header = "List, create, or delete branches") class GitBranch {}
@CommandLine.Command(name = "git-checkout", header = "Checkout a branch or paths to the working tree") class GitCheckout{}
@CommandLine.Command(name = "git-clone", header = "Clone a repository into a new directory") class GitClone{}
@CommandLine.Command(name = "git-diff", header = "Show changes between commits, commit and working tree, etc") class GitDiff{}
@CommandLine.Command(name = "git-merge", header = "Join two or more development histories together") class GitMerge{}
@CommandLine.Command(name = "git-push", header = "Update remote refs along with associated objects") class GitPush{}
@CommandLine.Command(name = "git-rebase", header = "Forward-port local commits to the updated upstream head") class GitRebase{}
@CommandLine.Command(name = "git-tag", header = "Create, list, delete or verify a tag object signed with GPG") class GitTag{}
@Test
public void testParseSubCommands() {
CommandLine commandLine = new CommandLine(new Git());
commandLine.addCommand("status", new GitStatus());
commandLine.addCommand("commit", new GitCommit());
commandLine.addCommand("add", new GitAdd());
commandLine.addCommand("branch", new GitBranch());
commandLine.addCommand("checkout", new GitCheckout());
commandLine.addCommand("clone", new GitClone());
commandLine.addCommand("diff", new GitDiff());
commandLine.addCommand("merge", new GitMerge());
commandLine.addCommand("push", new GitPush());
commandLine.addCommand("rebase", new GitRebase());
commandLine.addCommand("tag", new GitTag());
List<Object> parsed = commandLine.parse("--git-dir=/home/rpopma/picocli status -sbuno".split(" "));
assertEquals("command count", 2, parsed.size());
assertEquals(Git.class, parsed.get(0).getClass());
assertEquals(GitStatus.class, parsed.get(1).getClass());
Git git = (Git) parsed.get(0);
GitStatus status = (GitStatus) parsed.get(1);
assertEquals(new File("/home/rpopma/picocli"), git.gitDir);
assertTrue("status -s", status.shortFormat);
assertTrue("status -b", status.branchInfo);
assertFalse("NOT status --showIgnored", status.showIgnored);
assertEquals("status -u=no", GitStatusMode.no, status.mode);
}
@Test
public void testUsageSubCommands() throws Exception {
CommandLine commandLine = new CommandLine(new Git());
commandLine.addCommand("status", new GitStatus());
commandLine.addCommand("commit", new GitCommit());
commandLine.addCommand("add", new GitAdd());
commandLine.addCommand("branch", new GitBranch());
commandLine.addCommand("checkout", new GitCheckout());
commandLine.addCommand("clone", new GitClone());
commandLine.addCommand("diff", new GitDiff());
commandLine.addCommand("merge", new GitMerge());
commandLine.addCommand("push", new GitPush());
commandLine.addCommand("rebase", new GitRebase());
commandLine.addCommand("tag", new GitTag());
String expected = "Usage: git [-hV] [--git-dir=<gitDir>]%n" +
"Git is a fast, scalable, distributed revision control system with an unusually%n" +
"rich command set that provides both high-level operations and full access to%n" +
"internals.%n" +
" -V, --version Prints version information and exits%n" +
" -h, --help Prints this help message and exits%n" +
" --git-dir=<gitDir> Set the path to the repository%n" +
"%n" +
"Commands:%n" +
"%n" +
"The most commonly used git commands are:%n" +
" status Show the working tree status%n" +
" commit Record changes to the repository%n" +
" add Add file contents to the index%n" +
" branch List, create, or delete branches%n" +
" checkout Checkout a branch or paths to the working tree%n" +
" clone Clone a repository into a new directory%n" +
" diff Show changes between commits, commit and working tree, etc%n" +
" merge Join two or more development histories together%n" +
" push Update remote refs along with associated objects%n" +
" rebase Forward-port local commits to the updated upstream head%n" +
" tag Create, list, delete or verify a tag object signed with GPG%n";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
commandLine.usage(new PrintStream(baos, true, "UTF8"));
String result = baos.toString("UTF8");
assertEquals(String.format(expected), result);
}
}
| Cleanup, added sub-command test
| src/test/java/picocli/Demo.java | Cleanup, added sub-command test | <ide><path>rc/test/java/picocli/Demo.java
<ide>
<ide> @CommandLine.Command(name = "git", sortOptions = false, showDefaultValues = false,
<ide> description = "Git is a fast, scalable, distributed revision control " +
<del> "system with an unusually rich command set that provides both high-level operations " +
<del> "and full access to internals.")
<add> "system with an unusually rich command set that provides both " +
<add> "high-level operations and full access to internals.",
<add> commandListHeading = "%nCommands:%n%nThe most commonly used git commands are:%n")
<ide> class Git {
<ide> @CommandLine.Option(names = {"-V", "--version"}, help = true, description = "Prints version information and exits")
<ide> boolean isVersionRequested;
<ide>
<ide> @CommandLine.Command(name = "git-status",
<ide> header = "Show the working tree status",
<del> customSynopsis = "status [<options>...] [--] [<pathspec>...]",
<del> description = "Displays paths that have differences between the index file and the current HEAD commit," +
<del> "paths that have differences between the working tree and the index file, and paths in the" +
<del> "working tree that are not tracked by Git (and are not ignored by gitignore(5)). The first" +
<del> "are what you would commit by running git commit; the second and third are what you could" +
<add> customSynopsis = "git-status [<options>...] [--] [<pathspec>...]",
<add> description = "Displays paths that have differences between the index file and the current HEAD commit, " +
<add> "paths that have differences between the working tree and the index file, and paths in the " +
<add> "working tree that are not tracked by Git (and are not ignored by gitignore(5)). The first " +
<add> "are what you would commit by running git commit; the second and third are what you could " +
<ide> "commit by running git add before running git commit.")
<ide> class GitStatus {
<ide> @CommandLine.Option(names = {"-s", "--short"}, description = "Give the output in the short-format")
<ide>
<ide> assertEquals(Git.class, parsed.get(0).getClass());
<ide> assertEquals(GitStatus.class, parsed.get(1).getClass());
<add>
<ide> Git git = (Git) parsed.get(0);
<add> assertEquals(new File("/home/rpopma/picocli"), git.gitDir);
<add>
<ide> GitStatus status = (GitStatus) parsed.get(1);
<del>
<del> assertEquals(new File("/home/rpopma/picocli"), git.gitDir);
<ide> assertTrue("status -s", status.shortFormat);
<ide> assertTrue("status -b", status.branchInfo);
<ide> assertFalse("NOT status --showIgnored", status.showIgnored);
<ide> }
<ide>
<ide> @Test
<del> public void testUsageSubCommands() throws Exception {
<add> public void testUsageMainCommand() throws Exception {
<ide> CommandLine commandLine = new CommandLine(new Git());
<ide> commandLine.addCommand("status", new GitStatus());
<ide> commandLine.addCommand("commit", new GitCommit());
<ide> String result = baos.toString("UTF8");
<ide> assertEquals(String.format(expected), result);
<ide> }
<add>
<add> @Test
<add> public void testUsageSubCommand() throws Exception {
<add> String expected = "Show the working tree status%n" +
<add> "Usage: git-status [<options>...] [--] [<pathspec>...]%n" +
<add> "Displays paths that have differences between the index file and the current%n" +
<add> "HEAD commit, paths that have differences between the working tree and the index%n" +
<add> "file, and paths in the working tree that are not tracked by Git (and are not%n" +
<add> "ignored by gitignore(5)). The first are what you would commit by running git%n" +
<add> "commit; the second and third are what you could commit by running git add%n" +
<add> "before running git commit.%n" +
<add> " --ignored Show ignored files as well%n" +
<add> " -b, --branch Show the branch and tracking info even in%n" +
<add> " short-format%n" +
<add> " -s, --short Give the output in the short-format%n" +
<add> " -u, --untracked=<mode> Show untracked files.%n" +
<add> " The mode parameter is optional (defaults to%n" +
<add> " `all`), and is used to specify the handling of%n" +
<add> " untracked files.%n" +
<add> " The possible options are:%n" +
<add> " · no - Show no untracked files.%n" +
<add> " · normal - Shows untracked files and directories.%n" +
<add> " · all - Also shows individual files in untracked%n" +
<add> " directories.%n" +
<add> " Default: all%n";
<add> ByteArrayOutputStream baos = new ByteArrayOutputStream();
<add> CommandLine.usage(new GitStatus(), new PrintStream(baos, true, "UTF8"));
<add> String result = baos.toString("UTF8");
<add> assertEquals(String.format(expected), result);
<add> }
<ide> } |
|
Java | apache-2.0 | error: pathspec 'btm/src/test/java/bitronix/tm/resource/ResourceRegistrarTest.java' did not match any file(s) known to git
| e8de5a6513532d28444c2390575808678e13dcb2 | 1 | veresh/btm,gavioto/btm,tomsorgie/btm,sshankar/btm,pgbsl/btm,tomsorgie/btm,brettwooldridge/btm,leogong/btm,pgbsl/btm,sshankar/btm,bitronix/btm,Everteam-Software/btm,veresh/btm,marcus-nl/btm,Everteam-Software/btm,bitronix/btm,brettwooldridge/btm,gavioto/btm,leogong/btm,marcus-nl/btm | /*
* Bitronix Transaction Manager
*
* Copyright (c) 2011, Juergen Kellerer.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package bitronix.tm.resource;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.internal.XAResourceHolderState;
import bitronix.tm.recovery.RecoveryException;
import bitronix.tm.resource.common.ResourceBean;
import bitronix.tm.resource.common.XAResourceHolder;
import bitronix.tm.resource.common.XAResourceProducer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.transaction.xa.XAResource;
import java.util.concurrent.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* Tests the fundamental functionality of the newly implemented ResourceRegistrar.
*
* @author Juergen_Kellerer, 2011-08-24
*/
public class ResourceRegistrarTest {
ExecutorService executorService;
XAResourceProducer producer;
private XAResourceProducer createMockProducer(String uniqueName) throws RecoveryException {
XAResourceProducer producer;
producer = mock(XAResourceProducer.class);
when(producer.getUniqueName()).thenReturn(uniqueName);
ResourceBean resourceBean = mock(ResourceBean.class);
when(resourceBean.getUniqueName()).thenReturn(uniqueName);
XAResourceHolder resourceHolder = mock(XAResourceHolder.class);
when(resourceHolder.getResourceBean()).thenReturn(resourceBean);
XAResource xaResource = mock(XAResource.class);
when(resourceHolder.getXAResource()).thenReturn(xaResource);
when(producer.startRecovery()).thenReturn(new XAResourceHolderState(resourceHolder, resourceBean));
return producer;
}
private Future registerBlockingProducer(final XAResourceProducer producer, final CountDownLatch border) throws RecoveryException {
final XAResourceHolderState resourceHolderState = producer.startRecovery();
when(producer.startRecovery()).thenAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
border.await();
return resourceHolderState;
}
});
return executorService.submit(new Callable<Object>() {
public Object call() throws Exception {
ResourceRegistrar.register(producer);
return null;
}
});
}
@Before
public void setUp() throws Exception {
executorService = Executors.newCachedThreadPool();
producer = createMockProducer("xa-rp");
ResourceRegistrar.register(producer);
TransactionManagerServices.getTransactionManager();
}
@After
public void tearDown() throws Exception {
TransactionManagerServices.getTransactionManager().shutdown();
executorService.shutdown();
for (String name : ResourceRegistrar.getResourcesUniqueNames())
ResourceRegistrar.unregister(ResourceRegistrar.get(name));
}
@Test
public void testGet() throws Exception {
assertSame(producer, ResourceRegistrar.get("xa-rp"));
assertNull(ResourceRegistrar.get("non-existing"));
assertNull(ResourceRegistrar.get(null));
}
@Test
public void testGetDoesNotReturnUninitializedProducers() throws Exception {
CountDownLatch border = new CountDownLatch(1);
Future future = registerBlockingProducer(createMockProducer("uninitialized"), border);
assertNull(ResourceRegistrar.get("uninitialized"));
border.countDown();
future.get();
assertNotNull(ResourceRegistrar.get("uninitialized"));
}
@Test
public void testGetResourcesUniqueNames() throws Exception {
assertArrayEquals(new Object[]{"xa-rp"}, ResourceRegistrar.getResourcesUniqueNames().toArray());
}
@Test
public void testGetResourcesUniqueNamesDoesNotReturnUninitializedProducers() throws Exception {
CountDownLatch border = new CountDownLatch(1);
Future future = registerBlockingProducer(createMockProducer("uninitialized"), border);
assertArrayEquals(new Object[]{"xa-rp"}, ResourceRegistrar.getResourcesUniqueNames().toArray());
border.countDown();
future.get();
assertArrayEquals(new Object[]{"xa-rp", "uninitialized"}, ResourceRegistrar.getResourcesUniqueNames().toArray());
}
@Test(expected = IllegalStateException.class)
public void testCannotRegisterSameRPTwice() throws Exception {
ResourceRegistrar.register(createMockProducer("xa-rp"));
}
@Test
public void testNonRecoverableProducersAreNotRegistered() throws Exception {
final XAResourceProducer producer = createMockProducer("non-recoverable");
when(producer.startRecovery()).thenThrow(new RecoveryException("recovery not possible"));
try {
ResourceRegistrar.register(producer);
fail("expecting RecoveryException");
} catch (RecoveryException e) {
assertNull(ResourceRegistrar.get("non-recoverable"));
}
}
@Test
public void testUnregister() throws Exception {
assertEquals(1, ResourceRegistrar.getResourcesUniqueNames().size());
ResourceRegistrar.unregister(createMockProducer("xa-rp"));
assertEquals(0, ResourceRegistrar.getResourcesUniqueNames().size());
}
@Test
public void testFindXAResourceHolderDelegatesAndDoesNotCallUninitialized() throws Exception {
final XAResource resource = mock(XAResource.class);
final XAResourceProducer uninitializedProducer = createMockProducer("uninitialized");
CountDownLatch border = new CountDownLatch(1);
Future future = registerBlockingProducer(uninitializedProducer, border);
ResourceRegistrar.findXAResourceHolder(resource);
verify(producer, times(1)).findXAResourceHolder(resource);
verify(uninitializedProducer, times(0)).findXAResourceHolder(resource);
border.countDown();
future.get();
ResourceRegistrar.findXAResourceHolder(resource);
verify(producer, times(2)).findXAResourceHolder(resource);
verify(uninitializedProducer, times(1)).findXAResourceHolder(resource);
}
}
| btm/src/test/java/bitronix/tm/resource/ResourceRegistrarTest.java | Added tests for the fundamental functionality of the newly implemented ResourceRegistrar.
| btm/src/test/java/bitronix/tm/resource/ResourceRegistrarTest.java | Added tests for the fundamental functionality of the newly implemented ResourceRegistrar. | <ide><path>tm/src/test/java/bitronix/tm/resource/ResourceRegistrarTest.java
<add>/*
<add> * Bitronix Transaction Manager
<add> *
<add> * Copyright (c) 2011, Juergen Kellerer.
<add> *
<add> * This copyrighted material is made available to anyone wishing to use, modify,
<add> * copy, or redistribute it subject to the terms and conditions of the GNU
<add> * Lesser General Public License, as published by the Free Software Foundation.
<add> *
<add> * This program is distributed in the hope that it will be useful,
<add> * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
<add> * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
<add> * for more details.
<add> *
<add> * You should have received a copy of the GNU Lesser General Public License
<add> * along with this distribution; if not, write to:
<add> * Free Software Foundation, Inc.
<add> * 51 Franklin Street, Fifth Floor
<add> * Boston, MA 02110-1301 USA
<add> */
<add>
<add>package bitronix.tm.resource;
<add>
<add>import bitronix.tm.TransactionManagerServices;
<add>import bitronix.tm.internal.XAResourceHolderState;
<add>import bitronix.tm.recovery.RecoveryException;
<add>import bitronix.tm.resource.common.ResourceBean;
<add>import bitronix.tm.resource.common.XAResourceHolder;
<add>import bitronix.tm.resource.common.XAResourceProducer;
<add>import org.junit.After;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>import org.mockito.invocation.InvocationOnMock;
<add>import org.mockito.stubbing.Answer;
<add>
<add>import javax.transaction.xa.XAResource;
<add>import java.util.concurrent.*;
<add>
<add>import static org.junit.Assert.*;
<add>import static org.mockito.Mockito.*;
<add>
<add>/**
<add> * Tests the fundamental functionality of the newly implemented ResourceRegistrar.
<add> *
<add> * @author Juergen_Kellerer, 2011-08-24
<add> */
<add>public class ResourceRegistrarTest {
<add>
<add> ExecutorService executorService;
<add> XAResourceProducer producer;
<add>
<add> private XAResourceProducer createMockProducer(String uniqueName) throws RecoveryException {
<add> XAResourceProducer producer;
<add> producer = mock(XAResourceProducer.class);
<add> when(producer.getUniqueName()).thenReturn(uniqueName);
<add>
<add> ResourceBean resourceBean = mock(ResourceBean.class);
<add> when(resourceBean.getUniqueName()).thenReturn(uniqueName);
<add>
<add> XAResourceHolder resourceHolder = mock(XAResourceHolder.class);
<add> when(resourceHolder.getResourceBean()).thenReturn(resourceBean);
<add>
<add> XAResource xaResource = mock(XAResource.class);
<add> when(resourceHolder.getXAResource()).thenReturn(xaResource);
<add>
<add> when(producer.startRecovery()).thenReturn(new XAResourceHolderState(resourceHolder, resourceBean));
<add> return producer;
<add> }
<add>
<add> private Future registerBlockingProducer(final XAResourceProducer producer, final CountDownLatch border) throws RecoveryException {
<add> final XAResourceHolderState resourceHolderState = producer.startRecovery();
<add> when(producer.startRecovery()).thenAnswer(new Answer<Object>() {
<add> public Object answer(InvocationOnMock invocation) throws Throwable {
<add> border.await();
<add> return resourceHolderState;
<add> }
<add> });
<add>
<add> return executorService.submit(new Callable<Object>() {
<add> public Object call() throws Exception {
<add> ResourceRegistrar.register(producer);
<add> return null;
<add> }
<add> });
<add> }
<add>
<add> @Before
<add> public void setUp() throws Exception {
<add> executorService = Executors.newCachedThreadPool();
<add> producer = createMockProducer("xa-rp");
<add> ResourceRegistrar.register(producer);
<add> TransactionManagerServices.getTransactionManager();
<add> }
<add>
<add> @After
<add> public void tearDown() throws Exception {
<add> TransactionManagerServices.getTransactionManager().shutdown();
<add> executorService.shutdown();
<add> for (String name : ResourceRegistrar.getResourcesUniqueNames())
<add> ResourceRegistrar.unregister(ResourceRegistrar.get(name));
<add> }
<add>
<add>
<add> @Test
<add> public void testGet() throws Exception {
<add> assertSame(producer, ResourceRegistrar.get("xa-rp"));
<add> assertNull(ResourceRegistrar.get("non-existing"));
<add> assertNull(ResourceRegistrar.get(null));
<add> }
<add>
<add> @Test
<add> public void testGetDoesNotReturnUninitializedProducers() throws Exception {
<add> CountDownLatch border = new CountDownLatch(1);
<add> Future future = registerBlockingProducer(createMockProducer("uninitialized"), border);
<add>
<add> assertNull(ResourceRegistrar.get("uninitialized"));
<add> border.countDown();
<add> future.get();
<add> assertNotNull(ResourceRegistrar.get("uninitialized"));
<add> }
<add>
<add> @Test
<add> public void testGetResourcesUniqueNames() throws Exception {
<add> assertArrayEquals(new Object[]{"xa-rp"}, ResourceRegistrar.getResourcesUniqueNames().toArray());
<add> }
<add>
<add> @Test
<add> public void testGetResourcesUniqueNamesDoesNotReturnUninitializedProducers() throws Exception {
<add> CountDownLatch border = new CountDownLatch(1);
<add> Future future = registerBlockingProducer(createMockProducer("uninitialized"), border);
<add>
<add> assertArrayEquals(new Object[]{"xa-rp"}, ResourceRegistrar.getResourcesUniqueNames().toArray());
<add>
<add> border.countDown();
<add> future.get();
<add> assertArrayEquals(new Object[]{"xa-rp", "uninitialized"}, ResourceRegistrar.getResourcesUniqueNames().toArray());
<add> }
<add>
<add> @Test(expected = IllegalStateException.class)
<add> public void testCannotRegisterSameRPTwice() throws Exception {
<add> ResourceRegistrar.register(createMockProducer("xa-rp"));
<add> }
<add>
<add> @Test
<add> public void testNonRecoverableProducersAreNotRegistered() throws Exception {
<add> final XAResourceProducer producer = createMockProducer("non-recoverable");
<add> when(producer.startRecovery()).thenThrow(new RecoveryException("recovery not possible"));
<add>
<add> try {
<add> ResourceRegistrar.register(producer);
<add> fail("expecting RecoveryException");
<add> } catch (RecoveryException e) {
<add> assertNull(ResourceRegistrar.get("non-recoverable"));
<add> }
<add> }
<add>
<add> @Test
<add> public void testUnregister() throws Exception {
<add> assertEquals(1, ResourceRegistrar.getResourcesUniqueNames().size());
<add> ResourceRegistrar.unregister(createMockProducer("xa-rp"));
<add> assertEquals(0, ResourceRegistrar.getResourcesUniqueNames().size());
<add> }
<add>
<add> @Test
<add> public void testFindXAResourceHolderDelegatesAndDoesNotCallUninitialized() throws Exception {
<add> final XAResource resource = mock(XAResource.class);
<add> final XAResourceProducer uninitializedProducer = createMockProducer("uninitialized");
<add>
<add> CountDownLatch border = new CountDownLatch(1);
<add> Future future = registerBlockingProducer(uninitializedProducer, border);
<add>
<add> ResourceRegistrar.findXAResourceHolder(resource);
<add> verify(producer, times(1)).findXAResourceHolder(resource);
<add> verify(uninitializedProducer, times(0)).findXAResourceHolder(resource);
<add>
<add> border.countDown();
<add> future.get();
<add>
<add> ResourceRegistrar.findXAResourceHolder(resource);
<add> verify(producer, times(2)).findXAResourceHolder(resource);
<add> verify(uninitializedProducer, times(1)).findXAResourceHolder(resource);
<add> }
<add>} |
|
Java | mit | e6c12492ed7be2ba598b2bfa7087ed925bd4a603 | 0 | akaGelo/another-live-refresh,akaGelo/another-live-refresh,akaGelo/another-live-refresh | package ru.vyukov.anotherliverefresh.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class LiveRefreshIncludeFilter implements Filter {
private static final String REFRESH_CODE = "<script src=\"/alr/refresh.js\"></script>";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HtmlResponseWrapper capturingResponseWrapper = new HtmlResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, capturingResponseWrapper);
if (response.getContentType() != null && response.getContentType().contains("text/html")) {
String content = capturingResponseWrapper.getAsString();
content = content.replace("</head>", REFRESH_CODE + "\n</head>");
response.setContentLength(content.getBytes().length);
response.getWriter().write(content);
} else {
byte[] content = capturingResponseWrapper.getAsBytes();
response.setContentLength(content.length);
response.getOutputStream().write(content);
}
}
@Override
public void destroy() {
}
}
| another-live-refresh-spring-boot-starter/src/main/java/ru/vyukov/anotherliverefresh/filter/LiveRefreshIncludeFilter.java | package ru.vyukov.anotherliverefresh.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class LiveRefreshIncludeFilter implements Filter {
private static final String REFRESH_CODE = "<script src=\"/alr/refresh.js\"></script>";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HtmlResponseWrapper capturingResponseWrapper = new HtmlResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, capturingResponseWrapper);
String content = capturingResponseWrapper.getAsString();
if (response.getContentType() != null && response.getContentType().contains("text/html")) {
content = content.replace("</head>", REFRESH_CODE + "\n</head>");
}
response.setContentLength(content.getBytes().length);
response.getWriter().write(content);
}
@Override
public void destroy() {
}
}
| binary response support
| another-live-refresh-spring-boot-starter/src/main/java/ru/vyukov/anotherliverefresh/filter/LiveRefreshIncludeFilter.java | binary response support | <ide><path>nother-live-refresh-spring-boot-starter/src/main/java/ru/vyukov/anotherliverefresh/filter/LiveRefreshIncludeFilter.java
<ide>
<ide> chain.doFilter(request, capturingResponseWrapper);
<ide>
<del> String content = capturingResponseWrapper.getAsString();
<ide> if (response.getContentType() != null && response.getContentType().contains("text/html")) {
<add> String content = capturingResponseWrapper.getAsString();
<ide> content = content.replace("</head>", REFRESH_CODE + "\n</head>");
<add>
<add> response.setContentLength(content.getBytes().length);
<add> response.getWriter().write(content);
<add> } else {
<add> byte[] content = capturingResponseWrapper.getAsBytes();
<add> response.setContentLength(content.length);
<add> response.getOutputStream().write(content);
<ide> }
<del>
<del> response.setContentLength(content.getBytes().length);
<del> response.getWriter().write(content);
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | 7295acf3ded973e8abe2c2bf34ff013b0e6571a6 | 0 | linas/relex,virneo/relex,leungmanhin/relex,rodsol/relex,ainishdave/relex,opencog/relex,anitzkin/relex,virneo/relex,virneo/relex,opencog/relex,ainishdave/relex,AmeBel/relex,linas/relex,leungmanhin/relex,ainishdave/relex,williampma/relex,anitzkin/relex,williampma/relex,leungmanhin/relex,AmeBel/relex,ainishdave/relex,rodsol/relex,opencog/relex,rodsol/relex,williampma/relex,williampma/relex,AmeBel/relex,anitzkin/relex,linas/relex,anitzkin/relex,virneo/relex,anitzkin/relex,rodsol/relex | /*
* Copyright 2009 Linas Vepstas
*
* 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.
*/
package relex.test;
import java.util.ArrayList;
import java.util.Collections;
import relex.ParsedSentence;
import relex.RelationExtractor;
import relex.Sentence;
import relex.output.SimpleView;
public class TestRelEx
{
private RelationExtractor re;
private int pass;
private int fail;
private int subpass;
private int subfail;
private static ArrayList<String> sentfail= new ArrayList<String>();
public TestRelEx()
{
re = new RelationExtractor();
pass = 0;
fail = 0;
subpass = 0;
subfail = 0;
}
public ArrayList<String> split(String a)
{
String[] sa = a.split("\n");
ArrayList<String> saa = new ArrayList<String>();
for (String s : sa) {
saa.add(s);
}
Collections.sort (saa);
return saa;
}
/**
* First argument is the sentence.
* Second argument is a list of the relations that RelEx
* should be generating.
* Return true if RelEx generates the same dependencies
* as the second argument.
*/
public boolean test_sentence (String sent, String sf)
{
re.do_penn_tagging = false;
Sentence sntc = re.processSentence(sent);
ParsedSentence parse = sntc.getParses().get(0);
String rs = SimpleView.printBinaryRelations(parse);
ArrayList<String> exp = split(sf);
ArrayList<String> got = split(rs);
if (exp.size() != got.size())
{
System.err.println("Error: size miscompare:\n" +
"\tExpected = " + exp + "\n" +
"\tGot = " + got + "\n" +
"\tSentence = " + sent);
subfail ++;
fail ++;
sentfail.add(sent);
return false;
}
for (int i=0; i< exp.size(); i++)
{
if (!exp.get(i).equals (got.get(i)))
{
System.err.println("Error: content miscompare:\n" +
"\tExpected = " + exp + "\n" +
"\tGot = " + got + "\n" +
"\tSentence = " + sent);
subfail ++;
fail ++;
sentfail.add(sent);
return false;
}
}
subpass ++;
pass ++;
return true;
}
public void report(boolean rc, String subsys)
{
if (rc) {
System.err.println(subsys + ": Tested " + pass + " sentences, test passed OK");
} else {
System.err.println(subsys + ": Test failed\n\t" +
fail + " sentences failed\n\t" +
pass + " sentences passed");
}
subpass = 0;
subfail = 0;
}
public boolean test_comparatives()
{
boolean rc = true;
rc &= test_sentence ("Some people like pigs less than dogs.",
"_advmod(like, less)\n" +
"_obj(like, pig)\n" +
"_quantity(people, some)\n" +
"_subj(like, people)\n" +
"than(pig, dog)\n");
rc &= test_sentence ("Some people like pigs more than dogs.",
"_advmod(like, more)\n" +
"_obj(like, pig)\n" +
"_quantity(people, some)\n" +
"_subj(like, people)\n" +
"than(pig, dog)\n");
report(rc, "Comparatives");
return rc;
}
public boolean test_extraposition()
{
boolean rc = true;
rc &= test_sentence ("The woman who lives next door is a registered nurse.",
"_obj(be, nurse)\n" +
"_subj(be, woman)\n" +
"_amod(nurse, registered)\n" +
"_advmod(live, next_door)\n" +
"_subj(live, woman)\n" +
"who(woman, live)\n");
rc &= test_sentence ("A player who is injured has to leave the field.",
"_to-do(have, leave)\n" +
"_subj(have, player)\n" +
"_obj(leave, field)\n" +
"_predadj(player, injured)\n" +
"who(player, injured)\n" );
rc &= test_sentence ("Pizza, which most people love, is not very healthy.",
"_advmod(very, not)\n" +
"_advmod(healthy, very)\n" +
"_obj(love, pizza)\n" +
"_quantity(people, most)\n" +
"which(pizza, love)\n" +
"_subj(love, people)\n" +
"_predadj(pizza, healthy)\n" );
rc &= test_sentence ("The restaurant which belongs to my aunt is very famous.",
"_advmod(famous, very)\n" +
"to(belong, aunt)\n" +
"_subj(belong, restaurant)\n" +
"_poss(aunt, me)\n" +
"which(restaurant, belong)\n" +
"_predadj(restaurant, famous)\n");
rc &= test_sentence ("The books which I read in the library were written by Charles Dickens.",
"_obj(write, book)\n" +
"by(write, Charles_Dickens)\n" +
"_obj(read, book)\n" +
"in(read, library)\n" +
"_subj(read, I)\n" +
"which(book, read)\n");
rc &= test_sentence("This is the book whose author I met in a library.",
"_obj(be, book)\n" +
"_subj(be, this)\n" +
"_obj(meet, author)\n" +
"in(meet, library)\n" +
"_subj(meet, I)\n" +
"whose(book, author)\n");
rc &= test_sentence("The book that Jack lent me is very boring.",
"_advmod(boring, very)\n" +
"_iobj(lend, book)\n" +
"_obj(lend, me)\n" +
"_subj(lend, Jack)\n" +
"that_adj(book, lend)\n" +
"_predadj(book, boring)\n");
rc &= test_sentence("They ate a special curry which was recommended by the restaurant’s owner.",
"_obj(eat, curry)\n" +
"_subj(eat, they)\n" +
"_obj(recommend, curry)\n" +
"by(recommend, owner)\n" +
"_poss(owner, restaurant)\n" +
"which(curry, recommend)\n" +
"_amod(curry, special)\n");
rc &= test_sentence("The dog who Jack said chased me was black.",
"_obj(chase, me)\n" +
"_subj(chase, dog)\n" +
"_subj(say, Jack)\n" +
"_predadj(dog, black)\n" +
"who(dog, chase)\n");
rc &= test_sentence("Jack, who hosted the party, is my cousin.",
"_obj(be, cousin)\n" +
"_subj(be, Jack)\n" +
"_poss(cousin, me)\n" +
"_obj(host, party)\n" +
"_subj(host, Jack)\n" +
"who(Jack, host)\n");
rc &= test_sentence("Jack, whose name is in that book, is the student near the window.",
"near(be, window)\n" +
"_obj(be, student)\n" +
"_subj(be, Jack)\n" +
"_obj(near, window)\n" +
"_pobj(in, book)\n" +
"_psubj(in, name)\n" +
"_det(book, that)\n" +
"whose(Jack, name)\n");
rc &= test_sentence("Jack stopped the police car that was driving fast.",
"_obj(stop, car)\n" +
"_subj(stop, Jack)\n" +
"_advmod(drive, fast)\n" +
"_subj(drive, car)\n" +
"that_adj(car, drive)\n" +
"_nn(car, police)\n");
rc &= test_sentence("Just before the crossroads, the car was stopped by a traffic sign that stood on the street.",
"_obj(stop, car)\n" +
"by(stop, sign)\n" +
"_advmod(stop, just)\n" +
"on(stand, street)\n" +
"_subj(stand, sign)\n" +
"that_adj(sign, stand)\n" +
"_nn(sign, traffic)\n" +
"before(just, crossroads)\n");
report(rc, "Extrapostion");
return rc;
}
public static void main(String[] args)
{
TestRelEx ts = new TestRelEx();
boolean rc = true;
rc &= ts.test_comparatives();
rc &= ts.test_extraposition();
if (rc) {
System.err.println("Tested " + ts.pass + " sentences, test passed OK");
} else {
System.err.println("Test failed\n\t" +
ts.fail + " sentences failed\n\t" +
ts.pass + " sentences passed");
}
System.err.println("******************************");
System.err.println("Failed test sentences on Relex");
System.err.println("******************************");
if(sentfail.isEmpty())
System.err.println("All test sentences passed");
for(String temp : sentfail){
System.err.println(temp);
}
System.err.println("******************************\n");
}
}
| src/java_test/relex/test/TestRelEx.java | /*
* Copyright 2009 Linas Vepstas
*
* 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.
*/
package relex.test;
import java.util.ArrayList;
import java.util.Collections;
import relex.ParsedSentence;
import relex.RelationExtractor;
import relex.Sentence;
import relex.output.SimpleView;
public class TestRelEx
{
private RelationExtractor re;
private int pass;
private int fail;
private int subpass;
private int subfail;
private static ArrayList<String> sentfail= new ArrayList<String>();
public TestRelEx()
{
re = new RelationExtractor();
pass = 0;
fail = 0;
subpass = 0;
subfail = 0;
}
public ArrayList<String> split(String a)
{
String[] sa = a.split("\n");
ArrayList<String> saa = new ArrayList<String>();
for (String s : sa) {
saa.add(s);
}
Collections.sort (saa);
return saa;
}
/**
* First argument is the sentence.
* Second argument is a list of the relations that the
* Stanford parser generates.
* Return true if relex generates that same dependencies
* as the second argument.
*/
public boolean test_sentence (String sent, String sf)
{
re.do_penn_tagging = false;
Sentence sntc = re.processSentence(sent);
ParsedSentence parse = sntc.getParses().get(0);
String rs = SimpleView.printBinaryRelations(parse);
ArrayList<String> exp = split(sf);
ArrayList<String> got = split(rs);
if (exp.size() != got.size())
{
System.err.println("Error: size miscompare:\n" +
"\tExpected = " + exp + "\n" +
"\tGot = " + got + "\n" +
"\tSentence = " + sent);
subfail ++;
fail ++;
sentfail.add(sent);
return false;
}
for (int i=0; i< exp.size(); i++)
{
if (!exp.get(i).equals (got.get(i)))
{
System.err.println("Error: content miscompare:\n" +
"\tExpected = " + exp + "\n" +
"\tGot = " + got + "\n" +
"\tSentence = " + sent);
subfail ++;
fail ++;
sentfail.add(sent);
return false;
}
}
subpass ++;
pass ++;
return true;
}
public void report(boolean rc, String subsys)
{
if (rc) {
System.err.println(subsys + ": Tested " + pass + " sentences, test passed OK");
} else {
System.err.println(subsys + ": Test failed\n\t" +
fail + " sentences failed\n\t" +
pass + " sentences passed");
}
subpass = 0;
subfail = 0;
}
public boolean test_comparatives()
{
boolean rc = true;
rc &= test_sentence ("Some people like pigs less than dogs.",
"_advmod(like, less)\n" +
"_obj(like, pig)\n" +
"_quantity(people, some)\n" +
"_subj(like, people)\n" +
"than(pig, dog)\n");
rc &= test_sentence ("Some people like pigs more than dogs.",
"_advmod(like, more)\n" +
"_obj(like, pig)\n" +
"_quantity(people, some)\n" +
"_subj(like, people)\n" +
"than(pig, dog)\n");
report(rc, "Comparatives");
return rc;
}
public boolean test_extraposition()
{
boolean rc = true;
rc &= test_sentence ("The woman who lives next door is a registered nurse.",
"_obj(be, nurse)\n" +
"_subj(be, woman)\n" +
"_amod(nurse, registered)\n" +
"_advmod(live, next_door)\n" +
"_subj(live, woman)\n" +
"who(woman, live)\n");
rc &= test_sentence ("A player who is injured has to leave the field.",
"_to-do(have, leave)\n" +
"_subj(have, player)\n" +
"_obj(leave, field)\n" +
"_predadj(player, injured)\n" +
"who(player, injured)\n" );
rc &= test_sentence ("Pizza, which most people love, is not very healthy.",
"_advmod(very, not)\n" +
"_advmod(healthy, very)\n" +
"_obj(love, pizza)\n" +
"_quantity(people, most)\n" +
"which(pizza, love)\n" +
"_subj(love, people)\n" +
"_predadj(pizza, healthy)\n" );
rc &= test_sentence ("The restaurant which belongs to my aunt is very famous.",
"_advmod(famous, very)\n" +
"to(belong, aunt)\n" +
"_subj(belong, restaurant)\n" +
"_poss(aunt, me)\n" +
"which(restaurant, belong)\n" +
"_predadj(restaurant, famous)\n");
rc &= test_sentence ("The books which I read in the library were written by Charles Dickens.",
"_obj(write, book)\n" +
"by(write, Charles_Dickens)\n" +
"_obj(read, book)\n" +
"in(read, library)\n" +
"_subj(read, I)\n" +
"which(book, read)\n");
rc &= test_sentence("This is the book whose author I met in a library.",
"_obj(be, book)\n" +
"_subj(be, this)\n" +
"_obj(meet, author)\n" +
"in(meet, library)\n" +
"_subj(meet, I)\n" +
"whose(book, author)\n");
rc &= test_sentence("The book that Jack lent me is very boring.",
"_advmod(boring, very)\n" +
"_iobj(lend, book)\n" +
"_obj(lend, me)\n" +
"_subj(lend, Jack)\n" +
"that_adj(book, lend)\n" +
"_predadj(book, boring)\n");
rc &= test_sentence("They ate a special curry which was recommended by the restaurant’s owner.",
"_obj(eat, curry)\n" +
"_subj(eat, they)\n" +
"_obj(recommend, curry)\n" +
"by(recommend, owner)\n" +
"_poss(owner, restaurant)\n" +
"which(curry, recommend)\n" +
"_amod(curry, special)\n");
rc &= test_sentence("The dog who Jack said chased me was black.",
"_obj(chase, me)\n" +
"_subj(chase, dog)\n" +
"_subj(say, Jack)\n" +
"_predadj(dog, black)\n" +
"who(dog, chase)\n");
rc &= test_sentence("Jack, who hosted the party, is my cousin.",
"_obj(be, cousin)\n" +
"_subj(be, Jack)\n" +
"_poss(cousin, me)\n" +
"_obj(host, party)\n" +
"_subj(host, Jack)\n" +
"who(Jack, host)\n");
rc &= test_sentence("Jack, whose name is in that book, is the student near the window.",
"near(be, window)\n" +
"_obj(be, student)\n" +
"_subj(be, Jack)\n" +
"_obj(near, window)\n" +
"_pobj(in, book)\n" +
"_psubj(in, name)\n" +
"_det(book, that)\n" +
"whose(Jack, name)\n");
rc &= test_sentence("Jack stopped the police car that was driving fast.",
"_obj(stop, car)\n" +
"_subj(stop, Jack)\n" +
"_advmod(drive, fast)\n" +
"_subj(drive, car)\n" +
"that_adj(car, drive)\n" +
"_nn(car, police)\n");
rc &= test_sentence("Just before the crossroads, the car was stopped by a traffic sign that stood on the street.",
"_obj(stop, car)\n" +
"by(stop, sign)\n" +
"_advmod(stop, just)\n" +
"on(stand, street)\n" +
"_subj(stand, sign)\n" +
"that_adj(sign, stand)\n" +
"_nn(sign, traffic)\n" +
"before(just, crossroads)\n");
report(rc, "Extrapostion");
return rc;
}
public static void main(String[] args)
{
TestRelEx ts = new TestRelEx();
boolean rc = true;
rc &= ts.test_comparatives();
rc &= ts.test_extraposition();
if (rc) {
System.err.println("Tested " + ts.pass + " sentences, test passed OK");
} else {
System.err.println("Test failed\n\t" +
ts.fail + " sentences failed\n\t" +
ts.pass + " sentences passed");
}
System.err.println("******************************");
System.err.println("Failed test sentences on Relex");
System.err.println("******************************");
if(sentfail.isEmpty())
System.err.println("All test sentences passed");
for(String temp : sentfail){
System.err.println(temp);
}
System.err.println("******************************\n");
}
}
| Remove mention of stanford from this file.
| src/java_test/relex/test/TestRelEx.java | Remove mention of stanford from this file. | <ide><path>rc/java_test/relex/test/TestRelEx.java
<ide>
<ide> /**
<ide> * First argument is the sentence.
<del> * Second argument is a list of the relations that the
<del> * Stanford parser generates.
<del> * Return true if relex generates that same dependencies
<add> * Second argument is a list of the relations that RelEx
<add> * should be generating.
<add> * Return true if RelEx generates the same dependencies
<ide> * as the second argument.
<ide> */
<ide> public boolean test_sentence (String sent, String sf) |
|
Java | apache-2.0 | 1931b408b6a50e131705f2645d9e5890cd5d0c49 | 0 | SecUSo/privacy-friendly-shopping-list | package privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.dialog;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.R;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.context.AbstractInstanceFactory;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.context.InstanceFactory;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.utils.MessageUtils;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.utils.StringUtils;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.product.business.ProductService;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.product.business.domain.AutoCompleteLists;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.product.business.domain.ProductDto;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.camera.CameraActivity;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.ProductActivityCache;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.ProductsActivity;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.dialog.listeners.onFocusListener.ProductDialogFocusListener;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.dialog.listeners.price.PriceInputFilter;
import rx.Observable;
import java.io.File;
import java.util.Set;
import java.util.TreeSet;
import static android.app.Activity.RESULT_OK;
/**
* Created by Chris on 18.07.2016.
*/
public class ProductDialogFragment extends DialogFragment
{
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int MY_PERMISSIONS_REQUEST_USE_CAMERA = 2;
private static boolean opened;
private static boolean editDialog;
private static boolean resetState;
private static boolean saveConfirmed;
private ProductDto dto;
private ProductDialogCache dialogCache;
private ProductActivityCache cache;
private ProductService productService;
public static ProductDialogFragment newEditDialogInstance(ProductDto dto, ProductActivityCache cache)
{
editDialog = true;
ProductDialogFragment dialogFragment = getProductDialogFragment(dto, cache);
return dialogFragment;
}
public static ProductDialogFragment newAddDialogInstance(ProductDto dto, ProductActivityCache cache)
{
editDialog = false;
ProductDialogFragment dialogFragment = getProductDialogFragment(dto, cache);
return dialogFragment;
}
private static ProductDialogFragment getProductDialogFragment(ProductDto dto, ProductActivityCache cache)
{
ProductDialogFragment dialogFragment = new ProductDialogFragment();
dialogFragment.setCache(cache);
dialogFragment.setDto(dto);
return dialogFragment;
}
public void setCache(ProductActivityCache cache)
{
this.cache = cache;
}
public void setDto(ProductDto dto)
{
this.dto = dto;
}
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
opened = true; // flag to avoid opening this dialog twice
}
@Override
public void onDismiss(DialogInterface dialog)
{
super.onDismiss(dialog);
opened = false; // flag to avoid opening this dialog twice
if ( resetState && !saveConfirmed )
{
// if dto was implicitly saved because of taking a picture for the product, then delete the product
productService.deleteById(dto.getId())
.doOnCompleted(() ->
{
ProductsActivity productsActivity = (ProductsActivity) cache.getActivity();
productsActivity.updateListView();
resetState = false;
});
}
}
public static boolean isOpened()
{
return opened;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AbstractInstanceFactory instanceFactory = new InstanceFactory(cache.getActivity().getApplicationContext());
productService = (ProductService) instanceFactory.createInstance(ProductService.class);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.product_dialog, null);
dialogCache = new ProductDialogCache(v);
dialogCache.getExpandableLayout().setVisibility(View.GONE);
dialogCache.getProductName().setText(dto.getProductName());
dialogCache.getProductNotes().setText(dto.getProductNotes());
dialogCache.getQuantity().setText(dto.getQuantity());
dialogCache.getPrice().setText(dto.getProductPrice());
dialogCache.getCategory().setText(dto.getProductCategory());
dialogCache.getCustomStore().setText(dto.getProductStore());
dialogCache.getProductCheckBox().setChecked(dto.isChecked());
PackageManager pm = getContext().getPackageManager();
if ( !pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) )
{
dialogCache.getCameraIcon().setVisibility(View.GONE);
dialogCache.getProductImage().setVisibility(View.GONE);
}
if ( editDialog )
{
dialogCache.getTitleTextView().setText(getActivity().getResources().getString(R.string.product_name_edit));
dialogCache.getProductImage().setImageBitmap(dto.getThumbnailBitmap());
dialogCache.getProductCheckBox().setVisibility(View.VISIBLE);
}
else
{
dialogCache.getTitleTextView().setText(getActivity().getResources().getString(R.string.product_name_new));
Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ic_menu_camera);
dialogCache.getProductImage().setImageBitmap(bitmap);
dialogCache.getProductCheckBox().setVisibility(View.GONE);
}
dialogCache.getButtonPlus().setOnClickListener(new View.OnClickListener()
{
int value;
String newQuantity;
@Override
public void onClick(View view)
{
if ( !StringUtils.isEmpty(String.valueOf(dialogCache.getQuantity().getText())) )
{
value = Integer.parseInt(String.valueOf(dialogCache.getQuantity().getText()));
value++;
newQuantity = String.valueOf(value);
dialogCache.getQuantity().setText(newQuantity);
}
else
{
dialogCache.getQuantity().setText("1");
}
}
});
dialogCache.getButtonMinus().setOnClickListener(new View.OnClickListener()
{
int value;
String newQuantity;
@Override
public void onClick(View view)
{
value = Integer.parseInt(String.valueOf(dialogCache.getQuantity().getText()));
if ( value > 0 )
{
value--;
newQuantity = String.valueOf(value);
dialogCache.getQuantity().setText(newQuantity);
}
}
});
dialogCache.getExpandableImageView().setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
if ( dialogCache.getExpandableLayout().getVisibility() == View.GONE )
{
changePhotoThumbnailVisibility(R.drawable.ic_keyboard_arrow_up_white_48dp, View.VISIBLE);
}
else
{
changePhotoThumbnailVisibility(R.drawable.ic_keyboard_arrow_down_white_48dp, View.GONE);
}
}
});
dialogCache.getCameraIcon().setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
int permissionCheck = ContextCompat.checkSelfPermission(cache.getActivity(), Manifest.permission.CAMERA);
if ( permissionCheck == PackageManager.PERMISSION_GRANTED )
{
startImageCaptureAction();
}
else
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_USE_CAMERA);
}
}
});
dialogCache.getPrice().setFilters(new InputFilter[]{new PriceInputFilter(dialogCache)});
dialogCache.getProductNotes().setOnFocusChangeListener(new ProductDialogFocusListener(dialogCache));
dialogCache.getProductName().setOnFocusChangeListener(new ProductDialogFocusListener(dialogCache));
Observable<AutoCompleteLists> rxAutoCompleteLists = productService.getAutoCompleteListsObservable();
AutoCompleteLists autoCompleteLists = new AutoCompleteLists();
rxAutoCompleteLists
.doOnNext(result -> result.copyTo(autoCompleteLists))
.doOnCompleted(() -> setupAutoCompleteLists(autoCompleteLists))
.subscribe();
Set<String> productNames = new TreeSet<>();
productService.getAllProducts(cache.getListId())
.map(dto -> dto.getProductName())
.doOnNext(name -> productNames.add(name))
.subscribe();
dialogCache.getQuantity().setOnFocusChangeListener(new ProductDialogFocusListener(dialogCache));
dialogCache.getPrice().setOnFocusChangeListener(new ProductDialogFocusListener(dialogCache));
dialogCache.getProductImage().setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if ( !dto.isDefaultImage() && !dialogCache.isImageScheduledForDeletion() )
{
if ( !ImageViewerDialog.isOpened() )
{
DialogFragment imageViewerDialog = ImageViewerDialog.newInstance(dto, dialogCache);
imageViewerDialog.show(cache.getActivity().getSupportFragmentManager(), "ProductViewer");
}
}
}
});
builder.setPositiveButton(cache.getActivity().getResources().getString(R.string.okay), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
}
});
builder.setNegativeButton(cache.getActivity().getResources().getString(R.string.cancel), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
}
});
builder.setView(v);
AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
String productName = String.valueOf(dialogCache.getProductName().getText());
if ( StringUtils.isEmpty(productName) )
{
MessageUtils.showToast(getActivity().getApplicationContext(), R.string.alert_missing_product_name, Toast.LENGTH_LONG);
}
else
{
saveConfirmed = true;
saveUserInput(productName);
productService.saveOrUpdate(dto, cache.getListId())
.doOnCompleted(() ->
{
ProductsActivity productsActivity = (ProductsActivity) cache.getActivity();
productsActivity.updateListView();
})
.subscribe();
dialog.dismiss();
}
}
});
if ( !editDialog )
{
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
dialogCache.getProductNameInputLayout().setError(null);
dialogCache.getProductName().addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s)
{
if ( productNames.contains(s.toString()) )
{
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
dialogCache.getProductNameInputLayout().setError(getContext().getString(R.string.product_already_exists));
}
else
{
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);
dialogCache.getProductNameInputLayout().setError(null);
}
}
});
return dialog;
}
private void changePhotoThumbnailVisibility(int ic_keyboard_arrow_up_white_48dp, int visible)
{
dialogCache.getExpandableImageView().setImageResource(ic_keyboard_arrow_up_white_48dp);
dialogCache.getExpandableLayout().setVisibility(visible);
}
private void saveUserInput(String productName)
{
dto.setProductName(productName);
dto.setProductNotes(String.valueOf(dialogCache.getProductNotes().getText()));
dto.setQuantity(String.valueOf(dialogCache.getQuantity().getText()));
dto.setProductPrice(String.valueOf(dialogCache.getPrice().getText()));
dto.setProductCategory(String.valueOf(dialogCache.getCategory().getText()));
dto.setProductStore(String.valueOf(dialogCache.getCustomStore().getText()));
dto.setChecked(dialogCache.getProductCheckBox().isChecked());
if ( dialogCache.isImageScheduledForDeletion() )
{
Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ic_menu_camera);
File imageFile = new File(productService.getProductImagePath(dto.getId()));
imageFile.delete();
dto.setThumbnailBitmap(bitmap);
dto.setDefaultImage(true);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if ( requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK )
{
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get(CameraActivity.THUMBNAIL_KEY);
dialogCache.getProductImage().setImageBitmap(imageBitmap);
dto.setThumbnailBitmap(imageBitmap);
dto.setDefaultImage(false);
changePhotoThumbnailVisibility(R.drawable.ic_keyboard_arrow_up_white_48dp, View.VISIBLE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
switch ( requestCode )
{
case MY_PERMISSIONS_REQUEST_USE_CAMERA:
{
if ( grantResults.length > 0
&& grantResults[ 0 ] == PackageManager.PERMISSION_GRANTED )
{
startImageCaptureAction();
}
return;
}
}
}
private void startImageCaptureAction()
{
// dto must be saved first in order to have an id.
// id is needed to generate a unique file name for the image
String productName = String.valueOf(dialogCache.getProductName().getText());
if ( StringUtils.isEmpty(productName) )
{
String newProductName = getResources().getString(R.string.new_product);
productName = newProductName;
}
boolean newProductAdded = dto.getId() == null;
resetState = true && newProductAdded;
saveUserInput(productName);
productService.saveOrUpdate(dto, cache.getListId()).subscribe();
saveConfirmed = false;
dialogCache.setImageScheduledForDeletion(false);
Intent takePictureIntent = new Intent(cache.getActivity(), CameraActivity.class);
takePictureIntent.putExtra(ProductsActivity.PRODUCT_ID_KEY, dto.getId());
takePictureIntent.putExtra(ProductsActivity.PRODUCT_NAME, dto.getProductName());
this.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
private void setupAutoCompleteLists(AutoCompleteLists autoCompleteLists)
{
String[] productsArray = autoCompleteLists.getProductsArray();
ArrayAdapter<String> productNamesAdapter = new ArrayAdapter<>(getActivity(), R.layout.pfa_lists, productsArray);
dialogCache.getProductName().setAdapter(productNamesAdapter);
String[] storesArray = autoCompleteLists.getStoresArray();
ArrayAdapter<String> storesAdapter = new ArrayAdapter<>(getActivity(), R.layout.pfa_lists, storesArray);
dialogCache.getCustomStore().setAdapter(storesAdapter);
String[] categoryArray = autoCompleteLists.getCategoryArray();
ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(getActivity(), R.layout.pfa_lists, categoryArray);
dialogCache.getCategory().setAdapter(categoryAdapter);
}
}
| app/src/main/java/privacyfriendlyshoppinglist/secuso/org/privacyfriendlyshoppinglist/ui/products/dialog/ProductDialogFragment.java | package privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.dialog;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.R;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.context.AbstractInstanceFactory;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.context.InstanceFactory;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.utils.MessageUtils;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.framework.utils.StringUtils;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.product.business.ProductService;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.product.business.domain.AutoCompleteLists;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.logic.product.business.domain.ProductDto;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.camera.CameraActivity;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.ProductActivityCache;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.ProductsActivity;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.dialog.listeners.onFocusListener.ProductDialogFocusListener;
import privacyfriendlyshoppinglist.secuso.org.privacyfriendlyshoppinglist.ui.products.dialog.listeners.price.PriceInputFilter;
import rx.Observable;
import java.io.File;
import java.util.Set;
import java.util.TreeSet;
import static android.app.Activity.RESULT_OK;
/**
* Created by Chris on 18.07.2016.
*/
public class ProductDialogFragment extends DialogFragment
{
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int MY_PERMISSIONS_REQUEST_USE_CAMERA = 2;
private static boolean opened;
private static boolean editDialog;
private static boolean resetState;
private static boolean saveConfirmed;
private ProductDto dto;
private ProductDialogCache dialogCache;
private ProductActivityCache cache;
private ProductService productService;
public static ProductDialogFragment newEditDialogInstance(ProductDto dto, ProductActivityCache cache)
{
editDialog = true;
ProductDialogFragment dialogFragment = getProductDialogFragment(dto, cache);
return dialogFragment;
}
public static ProductDialogFragment newAddDialogInstance(ProductDto dto, ProductActivityCache cache)
{
editDialog = false;
ProductDialogFragment dialogFragment = getProductDialogFragment(dto, cache);
return dialogFragment;
}
private static ProductDialogFragment getProductDialogFragment(ProductDto dto, ProductActivityCache cache)
{
ProductDialogFragment dialogFragment = new ProductDialogFragment();
dialogFragment.setCache(cache);
dialogFragment.setDto(dto);
return dialogFragment;
}
public void setCache(ProductActivityCache cache)
{
this.cache = cache;
}
public void setDto(ProductDto dto)
{
this.dto = dto;
}
@Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
opened = true; // flag to avoid opening this dialog twice
}
@Override
public void onDismiss(DialogInterface dialog)
{
super.onDismiss(dialog);
opened = false; // flag to avoid opening this dialog twice
if ( resetState && !saveConfirmed )
{
// if dto was implicitly saved because of taking a picture for the product, then delete the product
productService.deleteById(dto.getId())
.doOnCompleted(() ->
{
ProductsActivity productsActivity = (ProductsActivity) cache.getActivity();
productsActivity.updateListView();
resetState = false;
});
}
}
public static boolean isOpened()
{
return opened;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AbstractInstanceFactory instanceFactory = new InstanceFactory(cache.getActivity().getApplicationContext());
productService = (ProductService) instanceFactory.createInstance(ProductService.class);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.product_dialog, null);
dialogCache = new ProductDialogCache(v);
dialogCache.getExpandableLayout().setVisibility(View.GONE);
dialogCache.getProductName().setText(dto.getProductName());
dialogCache.getProductNotes().setText(dto.getProductNotes());
dialogCache.getQuantity().setText(dto.getQuantity());
dialogCache.getPrice().setText(dto.getProductPrice());
dialogCache.getCategory().setText(dto.getProductCategory());
dialogCache.getCustomStore().setText(dto.getProductStore());
dialogCache.getProductCheckBox().setChecked(dto.isChecked());
PackageManager pm = getContext().getPackageManager();
if ( !pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) )
{
dialogCache.getCameraIcon().setVisibility(View.GONE);
dialogCache.getProductImage().setVisibility(View.GONE);
}
if ( editDialog )
{
dialogCache.getTitleTextView().setText(getActivity().getResources().getString(R.string.product_name_edit));
dialogCache.getProductImage().setImageBitmap(dto.getThumbnailBitmap());
dialogCache.getProductCheckBox().setVisibility(View.VISIBLE);
}
else
{
dialogCache.getTitleTextView().setText(getActivity().getResources().getString(R.string.product_name_new));
Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ic_menu_camera);
dialogCache.getProductImage().setImageBitmap(bitmap);
dialogCache.getProductCheckBox().setVisibility(View.GONE);
}
dialogCache.getButtonPlus().setOnClickListener(new View.OnClickListener()
{
int value;
String newQuantity;
@Override
public void onClick(View view)
{
if ( !StringUtils.isEmpty(String.valueOf(dialogCache.getQuantity().getText())) )
{
value = Integer.parseInt(String.valueOf(dialogCache.getQuantity().getText()));
value++;
newQuantity = String.valueOf(value);
dialogCache.getQuantity().setText(newQuantity);
}
else
{
dialogCache.getQuantity().setText("1");
}
}
});
dialogCache.getButtonMinus().setOnClickListener(new View.OnClickListener()
{
int value;
String newQuantity;
@Override
public void onClick(View view)
{
value = Integer.parseInt(String.valueOf(dialogCache.getQuantity().getText()));
if ( value > 0 )
{
value--;
newQuantity = String.valueOf(value);
dialogCache.getQuantity().setText(newQuantity);
}
}
});
dialogCache.getExpandableImageView().setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
if ( dialogCache.getExpandableLayout().getVisibility() == View.GONE )
{
dialogCache.getExpandableImageView().setImageResource(R.drawable.ic_keyboard_arrow_up_white_48dp);
dialogCache.getExpandableLayout().setVisibility(View.VISIBLE);
}
else
{
dialogCache.getExpandableImageView().setImageResource(R.drawable.ic_keyboard_arrow_down_white_48dp);
dialogCache.getExpandableLayout().setVisibility(View.GONE);
}
}
});
dialogCache.getCameraIcon().setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
int permissionCheck = ContextCompat.checkSelfPermission(cache.getActivity(), Manifest.permission.CAMERA);
if ( permissionCheck == PackageManager.PERMISSION_GRANTED )
{
startImageCaptureAction();
}
else
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_USE_CAMERA);
}
}
});
dialogCache.getPrice().setFilters(new InputFilter[]{new PriceInputFilter(dialogCache)});
dialogCache.getProductNotes().setOnFocusChangeListener(new ProductDialogFocusListener(dialogCache));
dialogCache.getProductName().setOnFocusChangeListener(new ProductDialogFocusListener(dialogCache));
Observable<AutoCompleteLists> rxAutoCompleteLists = productService.getAutoCompleteListsObservable();
AutoCompleteLists autoCompleteLists = new AutoCompleteLists();
rxAutoCompleteLists
.doOnNext(result -> result.copyTo(autoCompleteLists))
.doOnCompleted(() -> setupAutoCompleteLists(autoCompleteLists))
.subscribe();
Set<String> productNames = new TreeSet<>();
productService.getAllProducts(cache.getListId())
.map(dto -> dto.getProductName())
.doOnNext(name -> productNames.add(name))
.subscribe();
dialogCache.getQuantity().setOnFocusChangeListener(new ProductDialogFocusListener(dialogCache));
dialogCache.getPrice().setOnFocusChangeListener(new ProductDialogFocusListener(dialogCache));
dialogCache.getProductImage().setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if ( !dto.isDefaultImage() && !dialogCache.isImageScheduledForDeletion() )
{
if ( !ImageViewerDialog.isOpened() )
{
DialogFragment imageViewerDialog = ImageViewerDialog.newInstance(dto, dialogCache);
imageViewerDialog.show(cache.getActivity().getSupportFragmentManager(), "ProductViewer");
}
}
}
});
builder.setPositiveButton(cache.getActivity().getResources().getString(R.string.okay), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
}
});
builder.setNegativeButton(cache.getActivity().getResources().getString(R.string.cancel), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
}
});
builder.setView(v);
AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
String productName = String.valueOf(dialogCache.getProductName().getText());
if ( StringUtils.isEmpty(productName) )
{
MessageUtils.showToast(getActivity().getApplicationContext(), R.string.alert_missing_product_name, Toast.LENGTH_LONG);
}
else
{
saveConfirmed = true;
saveUserInput(productName);
productService.saveOrUpdate(dto, cache.getListId())
.doOnCompleted(() ->
{
ProductsActivity productsActivity = (ProductsActivity) cache.getActivity();
productsActivity.updateListView();
})
.subscribe();
dialog.dismiss();
}
}
});
if ( !editDialog )
{
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
dialogCache.getProductNameInputLayout().setError(null);
dialogCache.getProductName().addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
@Override
public void afterTextChanged(Editable s)
{
if ( productNames.contains(s.toString()) )
{
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
dialogCache.getProductNameInputLayout().setError(getContext().getString(R.string.product_already_exists));
}
else
{
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);
dialogCache.getProductNameInputLayout().setError(null);
}
}
});
return dialog;
}
private void saveUserInput(String productName)
{
dto.setProductName(productName);
dto.setProductNotes(String.valueOf(dialogCache.getProductNotes().getText()));
dto.setQuantity(String.valueOf(dialogCache.getQuantity().getText()));
dto.setProductPrice(String.valueOf(dialogCache.getPrice().getText()));
dto.setProductCategory(String.valueOf(dialogCache.getCategory().getText()));
dto.setProductStore(String.valueOf(dialogCache.getCustomStore().getText()));
dto.setChecked(dialogCache.getProductCheckBox().isChecked());
if ( dialogCache.isImageScheduledForDeletion() )
{
Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.ic_menu_camera);
File imageFile = new File(productService.getProductImagePath(dto.getId()));
imageFile.delete();
dto.setThumbnailBitmap(bitmap);
dto.setDefaultImage(true);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if ( requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK )
{
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get(CameraActivity.THUMBNAIL_KEY);
dialogCache.getProductImage().setImageBitmap(imageBitmap);
dto.setThumbnailBitmap(imageBitmap);
dto.setDefaultImage(false);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
switch ( requestCode )
{
case MY_PERMISSIONS_REQUEST_USE_CAMERA:
{
if ( grantResults.length > 0
&& grantResults[ 0 ] == PackageManager.PERMISSION_GRANTED )
{
startImageCaptureAction();
}
return;
}
}
}
private void startImageCaptureAction()
{
// dto must be saved first in order to have an id.
// id is needed to generate a unique file name for the image
String productName = String.valueOf(dialogCache.getProductName().getText());
if ( StringUtils.isEmpty(productName) )
{
String newProductName = getResources().getString(R.string.new_product);
productName = newProductName;
}
boolean newProductAdded = dto.getId() == null;
resetState = true && newProductAdded;
saveUserInput(productName);
productService.saveOrUpdate(dto, cache.getListId()).subscribe();
saveConfirmed = false;
dialogCache.setImageScheduledForDeletion(false);
Intent takePictureIntent = new Intent(cache.getActivity(), CameraActivity.class);
takePictureIntent.putExtra(ProductsActivity.PRODUCT_ID_KEY, dto.getId());
takePictureIntent.putExtra(ProductsActivity.PRODUCT_NAME, dto.getProductName());
this.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
private void setupAutoCompleteLists(AutoCompleteLists autoCompleteLists)
{
String[] productsArray = autoCompleteLists.getProductsArray();
ArrayAdapter<String> productNamesAdapter = new ArrayAdapter<>(getActivity(), R.layout.pfa_lists, productsArray);
dialogCache.getProductName().setAdapter(productNamesAdapter);
String[] storesArray = autoCompleteLists.getStoresArray();
ArrayAdapter<String> storesAdapter = new ArrayAdapter<>(getActivity(), R.layout.pfa_lists, storesArray);
dialogCache.getCustomStore().setAdapter(storesAdapter);
String[] categoryArray = autoCompleteLists.getCategoryArray();
ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(getActivity(), R.layout.pfa_lists, categoryArray);
dialogCache.getCategory().setAdapter(categoryAdapter);
}
}
| Feedback. Bugs 8 fixed
| app/src/main/java/privacyfriendlyshoppinglist/secuso/org/privacyfriendlyshoppinglist/ui/products/dialog/ProductDialogFragment.java | Feedback. Bugs 8 fixed | <ide><path>pp/src/main/java/privacyfriendlyshoppinglist/secuso/org/privacyfriendlyshoppinglist/ui/products/dialog/ProductDialogFragment.java
<ide> {
<ide> if ( dialogCache.getExpandableLayout().getVisibility() == View.GONE )
<ide> {
<del> dialogCache.getExpandableImageView().setImageResource(R.drawable.ic_keyboard_arrow_up_white_48dp);
<del> dialogCache.getExpandableLayout().setVisibility(View.VISIBLE);
<add> changePhotoThumbnailVisibility(R.drawable.ic_keyboard_arrow_up_white_48dp, View.VISIBLE);
<ide> }
<ide> else
<ide> {
<del> dialogCache.getExpandableImageView().setImageResource(R.drawable.ic_keyboard_arrow_down_white_48dp);
<del> dialogCache.getExpandableLayout().setVisibility(View.GONE);
<add> changePhotoThumbnailVisibility(R.drawable.ic_keyboard_arrow_down_white_48dp, View.GONE);
<ide> }
<ide> }
<ide> });
<ide> return dialog;
<ide> }
<ide>
<add> private void changePhotoThumbnailVisibility(int ic_keyboard_arrow_up_white_48dp, int visible)
<add> {
<add> dialogCache.getExpandableImageView().setImageResource(ic_keyboard_arrow_up_white_48dp);
<add> dialogCache.getExpandableLayout().setVisibility(visible);
<add> }
<add>
<ide> private void saveUserInput(String productName)
<ide> {
<ide> dto.setProductName(productName);
<ide> dialogCache.getProductImage().setImageBitmap(imageBitmap);
<ide> dto.setThumbnailBitmap(imageBitmap);
<ide> dto.setDefaultImage(false);
<add> changePhotoThumbnailVisibility(R.drawable.ic_keyboard_arrow_up_white_48dp, View.VISIBLE);
<ide> }
<ide> }
<ide> |
|
Java | mpl-2.0 | 4a17567c631c8509c0573c1b559138f63d1e4d32 | 0 | msteinhoff/hello-world | c66c012e-cb8e-11e5-9140-00264a111016 | src/main/java/HelloWorld.java | c65ddc8f-cb8e-11e5-ad43-00264a111016 | Initial commit.13 | src/main/java/HelloWorld.java | Initial commit.13 | <ide><path>rc/main/java/HelloWorld.java
<del>c65ddc8f-cb8e-11e5-ad43-00264a111016
<add>c66c012e-cb8e-11e5-9140-00264a111016 |
|
Java | apache-2.0 | 899da6fb0a0895a5945f9d40fc76023d50d30427 | 0 | bazaarvoice/curator-extensions | package com.bazaarvoice.zookeeper.dropwizard;
import com.bazaarvoice.zookeeper.ZooKeeperConnection;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class ManagedZooKeeperConnectionTest {
@Test(expected = NullPointerException.class)
public void testNullConnection() {
new ManagedZooKeeperConnection(null);
}
@Test
public void testClosesOnStop() throws Exception {
ZooKeeperConnection zookeeper = mock(ZooKeeperConnection.class);
ManagedZooKeeperConnection managed = new ManagedZooKeeperConnection(zookeeper);
managed.stop();
verify(zookeeper).close();
}
}
| dropwizard/src/test/java/com/bazaarvoice/zookeeper/dropwizard/ManagedZooKeeperConnectionTest.java | package com.bazaarvoice.zookeeper.dropwizard;
import com.bazaarvoice.zookeeper.ZooKeeperConnection;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class ManagedZooKeeperConnectionTest {
@Test
public void testClosesOnStop() throws Exception {
ZooKeeperConnection zookeeper = mock(ZooKeeperConnection.class);
ManagedZooKeeperConnection managed = new ManagedZooKeeperConnection(zookeeper);
managed.stop();
verify(zookeeper).close();
}
}
| Add test for null connection.
| dropwizard/src/test/java/com/bazaarvoice/zookeeper/dropwizard/ManagedZooKeeperConnectionTest.java | Add test for null connection. | <ide><path>ropwizard/src/test/java/com/bazaarvoice/zookeeper/dropwizard/ManagedZooKeeperConnectionTest.java
<ide> import static org.mockito.Mockito.verify;
<ide>
<ide> public class ManagedZooKeeperConnectionTest {
<add> @Test(expected = NullPointerException.class)
<add> public void testNullConnection() {
<add> new ManagedZooKeeperConnection(null);
<add> }
<add>
<ide> @Test
<ide> public void testClosesOnStop() throws Exception {
<ide> ZooKeeperConnection zookeeper = mock(ZooKeeperConnection.class); |
|
Java | apache-2.0 | d279ebc865b73e21158c9c98ebc148c4b8c2b207 | 0 | apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata,apache/airavata | /**
*
* 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.
*/
package org.apache.airavata.api.server.handler;
import org.apache.airavata.accountprovisioning.ConfigParam;
import org.apache.airavata.accountprovisioning.SSHAccountManager;
import org.apache.airavata.accountprovisioning.SSHAccountProvisionerFactory;
import org.apache.airavata.accountprovisioning.SSHAccountProvisionerProvider;
import org.apache.airavata.api.Airavata;
import org.apache.airavata.api.airavata_apiConstants;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.Constants;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.credential.store.cpi.CredentialStoreService;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.messaging.core.Type;
import org.apache.airavata.model.WorkflowModel;
import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisioner;
import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisionerConfigParam;
import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisionerConfigParamType;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule;
import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.appcatalog.gatewaygroups.GatewayGroups;
import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference;
import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile;
import org.apache.airavata.model.appcatalog.gatewayprofile.StoragePreference;
import org.apache.airavata.model.appcatalog.groupresourceprofile.BatchQueueResourcePolicy;
import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile;
import org.apache.airavata.model.appcatalog.storageresource.StorageResourceDescription;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserResourceProfile;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserStoragePreference;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.model.commons.airavata_commonsConstants;
import org.apache.airavata.model.credential.store.*;
import org.apache.airavata.model.data.movement.DMType;
import org.apache.airavata.model.data.movement.*;
import org.apache.airavata.model.data.replica.DataProductModel;
import org.apache.airavata.model.data.replica.DataReplicaLocationModel;
import org.apache.airavata.model.error.*;
import org.apache.airavata.model.experiment.*;
import org.apache.airavata.model.group.ResourcePermissionType;
import org.apache.airavata.model.group.ResourceType;
import org.apache.airavata.model.job.JobModel;
import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent;
import org.apache.airavata.model.messaging.event.ExperimentSubmitEvent;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.security.AuthzToken;
import org.apache.airavata.model.status.ExperimentState;
import org.apache.airavata.model.status.ExperimentStatus;
import org.apache.airavata.model.status.JobStatus;
import org.apache.airavata.model.status.QueueStatusModel;
import org.apache.airavata.model.workspace.Gateway;
import org.apache.airavata.model.workspace.Notification;
import org.apache.airavata.model.workspace.Project;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.airavata.service.security.interceptor.SecurityCheck;
import org.apache.airavata.sharing.registry.models.*;
import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class AiravataServerHandler implements Airavata.Iface {
private static final Logger logger = LoggerFactory.getLogger(AiravataServerHandler.class);
private Publisher statusPublisher;
private Publisher experimentPublisher;
private ThriftClientPool<SharingRegistryService.Client> sharingClientPool;
private ThriftClientPool<RegistryService.Client> registryClientPool;
private ThriftClientPool<CredentialStoreService.Client> csClientPool;
public AiravataServerHandler() {
try {
statusPublisher = MessagingFactory.getPublisher(Type.STATUS);
experimentPublisher = MessagingFactory.getPublisher(Type.EXPERIMENT_LAUNCH);
GenericObjectPool.Config poolConfig = new GenericObjectPool.Config();
poolConfig.maxActive = 100;
poolConfig.minIdle = 5;
poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
poolConfig.testOnBorrow = true;
poolConfig.testWhileIdle = true;
poolConfig.numTestsPerEvictionRun = 10;
poolConfig.maxWait = 3000;
sharingClientPool = new ThriftClientPool<>(
tProtocol -> new SharingRegistryService.Client(tProtocol), poolConfig, ServerSettings.getSharingRegistryHost(),
Integer.parseInt(ServerSettings.getSharingRegistryPort()));
registryClientPool = new ThriftClientPool<>(
tProtocol -> new RegistryService.Client(tProtocol), poolConfig, ServerSettings.getRegistryServerHost(),
Integer.parseInt(ServerSettings.getRegistryServerPort()));
csClientPool = new ThriftClientPool<>(
tProtocol -> new CredentialStoreService.Client(tProtocol), poolConfig, ServerSettings.getCredentialStoreServerHost(),
Integer.parseInt(ServerSettings.getCredentialStoreServerPort()));
initSharingRegistry();
postInitDefaultGateway();
} catch (ApplicationSettingsException e) {
logger.error("Error occured while reading airavata-server properties..", e);
} catch (AiravataException e) {
logger.error("Error occured while reading airavata-server properties..", e);
} catch (TException e) {
logger.error("Error occured while reading airavata-server properties..", e);
}
}
/**
* This method creates a password token for the default gateway profile. Default gateway is originally initialized
* at the registry server but we can not add the password token at that step as the credential store is not initialized
* before registry server.
*/
private void postInitDefaultGateway() {
RegistryService.Client registryClient = registryClientPool.getResource();
try {
GatewayResourceProfile gatewayResourceProfile = registryClient.getGatewayResourceProfile(ServerSettings.getDefaultUserGateway());
if (gatewayResourceProfile != null && gatewayResourceProfile.getCredentialStoreToken() == null) {
logger.debug("Starting to add the password credential for default gateway : " +
ServerSettings.getDefaultUserGateway());
PasswordCredential passwordCredential = new PasswordCredential();
passwordCredential.setPortalUserName(ServerSettings.getDefaultUser());
passwordCredential.setGatewayId(ServerSettings.getDefaultUserGateway());
passwordCredential.setLoginUserName(ServerSettings.getDefaultUser());
passwordCredential.setPassword(ServerSettings.getDefaultUserPassword());
passwordCredential.setDescription("Credentials for default gateway");
CredentialStoreService.Client csClient = csClientPool.getResource();
String token = null;
try {
logger.info("Creating password credential for default gateway");
token = csClient.addPasswordCredential(passwordCredential);
csClientPool.returnResource(csClient);
} catch (Exception ex) {
logger.error("Failed to create the password credential for the default gateway : " +
ServerSettings.getDefaultUserGateway(), ex);
if (csClient != null) {
csClientPool.returnBrokenResource(csClient);
}
}
if (token != null) {
logger.debug("Adding password credential token " + token +" to the default gateway : " + ServerSettings.getDefaultUserGateway());
gatewayResourceProfile.setIdentityServerPwdCredToken(token);
registryClient.updateGatewayResourceProfile(ServerSettings.getDefaultUserGateway(), gatewayResourceProfile);
}
registryClientPool.returnResource(registryClient);
}
} catch (Exception e) {
logger.error("Failed to add the password credentials for the default gateway", e);
if (registryClient != null) {
registryClientPool.returnBrokenResource(registryClient);
}
}
}
private void initSharingRegistry() throws ApplicationSettingsException, TException {
SharingRegistryService.Client client = sharingClientPool.getResource();
try {
if (!client.isDomainExists(ServerSettings.getDefaultUserGateway())) {
Domain domain = new Domain();
domain.setDomainId(ServerSettings.getDefaultUserGateway());
domain.setName(ServerSettings.getDefaultUserGateway());
domain.setDescription("Domain entry for " + domain.name);
client.createDomain(domain);
User user = new User();
user.setDomainId(domain.domainId);
user.setUserId(ServerSettings.getDefaultUser() + "@" + ServerSettings.getDefaultUserGateway());
user.setUserName(ServerSettings.getDefaultUser());
client.createUser(user);
//Creating Entity Types for each domain
EntityType entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId + ":PROJECT");
entityType.setDomainId(domain.domainId);
entityType.setName("PROJECT");
entityType.setDescription("Project entity type");
client.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId + ":EXPERIMENT");
entityType.setDomainId(domain.domainId);
entityType.setName("EXPERIMENT");
entityType.setDescription("Experiment entity type");
client.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId + ":FILE");
entityType.setDomainId(domain.domainId);
entityType.setName("FILE");
entityType.setDescription("File entity type");
client.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":"+ResourceType.APPLICATION_DEPLOYMENT.name());
entityType.setDomainId(domain.domainId);
entityType.setName("APPLICATION-DEPLOYMENT");
entityType.setDescription("Application Deployment entity type");
client.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":"+ResourceType.GROUP_RESOURCE_PROFILE.name());
entityType.setDomainId(domain.domainId);
entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name());
entityType.setDescription("Group Resource Profile entity type");
client.createEntityType(entityType);
//Creating Permission Types for each domain
PermissionType permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId + ":READ");
permissionType.setDomainId(domain.domainId);
permissionType.setName("READ");
permissionType.setDescription("Read permission type");
client.createPermissionType(permissionType);
permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId + ":WRITE");
permissionType.setDomainId(domain.domainId);
permissionType.setName("WRITE");
permissionType.setDescription("Write permission type");
client.createPermissionType(permissionType);
permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId+":EXEC");
permissionType.setDomainId(domain.domainId);
permissionType.setName("EXEC");
permissionType.setDescription("Execute permission type");
client.createPermissionType(permissionType);
}
sharingClientPool.returnResource(client);
} catch (Exception ex) {
sharingClientPool.returnBrokenResource(client);
throw ex;
}
}
/**
* Query Airavata to fetch the API version
*/
@Override
@SecurityCheck
public String getAPIVersion(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException,
AiravataSystemException, AuthorizationException, TException {
return airavata_apiConstants.AIRAVATA_API_VERSION;
}
/**
* Verify if User Exists within Airavata.
*
* @param authzToken
* @param gatewayId
* @param userName
* @return true/false
*/
@Override
public boolean isUserExists(AuthzToken authzToken, String gatewayId, String userName) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client client = registryClientPool.getResource();
try {
boolean isExists = client.isUserExists(gatewayId, userName);
registryClientPool.returnResource(client);
return isExists;
} catch (Exception e) {
logger.error("Error while verifying user", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while verifying user. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(client);
throw exception;
}
}
@Override
@SecurityCheck
public String addGateway(AuthzToken authzToken, Gateway gateway) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
RegistryService.Client registryClient = registryClientPool.getResource();
try {
String gatewayId = registryClient.addGateway(gateway);
Domain domain = new Domain();
domain.setDomainId(gateway.getGatewayId());
domain.setName(gateway.getGatewayName());
domain.setDescription("Domain entry for " + domain.name);
sharingClient.createDomain(domain);
//Creating Entity Types for each domain
EntityType entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":PROJECT");
entityType.setDomainId(domain.domainId);
entityType.setName("PROJECT");
entityType.setDescription("Project entity type");
sharingClient.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":EXPERIMENT");
entityType.setDomainId(domain.domainId);
entityType.setName("EXPERIMENT");
entityType.setDescription("Experiment entity type");
sharingClient.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":FILE");
entityType.setDomainId(domain.domainId);
entityType.setName("FILE");
entityType.setDescription("File entity type");
sharingClient.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":"+ResourceType.APPLICATION_DEPLOYMENT.name());
entityType.setDomainId(domain.domainId);
entityType.setName("APPLICATION-DEPLOYMENT");
entityType.setDescription("Application Deployment entity type");
sharingClient.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":"+ResourceType.GROUP_RESOURCE_PROFILE.name());
entityType.setDomainId(domain.domainId);
entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name());
entityType.setDescription("Group Resource Profile entity type");
sharingClient.createEntityType(entityType);
//Creating Permission Types for each domain
PermissionType permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId+":READ");
permissionType.setDomainId(domain.domainId);
permissionType.setName("READ");
permissionType.setDescription("Read permission type");
sharingClient.createPermissionType(permissionType);
permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId+":WRITE");
permissionType.setDomainId(domain.domainId);
permissionType.setName("WRITE");
permissionType.setDescription("Write permission type");
sharingClient.createPermissionType(permissionType);
permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId+":EXEC");
permissionType.setDomainId(domain.domainId);
permissionType.setName("EXEC");
permissionType.setDescription("Execute permission type");
sharingClient.createPermissionType(permissionType);
//Create an "everyone" group for the domain
String groupId = "everyone@" + domain.domainId;
UserGroup userGroup = new UserGroup();
userGroup.setGroupId(groupId);
userGroup.setDomainId(domain.domainId);
userGroup.setGroupCardinality(GroupCardinality.MULTI_USER);
userGroup.setCreatedTime(System.currentTimeMillis());
userGroup.setUpdatedTime(System.currentTimeMillis());
userGroup.setOwnerId(authzToken.getClaimsMap().get(Constants.USER_NAME) + "@" + domain.domainId);
userGroup.setName("everyone");
userGroup.setDescription("Default Group");
userGroup.setGroupType(GroupType.DOMAIN_LEVEL_GROUP);
sharingClient.createGroup(userGroup);
registryClientPool.returnResource(registryClient);
sharingClientPool.returnResource(sharingClient);
return gatewayId;
} catch (Exception e) {
logger.error("Error while adding gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding gateway. More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(registryClient);
throw exception;
}
}
/**
* Get all users in the gateway
*
* @param authzToken
* @param gatewayId The gateway data model.
* @return users
* list of usernames of the users in the gateway
*/
@Override
public List<String> getAllUsersInGateway(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<String> result = regClient.getAllUsersInGateway(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving users", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving users. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateGateway(AuthzToken authzToken, String gatewayId, Gateway updatedGateway)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGateway(gatewayId, updatedGateway);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while updating the gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating the gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public Gateway getGateway(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Gateway result = regClient.getGateway(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while getting the gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting the gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteGateway(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteGateway(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while deleting the gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting the gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<Gateway> getAllGateways(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException,
AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<Gateway> result = regClient.getAllGateways();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while getting all the gateways", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting all the gateways. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean isGatewayExist(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.isGatewayExist(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while getting gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* * API methods to retrieve notifications
* *
*
* @param authzToken
* @param notification
*/
@Override
@SecurityCheck
public String createNotification(AuthzToken authzToken, Notification notification) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.createNotification(notification);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while creating notification", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while creating notification. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateNotification(AuthzToken authzToken, Notification notification) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateNotification(notification);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while updating notification", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteNotification(AuthzToken authzToken, String gatewayId, String notificationId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteNotification(gatewayId, notificationId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while deleting notification", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting notification. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
// No security check
@Override
public Notification getNotification(AuthzToken authzToken, String gatewayId, String notificationId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Notification result = regClient.getNotification(gatewayId, notificationId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving notification", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retreiving notification. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
// No security check
@Override
public List<Notification> getAllNotifications(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<Notification> result = regClient.getAllNotifications(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while getting all notifications", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting all notifications. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String generateAndRegisterSSHKeys(AuthzToken authzToken, String gatewayId, String userName, String description, CredentialOwnerType credentialOwnerType) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
SSHCredential sshCredential = new SSHCredential();
sshCredential.setUsername(userName);
sshCredential.setGatewayId(gatewayId);
sshCredential.setDescription(description);
if (credentialOwnerType != null) {
sshCredential.setCredentialOwnerType(credentialOwnerType);
}
String key = csClient.addSSHCredential(sshCredential);
logger.debug("Airavata generated SSH keys for gateway : " + gatewayId + " and for user : " + userName);
csClientPool.returnResource(csClient);
return key;
}catch (Exception e){
logger.error("Error occurred while registering SSH Credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while registering SSH Credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
/**
* Generate and Register Username PWD Pair with Airavata Credential Store.
*
* @param authzToken
* @param gatewayId The identifier for the requested Gateway.
* @param portalUserName The User for which the credential should be registered. For community accounts, this user is the name of the
* community user name. For computational resources, this user name need not be the same user name on resoruces.
* @param password
* @return airavataCredStoreToken
* An SSH Key pair is generated and stored in the credential store and associated with users or community account
* belonging to a Gateway.
*/
@Override
@SecurityCheck
public String registerPwdCredential(AuthzToken authzToken, String gatewayId, String portalUserName,
String loginUserName, String password, String description) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
PasswordCredential pwdCredential = new PasswordCredential();
pwdCredential.setPortalUserName(portalUserName);
pwdCredential.setLoginUserName(loginUserName);
pwdCredential.setPassword(password);
pwdCredential.setDescription(description);
pwdCredential.setGatewayId(gatewayId);
String key = csClient.addPasswordCredential(pwdCredential);
logger.debug("Airavata generated PWD credential for gateway : " + gatewayId + " and for user : " + loginUserName);
csClientPool.returnResource(csClient);
return key;
}catch (Exception e){
logger.error("Error occurred while registering PWD Credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while registering PWD Credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public String getSSHPubKey(AuthzToken authzToken, String airavataCredStoreToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
SSHCredential sshCredential = csClient.getSSHCredential(airavataCredStoreToken, gatewayId);
logger.debug("Airavata retrieved SSH pub key for gateway id : " + gatewayId + " and for token : " + airavataCredStoreToken);
csClientPool.returnResource(csClient);
return sshCredential.getPublicKey();
}catch (Exception e){
logger.error("Error occurred while retrieving SSH credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public Map<String, String> getAllGatewaySSHPubKeys(AuthzToken authzToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
Map<String, String> allSSHKeysForGateway = csClient.getAllSSHKeysForGateway(gatewayId);
logger.debug("Airavata retrieved all SSH pub keys for gateway Id : " + gatewayId);
csClientPool.returnResource(csClient);
return allSSHKeysForGateway;
}catch (Exception e){
logger.error("Error occurred while retrieving SSH public keys for gateway : " + gatewayId , e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH public keys for gateway : " + gatewayId + ". More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<CredentialSummary> getAllCredentialSummaryForGateway(AuthzToken authzToken, SummaryType type, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
if(type.equals(SummaryType.SSH)){
logger.debug("Airavata will retrieve all SSH pub keys summaries for gateway Id : " + gatewayId);
List<CredentialSummary> result = csClient.getAllCredentialSummaryForGateway(type, gatewayId);
csClientPool.returnResource(csClient);
return result;
} else {
logger.info("Summay Type"+ type.toString() + " not supported by Airavata");
AiravataSystemException ex = new AiravataSystemException();
ex.setAiravataErrorType(AiravataErrorType.UNSUPPORTED_OPERATION);
ex.setMessage("Summay Type"+ type.toString() + " not supported by Airavata");
csClientPool.returnResource(csClient);
throw ex;
}
}catch (Exception e){
logger.error("Error occurred while retrieving SSH public keys summaries for gateway : " + gatewayId , e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH public keys summaries for gateway : " + gatewayId + ". More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<CredentialSummary> getAllCredentialSummaryForUsersInGateway(AuthzToken authzToken,SummaryType type, String gatewayId, String userId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
if(type.equals(SummaryType.SSH)){
logger.debug("Airavata will retrieve all SSH pub keys summaries for gateway Id : " + gatewayId);
List<CredentialSummary> result = csClient.getAllCredentialSummaryForUserInGateway(type, gatewayId, userId);
csClientPool.returnResource(csClient);
return result;
} else {
logger.info("Summay Type"+ type.toString() + " not supported by Airavata");
AiravataSystemException ex = new AiravataSystemException();
ex.setAiravataErrorType(AiravataErrorType.UNSUPPORTED_OPERATION);
ex.setMessage("Summay Type"+ type.toString() + " not supported by Airavata");
csClientPool.returnResource(csClient);
throw ex;
}
}catch (Exception e){
logger.error("Error occurred while retrieving SSH public keys summaries for user : " + userId , e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH public keys summaries for user : " + userId + ". More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public Map<String, String> getAllGatewayPWDCredentials(AuthzToken authzToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
Map<String, String> allPwdCredentials = csClient.getAllPWDCredentialsForGateway(gatewayId);
logger.debug("Airavata retrieved all PWD Credentials for gateway Id : " + gatewayId);
csClientPool.returnResource(csClient);
return allPwdCredentials;
}catch (Exception e){
logger.error("Error occurred while retrieving PWD Credentials for gateway : " + gatewayId , e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving PWD Credentials for gateway : " + gatewayId + ". More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteSSHPubKey(AuthzToken authzToken, String airavataCredStoreToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
logger.debug("Airavata deleted SSH pub key for gateway Id : " + gatewayId + " and with token id : " + airavataCredStoreToken);
boolean result = csClient.deleteSSHCredential(airavataCredStoreToken, gatewayId);
csClientPool.returnResource(csClient);
return result;
}catch (Exception e){
logger.error("Error occurred while deleting SSH credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while deleting SSH credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deletePWDCredential(AuthzToken authzToken, String airavataCredStoreToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
logger.debug("Airavata deleted PWD credential for gateway Id : " + gatewayId + " and with token id : " + airavataCredStoreToken);
boolean result = csClient.deletePWDCredential(airavataCredStoreToken, gatewayId);
csClientPool.returnResource(csClient);
return result;
}catch (Exception e){
logger.error("Error occurred while deleting PWD credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while deleting PWD credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
/**
* Create a Project
*
* @param project
*/
@Override
@SecurityCheck
public String createProject(AuthzToken authzToken, String gatewayId, Project project) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: verify that gatewayId and project.gatewayId match authzToken
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
String projectId = regClient.createProject(gatewayId, project);
if(ServerSettings.isEnableSharing()){
try {
Entity entity = new Entity();
entity.setEntityId(projectId);
final String domainId = project.getGatewayId();
entity.setDomainId(domainId);
entity.setEntityTypeId(domainId + ":" + "PROJECT");
entity.setOwnerId(project.getOwner() + "@" + domainId);
entity.setName(project.getName());
entity.setDescription(project.getDescription());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
logger.error("Rolling back project creation Proj ID : " + projectId);
regClient.deleteProject(projectId);
AiravataSystemException ase = new AiravataSystemException();
ase.setMessage("Failed to create entry for project in Sharing Registry");
throw ase;
}
}
logger.debug("Airavata created project with project Id : " + projectId + " for gateway Id : " + gatewayId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return projectId;
} catch (Exception e) {
logger.error("Error while creating the project", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while creating the project. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateProject(AuthzToken authzToken, String projectId, Project updatedProject) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, ProjectNotFoundException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
Project existingProject = regClient.getProject(projectId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(existingProject.getOwner())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(existingProject.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
projectId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
if(!updatedProject.getOwner().equals(existingProject.getOwner())){
throw new InvalidRequestException("Owner of a project cannot be changed");
}
if(!updatedProject.getGatewayId().equals(existingProject.getGatewayId())){
throw new InvalidRequestException("Gateway ID of a project cannot be changed");
}
regClient.updateProject(projectId, updatedProject);
logger.debug("Airavata updated project with project Id : " + projectId );
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
} catch (Exception e) {
logger.error("Error while updating the project", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating the project. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteProject(AuthzToken authzToken, String projectId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, ProjectNotFoundException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
Project existingProject = regClient.getProject(projectId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(existingProject.getOwner())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(existingProject.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
projectId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
boolean ret = regClient.deleteProject(projectId);
logger.debug("Airavata deleted project with project Id : " + projectId );
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return ret;
} catch (Exception e) {
logger.error("Error while removing the project", e);
ProjectNotFoundException exception = new ProjectNotFoundException();
exception.setMessage("Error while removing the project. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
private boolean validateString(String name){
boolean valid = true;
if (name == null || name.equals("") || name.trim().length() == 0){
valid = false;
}
return valid;
}
/**
* Get a Project by ID
*
* @param projectId
*/
@Override
@SecurityCheck
public Project getProject(AuthzToken authzToken, String projectId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, ProjectNotFoundException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
Project project = regClient.getProject(projectId);
if(authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(project.getOwner())
&& authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(project.getGatewayId())){
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return project;
}else if (ServerSettings.isEnableSharing()){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
projectId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access this resource");
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return project;
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
} else {
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return null;
}
} catch (Exception e) {
logger.error("Error while retrieving the project", e);
ProjectNotFoundException exception = new ProjectNotFoundException();
exception.setMessage("Error while retrieving the project. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Get all Project by user with pagination. Results will be ordered based
* on creation time DESC
*
* @param gatewayId
* The identifier for the requested gateway.
* @param userName
* The identifier of the user
* @param limit
* The amount results to be fetched
* @param offset
* The starting point of the results to be fetched
**/
@Override
@SecurityCheck
public List<Project> getUserProjects(AuthzToken authzToken, String gatewayId, String userName,
int limit, int offset)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if (ServerSettings.isEnableSharing()){
// user projects + user accessible projects
List<String> accessibleProjectIds = new ArrayList<>();
List<SearchCriteria> filters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(gatewayId + ":PROJECT");
filters.add(searchCriteria);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, filters, 0, -1).stream().forEach(p -> accessibleProjectIds
.add(p.entityId));
List<Project> result = regClient.searchProjects(gatewayId, userName, accessibleProjectIds, new HashMap<>(), limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}else{
List<Project> result = regClient.getUserProjects(gatewayId, userName, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}
} catch (Exception e) {
logger.error("Error while retrieving projects", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving projects. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
*
* Search User Projects
* Search and get all Projects for user by project description or/and project name with pagination.
* Results will be ordered based on creation time DESC.
*
* @param gatewayId
* The unique identifier of the gateway making the request.
*
* @param userName
* The identifier of the user.
*
* @param filters
* Map of multiple filter criteria. Currenlt search filters includes Project Name and Project Description
*
* @param limit
* The amount results to be fetched.
*
* @param offset
* The starting point of the results to be fetched.
*
*/
@Override
public List<Project> searchProjects(AuthzToken authzToken, String gatewayId, String userName, Map<ProjectSearchFields,
String> filters, int limit, int offset) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<String> accessibleProjIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> sharingFilters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(gatewayId + ":PROJECT");
sharingFilters.add(searchCriteria);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, sharingFilters, 0, -1).stream().forEach(e -> accessibleProjIds.add(e.entityId));
}
List<Project> result = regClient.searchProjects(gatewayId, userName, accessibleProjIds, filters, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}catch (Exception e) {
logger.error("Error while retrieving projects", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving projects. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Search Experiments by using multiple filter criteria with pagination. Results will be sorted
* based on creation time DESC
*
* @param gatewayId
* Identifier of the requested gateway
* @param userName
* Username of the requested user
* @param filters
* map of multiple filter criteria.
* @param limit
* Amount of results to be fetched
* @param offset
* The starting point of the results to be fetched
*/
@Override
@SecurityCheck
public List<ExperimentSummaryModel> searchExperiments(AuthzToken authzToken, String gatewayId, String userName, Map<ExperimentSearchFields,
String> filters, int limit, int offset)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<String> accessibleExpIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> sharingFilters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(gatewayId + ":EXPERIMENT");
sharingFilters.add(searchCriteria);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, sharingFilters, 0, -1).forEach(e -> accessibleExpIds.add(e.entityId));
}
List<ExperimentSummaryModel> result = regClient.searchExperiments(gatewayId, userName, accessibleExpIds, filters, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}catch (Exception e) {
logger.error("Error while retrieving experiments", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving experiments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Get Experiment execution statisitics by sending the gateway id and the time period interested in.
* This method will retrun an ExperimentStatistics object which contains the number of successfully
* completed experiments, failed experiments etc.
* @param gatewayId
* @param fromTime
* @param toTime
* @return
* @throws InvalidRequestException
* @throws AiravataClientException
* @throws AiravataSystemException
* @throws TException
*/
@Override
@SecurityCheck
public ExperimentStatistics getExperimentStatistics(AuthzToken authzToken, String gatewayId, long fromTime, long toTime,
String userName, String applicationName, String resourceHostName)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentStatistics result = regClient.getExperimentStatistics(gatewayId, fromTime, toTime, userName, applicationName, resourceHostName);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}catch (Exception e) {
logger.error("Error while retrieving experiments", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving experiments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Get Experiments within project with pagination. Results will be sorted
* based on creation time DESC
*
* @param projectId
* Identifier of the project
* @param limit
* Amount of results to be fetched
* @param offset
* The starting point of the results to be fetched
*/
@Override
@SecurityCheck
public List<ExperimentModel> getExperimentsInProject(AuthzToken authzToken, String projectId, int limit, int offset)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, ProjectNotFoundException,
AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
Project project = regClient.getProject(projectId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(project.getOwner())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(project.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
projectId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
List<ExperimentModel> result = regClient.getExperimentsInProject(projectId, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving the experiments", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the experiments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Get Experiments by user pagination. Results will be sorted
* based on creation time DESC
*
* @param gatewayId
* Identifier of the requesting gateway
* @param userName
* Username of the requested user
* @param limit
* Amount of results to be fetched
* @param offset
* The starting point of the results to be fetched
*/
@Override
@SecurityCheck
public List<ExperimentModel> getUserExperiments(AuthzToken authzToken, String gatewayId, String userName, int limit,
int offset) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<ExperimentModel> result = regClient.getUserExperiments(gatewayId, userName, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving the experiments", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the experiments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Create an experiment for the specified user belonging to the gateway. The gateway identity is not explicitly passed
* but inferred from the authentication header. This experiment is just a persistent place holder. The client
* has to subsequently configure and launch the created experiment. No action is taken on Airavata Server except
* registering the experiment in a persistent store.
*
* @param experiment@return The server-side generated.airavata.registry.core.experiment.globally unique identifier.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public String createExperiment(AuthzToken authzToken, String gatewayId, ExperimentModel experiment) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: verify that gatewayId and experiment.gatewayId match authzToken
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
String experimentId = regClient.createExperiment(gatewayId, experiment);
if(ServerSettings.isEnableSharing()) {
try {
Entity entity = new Entity();
entity.setEntityId(experimentId);
final String domainId = experiment.getGatewayId();
entity.setDomainId(domainId);
entity.setEntityTypeId(domainId + ":" + "EXPERIMENT");
entity.setOwnerId(experiment.getUserName() + "@" + domainId);
entity.setName(experiment.getExperimentName());
entity.setDescription(experiment.getDescription());
entity.setParentEntityId(experiment.getProjectId());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
logger.error("Rolling back experiment creation Exp ID : " + experimentId);
regClient.deleteExperiment(experimentId);
AiravataSystemException ase = new AiravataSystemException();
ase.setMessage("Failed to create sharing registry record");
throw ase;
}
}
ExperimentStatusChangeEvent event = new ExperimentStatusChangeEvent(ExperimentState.CREATED,
experimentId,
gatewayId);
String messageId = AiravataUtils.getId("EXPERIMENT");
MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
if(statusPublisher !=null) {
statusPublisher.publish(messageContext);
}
logger.debug(experimentId, "Created new experiment with experiment name {}", experiment.getExperimentName());
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return experimentId;
} catch (Exception e) {
logger.error("Error while creating the experiment with experiment name {}", experiment.getExperimentName());
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while creating the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* If the experiment is not already launched experiment can be deleted.
* @param authzToken
* @param experimentId
* @return
* @throws InvalidRequestException
* @throws AiravataClientException
* @throws AiravataSystemException
* @throws AuthorizationException
* @throws TException
*/
@Override
@SecurityCheck
public boolean deleteExperiment(AuthzToken authzToken, String experimentId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentModel experimentModel = regClient.getExperiment(experimentId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(experimentModel.getUserName())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(experimentModel.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
experimentId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
if(!(experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED)){
logger.error("Error while deleting the experiment");
throw new RegistryServiceException("Experiment is not in CREATED state. Hence cannot deleted. ID:"+ experimentId);
}
boolean result = regClient.deleteExperiment(experimentId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while deleting the experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Fetch previously created experiment metadata.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return experimentMetada
* This method will return the previously stored experiment metadata.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public ExperimentModel getExperiment(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException,
ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
ExperimentModel experimentModel = null;
try {
experimentModel = regClient.getExperiment(airavataExperimentId);
if(authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(experimentModel.getUserName())
&& authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(experimentModel.getGatewayId())){
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return experimentModel;
}else if(ServerSettings.isEnableSharing()){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
airavataExperimentId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access this resource");
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return experimentModel;
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}else{
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return null;
}
} catch (Exception e) {
logger.error("Error while getting the experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public ExperimentModel getExperimentByAdmin(AuthzToken authzToken, String airavataExperimentId)
throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
ExperimentModel experimentModel = null;
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
experimentModel = regClient.getExperiment(airavataExperimentId);
registryClientPool.returnResource(regClient);
if(gatewayId.equals(experimentModel.getGatewayId())){
return experimentModel;
} else {
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
logger.error("Error while getting the experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the completed nested tree structue of previously created experiment metadata which includes processes ->
* tasks -> jobs information.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return experimentMetada
* This method will return the previously stored experiment metadata.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public ExperimentModel getDetailedExperimentTree(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException,
ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentModel result = regClient.getDetailedExperimentTree(airavataExperimentId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving the experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Configure a previously created experiment with required inputs, scheduling and other quality of service
* parameters. This method only updates the experiment object within the registry. The experiment has to be launched
* to make it actionable by the server.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @param experiment
* @return This method call does not have a return value.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public void updateExperiment(AuthzToken authzToken, String airavataExperimentId, ExperimentModel experiment)
throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, AiravataSystemException,
AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentModel experimentModel = regClient.getExperiment(airavataExperimentId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(experimentModel.getUserName())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(experimentModel.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
airavataExperimentId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
regClient.updateExperiment(airavataExperimentId, experiment);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while updating experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateExperimentConfiguration(AuthzToken authzToken, String airavataExperimentId, UserConfigurationDataModel userConfiguration)
throws AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
regClient.send_updateExperimentConfiguration(airavataExperimentId, userConfiguration);
registryClientPool.returnResource(regClient);
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while updating user configuration", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user configuration. " +
"Update experiment is only valid for experiments " +
"with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " +
"experiment is in one of above statuses... " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateResourceScheduleing(AuthzToken authzToken, String airavataExperimentId,
ComputationalResourceSchedulingModel resourceScheduling) throws AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
regClient.updateResourceScheduleing(airavataExperimentId, resourceScheduling);
registryClientPool.returnResource(regClient);
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while updating scheduling info", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating scheduling info. " +
"Update experiment is only valid for experiments " +
"with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " +
"experiment is in one of above statuses... " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* *
* * Validate experiment configuration. A true in general indicates, the experiment is ready to be launched.
* *
* * @param experimentID
* * @return sucess/failure
* *
* *
*
* @param airavataExperimentId
*/
@Override
@SecurityCheck
public boolean validateExperiment(AuthzToken authzToken, String airavataExperimentId) throws TException {
// TODO - call validation module and validate experiment
/* try {
ExperimentModel experimentModel = regClient.getExperiment(airavataExperimentId);
if (experimentModel == null) {
logger.error(airavataExperimentId, "Experiment validation failed , experiment {} doesn't exist.", airavataExperimentId);
throw new ExperimentNotFoundException("Requested experiment id " + airavataExperimentId + " does not exist in the system..");
}
} catch (RegistryServiceException | ApplicationSettingsException e1) {
logger.error(airavataExperimentId, "Error while retrieving projects", e1);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving projects. More info : " + e1.getMessage());
throw exception;
}
Client orchestratorClient = getOrchestratorClient();
try{
if (orchestratorClient.validateExperiment(airavataExperimentId)) {
logger.debug(airavataExperimentId, "Experiment validation succeed.");
return true;
} else {
logger.debug(airavataExperimentId, "Experiment validation failed.");
return false;
}}catch (TException e){
throw e;
}finally {
orchestratorClient.getOutputProtocol().getTransport().close();
orchestratorClient.getInputProtocol().getTransport().close();
}*/
return true;
}
/**
* Fetch the previously configured experiment configuration information.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return This method returns the previously configured experiment configuration data.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
*<p/>
*UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
*step, then Airavata Registry will not have a provenance area setup. The client has to follow
*gateway registration steps and retry this request.
*<p/>
*AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
*For now this is a place holder.
*<p/>
*INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
*is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any
* Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public ExperimentStatus getExperimentStatus(AuthzToken authzToken, String airavataExperimentId) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ExperimentStatus result = regClient.getExperimentStatus(airavataExperimentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
AiravataSystemException exception = new AiravataSystemException();
exception.setMessage(e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<OutputDataObjectType> getExperimentOutputs(AuthzToken authzToken, String airavataExperimentId)
throws AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<OutputDataObjectType> result = regClient.getExperimentOutputs(airavataExperimentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while retrieving the experiment outputs", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the experiment outputs. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<OutputDataObjectType> getIntermediateOutputs(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException,
ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return null;
}
@SecurityCheck
public Map<String, JobStatus> getJobStatuses(AuthzToken authzToken, String airavataExperimentId)
throws AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, JobStatus> result = regClient.getJobStatuses(airavataExperimentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while retrieving the job statuses", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the job statuses. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<JobModel> getJobDetails(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException,
ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<JobModel> result = regClient.getJobDetails(airavataExperimentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while retrieving the job details", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the job details. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Launch a previously created and configured experiment. Airavata Server will then start processing the request and appropriate
* notifications and intermediate and output data will be subsequently available for this experiment.
*
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return This method call does not have a return value.
* @throws org.apache.airavata.model.error.InvalidRequestException
* For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException
* If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException
* The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException
* This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public void launchExperiment(AuthzToken authzToken, final String airavataExperimentId, String gatewayId)
throws AuthorizationException, AiravataSystemException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentModel experiment = regClient.getExperiment(airavataExperimentId);
// TODO: fix checking if the user has access to the deployment of this application, should check for entity type APPLICATION_DEPLOYMENT and permission type EXEC
// String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
// String appInterfaceId = experiment.getExecutionId();
// ApplicationInterfaceDescription applicationInterfaceDescription = regClient.getApplicationInterface(appInterfaceId);
// List<String> entityIds = applicationInterfaceDescription.getApplicationModules();
// if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId, entityIds.get(0),gatewayId + ":READ")) {
// logger.error(airavataExperimentId, "User does not have access to application module {}.", entityIds.get(0));
// throw new AuthorizationException("User does not have permission to access this resource");
// }
if (experiment == null) {
logger.error(airavataExperimentId, "Error while launching experiment, experiment {} doesn't exist.", airavataExperimentId);
throw new ExperimentNotFoundException("Requested experiment id " + airavataExperimentId + " does not exist in the system..");
}
submitExperiment(gatewayId, airavataExperimentId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
} catch (Exception e1) {
logger.error(airavataExperimentId, "Error while instantiate the registry instance", e1);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while instantiate the registry instance. More info : " + e1.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
// private OrchestratorService.Client getOrchestratorClient() throws TException {
// try {
// final String serverHost = ServerSettings.getOrchestratorServerHost();
// final int serverPort = ServerSettings.getOrchestratorServerPort();
// return OrchestratorClientFactory.createOrchestratorClient(serverHost, serverPort);
// } catch (AiravataException e) {
// throw new TException(e);
// }
// }
/**
* Clone an specified experiment with a new name. A copy of the experiment configuration is made and is persisted with new metadata.
* The client has to subsequently update this configuration if needed and launch the cloned experiment.
*
* @param existingExperimentID
* This is the experiment identifier that already exists in the system. Will use this experimentID to retrieve
* user configuration which is used with the clone experiment.
*
* @param newExperimentName
* experiment name that should be used in the cloned experiment
*
* @return
* The server-side generated.airavata.registry.core.experiment.globally unique identifier for the newly cloned experiment.
*
* @throws org.apache.airavata.model.error.InvalidRequestException
* For any incorrect forming of the request itself.
*
* @throws org.apache.airavata.model.error.ExperimentNotFoundException
* If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
*
* @throws org.apache.airavata.model.error.AiravataClientException
* The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
*
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
*
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
*
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
*
* @throws org.apache.airavata.model.error.AiravataSystemException
* This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*
*
* @param existingExperimentID
* @param newExperimentName
*/
@Override
@SecurityCheck
public String cloneExperiment(AuthzToken authzToken, String existingExperimentID, String newExperimentName, String newExperimentProjectId)
throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, AiravataSystemException,
AuthorizationException, ProjectNotFoundException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
// getExperiment will apply sharing permissions
ExperimentModel existingExperiment = this.getExperiment(authzToken, existingExperimentID);
String result = cloneExperimentInternal(regClient, sharingClient, authzToken, existingExperimentID, newExperimentName, newExperimentProjectId, existingExperiment);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error(existingExperimentID, "Error while cloning the experiment with existing configuration...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while cloning the experiment with existing configuration. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public String cloneExperimentByAdmin(AuthzToken authzToken, String existingExperimentID, String newExperimentName, String newExperimentProjectId)
throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, AiravataSystemException,
AuthorizationException, ProjectNotFoundException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
// get existing experiment by bypassing normal sharing permissions for the admin user
ExperimentModel existingExperiment = this.getExperimentByAdmin(authzToken, existingExperimentID);
String result = cloneExperimentInternal(regClient, sharingClient, authzToken, existingExperimentID, newExperimentName, newExperimentProjectId, existingExperiment);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error(existingExperimentID, "Error while cloning the experiment with existing configuration...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while cloning the experiment with existing configuration. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
private String cloneExperimentInternal(RegistryService.Client regClient, SharingRegistryService.Client sharingClient,
AuthzToken authzToken, String existingExperimentID, String newExperimentName, String newExperimentProjectId, ExperimentModel existingExperiment)
throws ExperimentNotFoundException, ProjectNotFoundException, TException, AuthorizationException, ApplicationSettingsException {
if (existingExperiment == null){
logger.error(existingExperimentID, "Error while cloning experiment {}, experiment doesn't exist.", existingExperimentID);
throw new ExperimentNotFoundException("Requested experiment id " + existingExperimentID + " does not exist in the system..");
}
if (newExperimentProjectId != null) {
// getProject will apply sharing permissions
Project project = this.getProject(authzToken, newExperimentProjectId);
if (project == null){
logger.error("Error while cloning experiment {}, project {} doesn't exist.", existingExperimentID, newExperimentProjectId);
throw new ProjectNotFoundException("Requested project id " + newExperimentProjectId + " does not exist in the system..");
}
existingExperiment.setProjectId(project.getProjectID());
}
// make sure user has write access to the project
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
existingExperiment.getProjectId(), gatewayId + ":WRITE")){
logger.error("Error while cloning experiment {}, user doesn't have write access to project {}", existingExperimentID, existingExperiment.getProjectId());
throw new AuthorizationException("User does not have permission to clone an experiment in this project");
}
existingExperiment.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime());
if (existingExperiment.getExecutionId() != null){
List<OutputDataObjectType> applicationOutputs = regClient.getApplicationOutputs(existingExperiment.getExecutionId());
existingExperiment.setExperimentOutputs(applicationOutputs);
}
if (validateString(newExperimentName)){
existingExperiment.setExperimentName(newExperimentName);
}
if (existingExperiment.getErrors() != null ){
existingExperiment.getErrors().clear();
}
if(existingExperiment.getUserConfigurationData() != null && existingExperiment.getUserConfigurationData()
.getComputationalResourceScheduling() != null){
String compResourceId = existingExperiment.getUserConfigurationData()
.getComputationalResourceScheduling().getResourceHostId();
ComputeResourceDescription computeResourceDescription = regClient.getComputeResource(compResourceId);
if(!computeResourceDescription.isEnabled()){
existingExperiment.getUserConfigurationData().setComputationalResourceScheduling(null);
}
}
logger.debug("Airavata cloned experiment with experiment id : " + existingExperimentID);
existingExperiment.setUserName(userId);
String expId = regClient.createExperiment(gatewayId, existingExperiment);
if(ServerSettings.isEnableSharing()){
try {
Entity entity = new Entity();
entity.setEntityId(expId);
final String domainId = existingExperiment.getGatewayId();
entity.setDomainId(domainId);
entity.setEntityTypeId(domainId + ":" + "EXPERIMENT");
entity.setOwnerId(existingExperiment.getUserName() + "@" + domainId);
entity.setName(existingExperiment.getExperimentName());
entity.setDescription(existingExperiment.getDescription());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
logger.error("rolling back experiment creation Exp ID : " + expId);
regClient.deleteExperiment(expId);
}
}
return expId;
}
/**
* Terminate a running experiment.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return This method call does not have a return value.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public void terminateExperiment(AuthzToken authzToken, String airavataExperimentId, String gatewayId)
throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ExperimentModel existingExperiment = regClient.getExperiment(airavataExperimentId);
if (existingExperiment == null){
logger.error(airavataExperimentId, "Error while cancelling experiment {}, experiment doesn't exist.", airavataExperimentId);
throw new ExperimentNotFoundException("Requested experiment id " + airavataExperimentId + " does not exist in the system..");
}
switch (existingExperiment.getExperimentStatus().get(0).getState()) {
case COMPLETED: case CANCELED: case FAILED: case CANCELING:
logger.warn("Can't terminate already {} experiment", existingExperiment.getExperimentStatus().get(0).getState().name());
break;
case CREATED:
logger.warn("Experiment termination is only allowed for launched experiments.");
break;
default:
submitCancelExperiment(gatewayId, airavataExperimentId);
logger.debug("Airavata cancelled experiment with experiment id : " + airavataExperimentId);
break;
}
registryClientPool.returnResource(regClient);
} catch (RegistryServiceException | AiravataException e) {
logger.error(airavataExperimentId, "Error while cancelling the experiment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while cancelling the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Application Module.
*
* @param applicationModule Application Module Object created from the datamodel.
* @return appModuleId
* Returns a server-side generated airavata appModule globally unique identifier.
*/
@Override
@SecurityCheck
public String registerApplicationModule(AuthzToken authzToken, String gatewayId, ApplicationModule applicationModule)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerApplicationModule(gatewayId, applicationModule);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while adding application module...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding application module. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a Application Module.
*
* @param appModuleId The identifier for the requested application module
* @return applicationModule
* Returns a application Module Object.
*/
@Override
@SecurityCheck
public ApplicationModule getApplicationModule(AuthzToken authzToken, String appModuleId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ApplicationModule result = regClient.getApplicationModule(appModuleId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appModuleId, "Error while retrieving application module...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the adding application module. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Application Module.
*
* @param appModuleId The identifier for the requested application module to be updated.
* @param applicationModule Application Module Object created from the datamodel.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateApplicationModule(AuthzToken authzToken, String appModuleId, ApplicationModule applicationModule)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateApplicationModule(appModuleId, applicationModule);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appModuleId, "Error while updating application module...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating application module. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all Application Module Descriptions.
*
* @return list applicationModule.
* Returns the list of all Application Module Objects.
*/
@Override
@SecurityCheck
public List<ApplicationModule> getAllAppModules(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<ApplicationModule> result = regClient.getAllAppModules(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving all application modules...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving all application modules. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all accessible Application Module Descriptions.
*
* @return list applicationModule.
* Returns the list of Application Module Objects that are accessible to the user.
*/
@Override
@SecurityCheck
public List<ApplicationModule> getAccessibleAppModules(AuthzToken authzToken, String gatewayId, ResourcePermissionType permissionType) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<String> accessibleAppDeploymentIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> sharingFilters = new ArrayList<>();
SearchCriteria entityTypeFilter = new SearchCriteria();
entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
entityTypeFilter.setSearchCondition(SearchCondition.EQUAL);
entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name());
sharingFilters.add(entityTypeFilter);
SearchCriteria permissionTypeFilter = new SearchCriteria();
permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL);
permissionTypeFilter.setValue(gatewayId + ":" + permissionType.name());
sharingFilters.add(permissionTypeFilter);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, sharingFilters, 0, -1).forEach(a -> accessibleAppDeploymentIds.add(a.entityId));
}
List<String> accessibleComputeResourceIds = new ArrayList<>();
List<GroupResourceProfile> groupResourceProfileList = getGroupResourceList(authzToken, gatewayId);
for(GroupResourceProfile groupResourceProfile : groupResourceProfileList) {
List<GroupComputeResourcePreference> groupComputeResourcePreferenceList = groupResourceProfile.getComputePreferences();
for(GroupComputeResourcePreference groupComputeResourcePreference : groupComputeResourcePreferenceList) {
accessibleComputeResourceIds.add(groupComputeResourcePreference.getComputeResourceId());
}
}
List<ApplicationModule> result = regClient.getAccessibleAppModules(gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving all application modules...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving all application modules. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Delete a Application Module.
*
* @param appModuleId The identifier for the requested application module to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteApplicationModule(AuthzToken authzToken, String appModuleId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteApplicationModule(appModuleId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appModuleId, "Error while deleting application module...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting the application module. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Application Deployment.
*
* @param applicationDeployment@return appModuleId
* Returns a server-side generated airavata appModule globally unique identifier.
*/
@Override
@SecurityCheck
public String registerApplicationDeployment(AuthzToken authzToken, String gatewayId, ApplicationDeploymentDescription applicationDeployment)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: verify that gatewayId matches authzToken gatewayId
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
String result = regClient.registerApplicationDeployment(gatewayId, applicationDeployment);
Entity entity = new Entity();
entity.setEntityId(result);
final String domainId = gatewayId;
entity.setDomainId(domainId);
entity.setEntityTypeId(domainId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name());
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
entity.setOwnerId(userName + "@" + domainId);
entity.setName(result);
entity.setDescription(applicationDeployment.getAppDeploymentDescription());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while adding application deployment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Fetch a Application Deployment.
*
* @param appDeploymentId The identifier for the requested application module
* @return applicationDeployment
* Returns a application Deployment Object.
*/
@Override
@SecurityCheck
public ApplicationDeploymentDescription getApplicationDeployment(AuthzToken authzToken, String appDeploymentId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ApplicationDeploymentDescription result = regClient.getApplicationDeployment(appDeploymentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appDeploymentId, "Error while retrieving application deployment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Application Deployment.
*
* @param appDeploymentId The identifier for the requested application deployment to be updated.
* @param applicationDeployment
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateApplicationDeployment(AuthzToken authzToken, String appDeploymentId,
ApplicationDeploymentDescription applicationDeployment)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateApplicationDeployment(appDeploymentId, applicationDeployment);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appDeploymentId, "Error while updating application deployment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a Application deployment.
*
* @param appDeploymentId The identifier for the requested application deployment to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteApplicationDeployment(AuthzToken authzToken, String appDeploymentId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteApplicationDeployment(appDeploymentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appDeploymentId, "Error while deleting application deployment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all Application Deployment Descriptions.
*
* @return list applicationDeployment.
* Returns the list of all Application Deployment Objects.
*/
@Override
@SecurityCheck
public List<ApplicationDeploymentDescription> getAllApplicationDeployments(AuthzToken authzToken, String gatewayId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<ApplicationDeploymentDescription> result = regClient.getAllApplicationDeployments(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving application deployments...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all accessible Application Deployment Descriptions.
*
* @return list applicationDeployment.
* Returns the list of Application Deployment Objects that are accessible to the user.
*/
@Override
@SecurityCheck
public List<ApplicationDeploymentDescription> getAccessibleApplicationDeployments(AuthzToken authzToken, String gatewayId, ResourcePermissionType permissionType)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<String> accessibleAppDeploymentIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> sharingFilters = new ArrayList<>();
SearchCriteria entityTypeFilter = new SearchCriteria();
entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
entityTypeFilter.setSearchCondition(SearchCondition.EQUAL);
entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name());
sharingFilters.add(entityTypeFilter);
SearchCriteria permissionTypeFilter = new SearchCriteria();
permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL);
permissionTypeFilter.setValue(gatewayId + ":" + permissionType.name());
sharingFilters.add(permissionTypeFilter);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, sharingFilters, 0, -1).forEach(a -> accessibleAppDeploymentIds.add(a.entityId));
}
List<String> accessibleComputeResourceIds = new ArrayList<>();
List<GroupResourceProfile> groupResourceProfileList = getGroupResourceList(authzToken, gatewayId);
for(GroupResourceProfile groupResourceProfile : groupResourceProfileList) {
List<GroupComputeResourcePreference> groupComputeResourcePreferenceList = groupResourceProfile.getComputePreferences();
for(GroupComputeResourcePreference groupComputeResourcePreference : groupComputeResourcePreferenceList) {
accessibleComputeResourceIds.add(groupComputeResourcePreference.getComputeResourceId());
}
}
List<ApplicationDeploymentDescription> result = regClient.getAccessibleApplicationDeployments(gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving application deployments...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Fetch a list of Deployed Compute Hosts.
*
* @param appModuleId The identifier for the requested application module
* @return list<string>
* Returns a list of Deployed Resources.
*/
@Override
@SecurityCheck
public List<String> getAppModuleDeployedResources(AuthzToken authzToken, String appModuleId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<String> result = regClient.getAppModuleDeployedResources(appModuleId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appModuleId, "Error while retrieving application deployments...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Application Interface.
*
* @param applicationInterface@return appInterfaceId
* Returns a server-side generated airavata application interface globally unique identifier.
*/
@Override
@SecurityCheck
public String registerApplicationInterface(AuthzToken authzToken, String gatewayId,
ApplicationInterfaceDescription applicationInterface) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerApplicationInterface(gatewayId, applicationInterface);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while adding application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String cloneApplicationInterface(AuthzToken authzToken, String existingAppInterfaceID, String newApplicationName, String gatewayId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ApplicationInterfaceDescription existingInterface = regClient.getApplicationInterface(existingAppInterfaceID);
if (existingInterface == null){
logger.error("Provided application interface does not exist.Please provide a valid application interface id...");
throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
}
existingInterface.setApplicationName(newApplicationName);
existingInterface.setApplicationInterfaceId(airavata_commonsConstants.DEFAULT_ID);
String interfaceId = regClient.registerApplicationInterface(gatewayId, existingInterface);
logger.debug("Airavata cloned application interface : " + existingAppInterfaceID + " for gateway id : " + gatewayId );
registryClientPool.returnResource(regClient);
return interfaceId;
} catch (Exception e) {
logger.error("Error while adding application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a Application Interface.
*
* @param appInterfaceId The identifier for the requested application module
* @return applicationInterface
* Returns a application Interface Object.
*/
@Override
@SecurityCheck
public ApplicationInterfaceDescription getApplicationInterface(AuthzToken authzToken, String appInterfaceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ApplicationInterfaceDescription result = regClient.getApplicationInterface(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while retrieving application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Application Interface.
*
* @param appInterfaceId The identifier for the requested application deployment to be updated.
* @param applicationInterface
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateApplicationInterface(AuthzToken authzToken, String appInterfaceId,
ApplicationInterfaceDescription applicationInterface) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateApplicationInterface(appInterfaceId, applicationInterface);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while updating application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a Application Interface.
*
* @param appInterfaceId The identifier for the requested application interface to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteApplicationInterface(AuthzToken authzToken, String appInterfaceId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteApplicationInterface(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while deleting application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch name and id of Application Interface documents.
*
* @return map<applicationId, applicationInterfaceNames>
* Returns a list of application interfaces with corresponsing id's
*/
@Override
@SecurityCheck
public Map<String, String> getAllApplicationInterfaceNames(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, String> result = regClient.getAllApplicationInterfaceNames(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving application interfaces...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application interfaces. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all Application Interface documents.
*
* @return map<applicationId, applicationInterfaceNames>
* Returns a list of application interfaces documents
*/
@Override
@SecurityCheck
public List<ApplicationInterfaceDescription> getAllApplicationInterfaces(AuthzToken authzToken, String gatewayId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<ApplicationInterfaceDescription> result = regClient.getAllApplicationInterfaces(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving application interfaces...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application interfaces. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the list of Application Inputs.
*
* @param appInterfaceId The identifier for the requested application interface
* @return list<applicationInterfaceModel.InputDataObjectType>
* Returns a list of application inputs.
*/
@Override
@SecurityCheck
public List<InputDataObjectType> getApplicationInputs(AuthzToken authzToken, String appInterfaceId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<InputDataObjectType> result = regClient.getApplicationInputs(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while retrieving application inputs...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application inputs. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the list of Application Outputs.
*
* @param appInterfaceId The identifier for the requested application interface
* @return list<applicationInterfaceModel.OutputDataObjectType>
* Returns a list of application outputs.
*/
@Override
@SecurityCheck
public List<OutputDataObjectType> getApplicationOutputs(AuthzToken authzToken, String appInterfaceId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<OutputDataObjectType> result = regClient.getApplicationOutputs(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
AiravataSystemException exception = new AiravataSystemException();
exception.setMessage(e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a list of all deployed Compute Hosts for a given application interfaces.
*
* @param appInterfaceId The identifier for the requested application interface
* @return map<computeResourceId, computeResourceName>
* A map of registered compute resource id's and their corresponding hostnames.
* Deployments of each modules listed within the interfaces will be listed.
*/
@Override
@SecurityCheck
public Map<String, String> getAvailableAppInterfaceComputeResources(AuthzToken authzToken, String appInterfaceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, String> result = regClient.getAvailableAppInterfaceComputeResources(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while saving compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while saving compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Compute Resource.
*
* @param computeResourceDescription Compute Resource Object created from the datamodel.
* @return computeResourceId
* Returns a server-side generated airavata compute resource globally unique identifier.
*/
@Override
@SecurityCheck
public String registerComputeResource(AuthzToken authzToken, ComputeResourceDescription computeResourceDescription)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerComputeResource(computeResourceDescription);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while saving compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while saving compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the given Compute Resource.
*
* @param computeResourceId The identifier for the requested compute resource
* @return computeResourceDescription
* Compute Resource Object created from the datamodel..
*/
@Override
@SecurityCheck
public ComputeResourceDescription getComputeResource(AuthzToken authzToken, String computeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ComputeResourceDescription result = regClient.getComputeResource(computeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while retrieving compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all registered Compute Resources.
*
* @return A map of registered compute resource id's and thier corresponding hostnames.
* Compute Resource Object created from the datamodel..
*/
@Override
@SecurityCheck
public Map<String, String> getAllComputeResourceNames(AuthzToken authzToken) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, String> result = regClient.getAllComputeResourceNames();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Compute Resource.
*
* @param computeResourceId The identifier for the requested compute resource to be updated.
* @param computeResourceDescription Compute Resource Object created from the datamodel.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateComputeResource(AuthzToken authzToken, String computeResourceId, ComputeResourceDescription computeResourceDescription)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateComputeResource(computeResourceId, computeResourceDescription);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while updating compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updaing compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a Compute Resource.
*
* @param computeResourceId The identifier for the requested compute resource to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteComputeResource(AuthzToken authzToken, String computeResourceId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteComputeResource(computeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while deleting compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Storage Resource.
*
* @param authzToken
* @param storageResourceDescription Storge Resource Object created from the datamodel.
* @return storageResourceId
* Returns a server-side generated airavata storage resource globally unique identifier.
*/
@Override
@SecurityCheck
public String registerStorageResource(AuthzToken authzToken, StorageResourceDescription storageResourceDescription)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerStorageResource(storageResourceDescription);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while saving storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while saving storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the given Storage Resource.
*
* @param authzToken
* @param storageResourceId The identifier for the requested storage resource
* @return storageResourceDescription
* Storage Resource Object created from the datamodel..
*/
@Override
@SecurityCheck
public StorageResourceDescription getStorageResource(AuthzToken authzToken, String storageResourceId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
StorageResourceDescription result = regClient.getStorageResource(storageResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(storageResourceId, "Error while retrieving storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all registered Storage Resources.
*
* @param authzToken
* @return A map of registered compute resource id's and thier corresponding hostnames.
* Compute Resource Object created from the datamodel..
*/
@Override
@SecurityCheck
public Map<String, String> getAllStorageResourceNames(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, String> result = regClient.getAllStorageResourceNames();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Compute Resource.
*
* @param authzToken
* @param storageResourceId The identifier for the requested compute resource to be updated.
* @param storageResourceDescription Storage Resource Object created from the datamodel.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateStorageResource(AuthzToken authzToken, String storageResourceId, StorageResourceDescription storageResourceDescription) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateStorageResource(storageResourceId, storageResourceDescription);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(storageResourceId, "Error while updating storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updaing storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a Storage Resource.
*
* @param authzToken
* @param storageResourceId The identifier for the requested compute resource to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteStorageResource(AuthzToken authzToken, String storageResourceId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteStorageResource(storageResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(storageResourceId, "Error while deleting storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Local Job Submission details to a compute resource
* App catalog will return a jobSubmissionInterfaceId which will be added to the jobSubmissionInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param localSubmission The LOCALSubmission object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addLocalSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder, LOCALSubmission localSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addLocalSubmissionDetails(computeResourceId, priorityOrder, localSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given Local Job Submission details
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param localSubmission The LOCALSubmission object to be updated.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean updateLocalSubmissionDetails(AuthzToken authzToken, String jobSubmissionInterfaceId, LOCALSubmission localSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateLocalSubmissionDetails(jobSubmissionInterfaceId, localSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public LOCALSubmission getLocalJobSubmission(AuthzToken authzToken, String jobSubmissionId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
LOCALSubmission result = regClient.getLocalJobSubmission(jobSubmissionId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving local job submission interface to resource compute resource...";
logger.error(jobSubmissionId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a SSH Job Submission details to a compute resource
* App catalog will return a jobSubmissionInterfaceId which will be added to the jobSubmissionInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param sshJobSubmission The SSHJobSubmission object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addSSHJobSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addSSHJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a SSH_FORK Job Submission details to a compute resource
* App catalog will return a jobSubmissionInterfaceId which will be added to the jobSubmissionInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param sshJobSubmission The SSHJobSubmission object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addSSHForkJobSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addSSHForkJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public SSHJobSubmission getSSHJobSubmission(AuthzToken authzToken, String jobSubmissionId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
SSHJobSubmission result = regClient.getSSHJobSubmission(jobSubmissionId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving SSH job submission interface to resource compute resource...";
logger.error(jobSubmissionId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Cloud Job Submission details to a compute resource
* App catalog will return a jobSubmissionInterfaceId which will be added to the jobSubmissionInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param cloudJobSubmission The SSHJobSubmission object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addCloudJobSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder,
CloudJobSubmission cloudJobSubmission) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addCloudJobSubmissionDetails(computeResourceId, priorityOrder, cloudJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public CloudJobSubmission getCloudJobSubmission(AuthzToken authzToken, String jobSubmissionId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
CloudJobSubmission result = regClient.getCloudJobSubmission(jobSubmissionId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving Cloud job submission interface to resource compute resource...";
logger.error(jobSubmissionId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String addUNICOREJobSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder,
UnicoreJobSubmission unicoreJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addUNICOREJobSubmissionDetails(computeResourceId, priorityOrder, unicoreJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public UnicoreJobSubmission getUnicoreJobSubmission(AuthzToken authzToken, String jobSubmissionId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UnicoreJobSubmission result = regClient.getUnicoreJobSubmission(jobSubmissionId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving Unicore job submission interface to resource compute resource...";
logger.error(jobSubmissionId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given SSH Job Submission details
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param sshJobSubmission The SSHJobSubmission object to be updated.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean updateSSHJobSubmissionDetails(AuthzToken authzToken, String jobSubmissionInterfaceId, SSHJobSubmission sshJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateSSHJobSubmissionDetails(jobSubmissionInterfaceId, sshJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given cloud Job Submission details
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param cloudJobSubmission The SSHJobSubmission object to be updated.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean updateCloudJobSubmissionDetails(AuthzToken authzToken, String jobSubmissionInterfaceId, CloudJobSubmission cloudJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateCloudJobSubmissionDetails(jobSubmissionInterfaceId, cloudJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateUnicoreJobSubmissionDetails(AuthzToken authzToken, String jobSubmissionInterfaceId, UnicoreJobSubmission unicoreJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUnicoreJobSubmissionDetails(jobSubmissionInterfaceId, unicoreJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Local data moevement details to a compute resource
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param resourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param localDataMovement The LOCALDataMovement object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addLocalDataMovementDetails(AuthzToken authzToken, String resourceId, DMType dmType, int priorityOrder,
LOCALDataMovement localDataMovement) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addLocalDataMovementDetails(resourceId, dmType, priorityOrder, localDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceId, "Error while adding data movement interface to resource resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding data movement interface to resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given Local data movement details
*
* @param dataMovementInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param localDataMovement The LOCALDataMovement object to be updated.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateLocalDataMovementDetails(AuthzToken authzToken, String dataMovementInterfaceId, LOCALDataMovement localDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateLocalDataMovementDetails(dataMovementInterfaceId, localDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while updating local data movement interface..", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating local data movement interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public LOCALDataMovement getLocalDataMovement(AuthzToken authzToken, String dataMovementId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
LOCALDataMovement result = regClient.getLocalDataMovement(dataMovementId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving local data movement interface to resource compute resource...";
logger.error(dataMovementId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a SCP data moevement details to a compute resource
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param resourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param scpDataMovement The SCPDataMovement object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addSCPDataMovementDetails(AuthzToken authzToken, String resourceId, DMType dmType, int priorityOrder, SCPDataMovement scpDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addSCPDataMovementDetails(resourceId, dmType, priorityOrder, scpDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceId, "Error while adding data movement interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given scp data movement details
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param dataMovementInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param scpDataMovement The SCPDataMovement object to be updated.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateSCPDataMovementDetails(AuthzToken authzToken, String dataMovementInterfaceId, SCPDataMovement scpDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateSCPDataMovementDetails(dataMovementInterfaceId, scpDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public SCPDataMovement getSCPDataMovement(AuthzToken authzToken, String dataMovementId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
SCPDataMovement result = regClient.getSCPDataMovement(dataMovementId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving SCP data movement interface to resource compute resource...";
logger.error(dataMovementId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String addUnicoreDataMovementDetails(AuthzToken authzToken, String resourceId, DMType dmType, int priorityOrder, UnicoreDataMovement unicoreDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addUnicoreDataMovementDetails(resourceId, dmType, priorityOrder, unicoreDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceId, "Error while adding data movement interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateUnicoreDataMovementDetails(AuthzToken authzToken, String dataMovementInterfaceId, UnicoreDataMovement unicoreDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUnicoreDataMovementDetails(dataMovementInterfaceId, unicoreDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while updating unicore data movement to compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating unicore data movement to compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public UnicoreDataMovement getUnicoreDataMovement(AuthzToken authzToken, String dataMovementId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UnicoreDataMovement result = regClient.getUnicoreDataMovement(dataMovementId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving UNICORE data movement interface...";
logger.error(dataMovementId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a GridFTP data moevement details to a compute resource
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param gridFTPDataMovement The GridFTPDataMovement object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addGridFTPDataMovementDetails(AuthzToken authzToken, String computeResourceId, DMType dmType, int priorityOrder,
GridFTPDataMovement gridFTPDataMovement) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addGridFTPDataMovementDetails(computeResourceId, dmType, priorityOrder, gridFTPDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding data movement interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given GridFTP data movement details to a compute resource
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param dataMovementInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param gridFTPDataMovement The GridFTPDataMovement object to be updated.
* @return status
* Returns a success/failure of the updation.
*/
@Override
@SecurityCheck
public boolean updateGridFTPDataMovementDetails(AuthzToken authzToken, String dataMovementInterfaceId, GridFTPDataMovement gridFTPDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGridFTPDataMovementDetails(dataMovementInterfaceId, gridFTPDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public GridFTPDataMovement getGridFTPDataMovement(AuthzToken authzToken, String dataMovementId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
GridFTPDataMovement result = regClient.getGridFTPDataMovement(dataMovementId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving GridFTP data movement interface to resource compute resource...";
logger.error(dataMovementId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Change the priority of a given job submisison interface
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be changed
* @param newPriorityOrder
* @return status
* Returns a success/failure of the change.
*/
@Override
@SecurityCheck
public boolean changeJobSubmissionPriority(AuthzToken authzToken, String jobSubmissionInterfaceId, int newPriorityOrder) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return false;
}
/**
* Change the priority of a given data movement interface
*
* @param dataMovementInterfaceId The identifier of the DataMovement Interface to be changed
* @param newPriorityOrder
* @return status
* Returns a success/failure of the change.
*/
@Override
@SecurityCheck
public boolean changeDataMovementPriority(AuthzToken authzToken, String dataMovementInterfaceId, int newPriorityOrder)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return false;
}
/**
* Change the priorities of a given set of job submission interfaces
*
* @param jobSubmissionPriorityMap A Map of identifiers of the JobSubmission Interfaces and thier associated priorities to be set.
* @return status
* Returns a success/failure of the changes.
*/
@Override
@SecurityCheck
public boolean changeJobSubmissionPriorities(AuthzToken authzToken, Map<String, Integer> jobSubmissionPriorityMap)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return false;
}
/**
* Change the priorities of a given set of data movement interfaces
*
* @param dataMovementPriorityMap A Map of identifiers of the DataMovement Interfaces and thier associated priorities to be set.
* @return status
* Returns a success/failure of the changes.
*/
@Override
@SecurityCheck
public boolean changeDataMovementPriorities(AuthzToken authzToken, Map<String, Integer> dataMovementPriorityMap)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return false;
}
/**
* Delete a given job submisison interface
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be changed
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteJobSubmissionInterface(AuthzToken authzToken, String computeResourceId, String jobSubmissionInterfaceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteJobSubmissionInterface(computeResourceId, jobSubmissionInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while deleting job submission interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting job submission interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a given data movement interface
*
* @param dataMovementInterfaceId The identifier of the DataMovement Interface to be changed
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteDataMovementInterface(AuthzToken authzToken, String resourceId, String dataMovementInterfaceId, DMType dmType)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteDataMovementInterface(resourceId, dataMovementInterfaceId, dmType);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while deleting data movement interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting data movement interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String registerResourceJobManager(AuthzToken authzToken, ResourceJobManager resourceJobManager) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerResourceJobManager(resourceJobManager);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceJobManager.getResourceJobManagerId(), "Error while adding resource job manager...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding resource job manager. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateResourceJobManager(AuthzToken authzToken, String resourceJobManagerId, ResourceJobManager updatedResourceJobManager)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateResourceJobManager(resourceJobManagerId, updatedResourceJobManager);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceJobManagerId, "Error while updating resource job manager...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating resource job manager. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public ResourceJobManager getResourceJobManager(AuthzToken authzToken,String resourceJobManagerId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ResourceJobManager result = regClient.getResourceJobManager(resourceJobManagerId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceJobManagerId, "Error while retrieving resource job manager...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving resource job manager. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteResourceJobManager(AuthzToken authzToken, String resourceJobManagerId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteResourceJobManager(resourceJobManagerId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceJobManagerId, "Error while deleting resource job manager...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting resource job manager. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteBatchQueue(AuthzToken authzToken, String computeResourceId, String queueName) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteBatchQueue(computeResourceId, queueName);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while deleting batch queue...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting batch queue. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Gateway Resource Profile.
*
* @param gatewayResourceProfile Gateway Resource Profile Object.
* The GatewayID should be obtained from Airavata gateway registration and passed to register a corresponding
* resource profile.
* @return status.
* Returns a success/failure of the registration.
*/
@Override
@SecurityCheck
public String registerGatewayResourceProfile(AuthzToken authzToken, GatewayResourceProfile gatewayResourceProfile)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerGatewayResourceProfile(gatewayResourceProfile);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while registering gateway resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering gateway resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the given Gateway Resource Profile.
*
* @param gatewayID The identifier for the requested gateway resource
* @return gatewayResourceProfile
* Gateway Resource Profile Object.
*/
@Override
@SecurityCheck
public GatewayResourceProfile getGatewayResourceProfile(AuthzToken authzToken, String gatewayID) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
GatewayResourceProfile result = regClient.getGatewayResourceProfile(gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while retrieving gateway resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving gateway resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Gateway Resource Profile.
*
* @param gatewayID The identifier for the requested gateway resource to be updated.
* @param gatewayResourceProfile Gateway Resource Profile Object.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateGatewayResourceProfile(AuthzToken authzToken,
String gatewayID,
GatewayResourceProfile gatewayResourceProfile) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGatewayResourceProfile(gatewayID, gatewayResourceProfile);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while updating gateway resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete the given Gateway Resource Profile.
*
* @param gatewayID The identifier for the requested gateway resource to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteGatewayResourceProfile(AuthzToken authzToken, String gatewayID) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteGatewayResourceProfile(gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while removing gateway resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while removing gateway resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Compute Resource Preference to a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be added.
* @param computeResourceId Preferences related to a particular compute resource
* @param computeResourcePreference The ComputeResourcePreference object to be added to the resource profile.
* @return status
* Returns a success/failure of the addition. If a profile already exists, this operation will fail.
* Instead an update should be used.
*/
@Override
@SecurityCheck
public boolean addGatewayComputeResourcePreference(AuthzToken authzToken, String gatewayID, String computeResourceId,
ComputeResourcePreference computeResourcePreference) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.addGatewayComputeResourcePreference(gatewayID, computeResourceId, computeResourcePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while registering gateway resource profile preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering gateway resource profile preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean addGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageResourceId, StoragePreference dataStoragePreference)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.addGatewayStoragePreference(gatewayID, storageResourceId, dataStoragePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while registering gateway resource profile preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering gateway resource profile preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a Compute Resource Preference of a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be requested
* @param computeResourceId Preferences related to a particular compute resource
* @return computeResourcePreference
* Returns the ComputeResourcePreference object.
*/
@Override
@SecurityCheck
public ComputeResourcePreference getGatewayComputeResourcePreference(AuthzToken authzToken, String gatewayID, String computeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ComputeResourcePreference result = regClient.getGatewayComputeResourcePreference(gatewayID, computeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading gateway compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public StoragePreference getGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
StoragePreference result = regClient.getGatewayStoragePreference(gatewayID, storageId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading gateway data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all Compute Resource Preferences of a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be requested
* @return computeResourcePreference
* Returns the ComputeResourcePreference object.
*/
@Override
@SecurityCheck
public List<ComputeResourcePreference> getAllGatewayComputeResourcePreferences(AuthzToken authzToken, String gatewayID)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<ComputeResourcePreference> result = regClient.getAllGatewayComputeResourcePreferences(gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway compute resource preferences...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading gateway compute resource preferences. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<StoragePreference> getAllGatewayStoragePreferences(AuthzToken authzToken, String gatewayID) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<StoragePreference> result = regClient.getAllGatewayStoragePreferences(gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway data storage preferences...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading gateway data storage preferences. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<GatewayResourceProfile> getAllGatewayResourceProfiles(AuthzToken authzToken) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<GatewayResourceProfile> result = regClient.getAllGatewayResourceProfiles();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading retrieving all gateway profiles. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Compute Resource Preference to a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be updated.
* @param computeResourceId Preferences related to a particular compute resource
* @param computeResourcePreference The ComputeResourcePreference object to be updated to the resource profile.
* @return status
* Returns a success/failure of the updation.
*/
@Override
@SecurityCheck
public boolean updateGatewayComputeResourcePreference(AuthzToken authzToken, String gatewayID, String computeResourceId,
ComputeResourcePreference computeResourcePreference)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGatewayComputeResourcePreference(gatewayID, computeResourceId, computeResourcePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageId, StoragePreference dataStoragePreference) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGatewayStoragePreference(gatewayID, storageId, dataStoragePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete the Compute Resource Preference of a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be deleted.
* @param computeResourceId Preferences related to a particular compute resource
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteGatewayComputeResourcePreference(AuthzToken authzToken, String gatewayID, String computeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteGatewayComputeResourcePreference(gatewayID, computeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteGatewayStoragePreference(gatewayID, storageId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<SSHAccountProvisioner> getSSHAccountProvisioners(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
List<SSHAccountProvisioner> sshAccountProvisioners = new ArrayList<>();
List<SSHAccountProvisionerProvider> sshAccountProvisionerProviders = SSHAccountProvisionerFactory.getSSHAccountProvisionerProviders();
for (SSHAccountProvisionerProvider provider : sshAccountProvisionerProviders) {
// TODO: Move this Thrift conversion to utility class
SSHAccountProvisioner sshAccountProvisioner = new SSHAccountProvisioner();
sshAccountProvisioner.setCanCreateAccount(provider.canCreateAccount());
sshAccountProvisioner.setCanInstallSSHKey(provider.canInstallSSHKey());
sshAccountProvisioner.setName(provider.getName());
List<SSHAccountProvisionerConfigParam> sshAccountProvisionerConfigParams = new ArrayList<>();
for (ConfigParam configParam : provider.getConfigParams()) {
SSHAccountProvisionerConfigParam sshAccountProvisionerConfigParam = new SSHAccountProvisionerConfigParam();
sshAccountProvisionerConfigParam.setName(configParam.getName());
sshAccountProvisionerConfigParam.setDescription(configParam.getDescription());
sshAccountProvisionerConfigParam.setIsOptional(configParam.isOptional());
switch (configParam.getType()){
case STRING:
sshAccountProvisionerConfigParam.setType(SSHAccountProvisionerConfigParamType.STRING);
break;
case CRED_STORE_PASSWORD_TOKEN:
sshAccountProvisionerConfigParam.setType(SSHAccountProvisionerConfigParamType.CRED_STORE_PASSWORD_TOKEN);
break;
}
sshAccountProvisionerConfigParams.add(sshAccountProvisionerConfigParam);
}
sshAccountProvisioner.setConfigParams(sshAccountProvisionerConfigParams);
sshAccountProvisioners.add(sshAccountProvisioner);
}
return sshAccountProvisioners;
}
@Override
@SecurityCheck
public boolean doesUserHaveSSHAccount(AuthzToken authzToken, String computeResourceId, String userId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
return SSHAccountManager.doesUserHaveSSHAccount(gatewayId, computeResourceId, userId);
} catch (Exception e) {
String errorMessage = "Error occurred while checking if [" + userId + "] has an SSH Account on [" +
computeResourceId + "].";
logger.error(errorMessage, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMessage + " More info : " + e.getMessage());
throw exception;
}
}
@Override
@SecurityCheck
public UserComputeResourcePreference setupUserComputeResourcePreferencesForSSH(AuthzToken authzToken, String computeResourceId, String userId, String airavataCredStoreToken) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
CredentialStoreService.Client csClient = csClientPool.getResource();
SSHCredential sshCredential = null;
try {
sshCredential = csClient.getSSHCredential(airavataCredStoreToken, gatewayId);
}catch (Exception e){
logger.error("Error occurred while retrieving SSH Credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH Credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
try {
UserComputeResourcePreference userComputeResourcePreference = SSHAccountManager.setupSSHAccount(gatewayId, computeResourceId, userId, sshCredential);
return userComputeResourcePreference;
}catch (Exception e){
logger.error("Error occurred while automatically setting up SSH account for user [" + userId + "]", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while automatically setting up SSH account for user [" + userId + "]. More info : " + e.getMessage());
throw exception;
}
}
/**
* Register a User Resource Profile.
*
* @param userResourceProfile User Resource Profile Object.
* The userId should be obtained from Airavata user profile registration and passed to register a corresponding
* resource profile.
* @return status.
* Returns a success/failure of the registration.
*/
@Override
@SecurityCheck
public String registerUserResourceProfile(AuthzToken authzToken, UserResourceProfile userResourceProfile)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerUserResourceProfile(userResourceProfile);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while registering user resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering user resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the given User Resource Profile.
*
* @param userId The identifier for the requested User resource
*
* @param gatewayID The identifier to link a gateway for the requested User resource
*
* @return userResourceProfile
* User Resource Profile Object.
*/
@Override
@SecurityCheck
public UserResourceProfile getUserResourceProfile(AuthzToken authzToken, String userId, String gatewayID) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UserResourceProfile result = regClient.getUserResourceProfile(userId, gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while retrieving user resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a User Resource Profile.
*
* @param userId : The identifier for the requested user resource profile to be updated.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userResourceProfile User Resource Profile Object.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateUserResourceProfile(AuthzToken authzToken,
String userId,
String gatewayID,
UserResourceProfile userResourceProfile) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUserResourceProfile(userId, gatewayID, userResourceProfile);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while updating user resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete the given User Resource Profile.
*
* @param userId : The identifier for the requested userId resource to be deleted.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteUserResourceProfile(AuthzToken authzToken, String userId, String gatewayID) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteUserResourceProfile(userId, gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while removing user resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while removing user resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Compute Resource Preference to a registered User Resource profile.
*
* @param userId The identifier for the User Resource profile to be added.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userComputeResourceId Preferences related to a particular compute resource
* @param userComputeResourcePreference The ComputeResourcePreference object to be added to the resource profile.
* @return status
* Returns a success/failure of the addition. If a profile already exists, this operation will fail.
* Instead an update should be used.
*/
@Override
@SecurityCheck
public boolean addUserComputeResourcePreference(AuthzToken authzToken, String userId, String gatewayID, String userComputeResourceId,
UserComputeResourcePreference userComputeResourcePreference) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.addUserComputeResourcePreference(userId, gatewayID, userComputeResourceId, userComputeResourcePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while registering user resource profile preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering user resource profile preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean addUserStoragePreference(AuthzToken authzToken, String userId, String gatewayID, String userStorageResourceId, UserStoragePreference dataStoragePreference)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.addUserStoragePreference(userId, gatewayID, userStorageResourceId, dataStoragePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while registering user storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering user storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a Compute Resource Preference of a registered User Resource profile.
*
* @param userId : The identifier for the User Resource profile to be requested
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userComputeResourceId Preferences related to a particular compute resource
* @return computeResourcePreference
* Returns the ComputeResourcePreference object.
*/
@Override
@SecurityCheck
public UserComputeResourcePreference getUserComputeResourcePreference(AuthzToken authzToken, String userId, String gatewayID, String userComputeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UserComputeResourcePreference result = regClient.getUserComputeResourcePreference(userId, gatewayID, userComputeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading user compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public UserStoragePreference getUserStoragePreference(AuthzToken authzToken, String userId, String gatewayID, String userStorageId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UserStoragePreference result = regClient.getUserStoragePreference(userId, gatewayID, userStorageId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading user data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all User Compute Resource Preferences of a registered gateway profile.
*
* @param userId
* @param gatewayID The identifier for the gateway profile to be requested
* @return computeResourcePreference
* Returns the ComputeResourcePreference object.
*/
@Override
@SecurityCheck
public List<UserComputeResourcePreference> getAllUserComputeResourcePreferences(AuthzToken authzToken, String userId, String gatewayID)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<UserComputeResourcePreference> result = regClient.getAllUserComputeResourcePreferences(userId, gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading User compute resource preferences...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading User compute resource preferences. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<UserStoragePreference> getAllUserStoragePreferences(AuthzToken authzToken, String userId, String gatewayID) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<UserStoragePreference> result = regClient.getAllUserStoragePreferences(userId, gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading User data storage preferences...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading User data storage preferences. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<UserResourceProfile> getAllUserResourceProfiles(AuthzToken authzToken) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<UserResourceProfile> result = regClient.getAllUserResourceProfiles();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading retrieving all user resource profiles. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Compute Resource Preference to a registered User Resource profile.
*
* @param userId : The identifier for the User Resource profile to be updated.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userComputeResourceId Preferences related to a particular compute resource
* @param userComputeResourcePreference The ComputeResourcePreference object to be updated to the resource profile.
* @return status
* Returns a success/failure of the updation.
*/
@Override
@SecurityCheck
public boolean updateUserComputeResourcePreference(AuthzToken authzToken, String userId, String gatewayID, String userComputeResourceId,
UserComputeResourcePreference userComputeResourcePreference)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUserComputeResourcePreference(userId, gatewayID, userComputeResourceId, userComputeResourcePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateUserStoragePreference(AuthzToken authzToken, String userId, String gatewayID, String userStorageId, UserStoragePreference dataStoragePreference) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUserStoragePreference(userId, gatewayID, userStorageId, dataStoragePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete the Compute Resource Preference of a registered User Resource profile.
*
* @param userId The identifier for the User profile to be deleted.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userComputeResourceId Preferences related to a particular compute resource
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteUserComputeResourcePreference(AuthzToken authzToken, String userId,String gatewayID, String userComputeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteUserComputeResourcePreference(userId, gatewayID, userComputeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteUserStoragePreference(AuthzToken authzToken, String userId, String gatewayID, String userStorageId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteUserStoragePreference(userId, gatewayID, userStorageId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<String> getAllWorkflows(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<String> result = regClient.getAllWorkflows(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retrieving all workflow template Ids.";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
public List<QueueStatusModel> getLatestQueueStatuses(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<QueueStatusModel> result = regClient.getLatestQueueStatuses();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retrieving queue statuses";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public WorkflowModel getWorkflow(AuthzToken authzToken, String workflowTemplateId)
throws InvalidRequestException, AiravataClientException, AuthorizationException, AiravataSystemException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
WorkflowModel result = regClient.getWorkflow(workflowTemplateId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retrieving the workflow "+workflowTemplateId+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public void deleteWorkflow(AuthzToken authzToken, String workflowTemplateId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
regClient.deleteWorkflow(workflowTemplateId);
registryClientPool.returnResource(regClient);
return;
} catch (Exception e) {
String msg = "Error in deleting the workflow "+workflowTemplateId+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String registerWorkflow(AuthzToken authzToken, String gatewayId, WorkflowModel workflow)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerWorkflow(gatewayId, workflow);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in registering the workflow "+workflow.getName()+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateWorkflow(AuthzToken authzToken, String workflowTemplateId, WorkflowModel workflow)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
regClient.updateWorkflow(workflowTemplateId, workflow);
registryClientPool.returnResource(regClient);
return;
} catch (Exception e) {
String msg = "Error in updating the workflow "+workflow.getName()+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String getWorkflowTemplateId(AuthzToken authzToken, String workflowName)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.getWorkflowTemplateId(workflowName);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retrieving the workflow template id for "+workflowName+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean isWorkflowExistWithName(AuthzToken authzToken, String workflowName)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.isWorkflowExistWithName(workflowName);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in veriying the workflow for workflow name "+workflowName+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* ReplicaCatalog Related Methods
* @return
* @throws TException
* @throws ApplicationSettingsException
*/
@Override
@SecurityCheck
public String registerDataProduct(AuthzToken authzToken, DataProductModel dataProductModel) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerDataProduct(dataProductModel);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in registering the data resource"+dataProductModel.getProductName()+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public DataProductModel getDataProduct(AuthzToken authzToken, String productUri) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
DataProductModel result = regClient.getDataProduct(productUri);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retreiving the data product "+productUri+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String registerReplicaLocation(AuthzToken authzToken, DataReplicaLocationModel replicaLocationModel) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerReplicaLocation(replicaLocationModel);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retreiving the replica "+replicaLocationModel.getReplicaName()+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public DataProductModel getParentDataProduct(AuthzToken authzToken, String productUri) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
DataProductModel result = regClient.getParentDataProduct(productUri);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retreiving the parent data product for "+ productUri+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<DataProductModel> getChildDataProducts(AuthzToken authzToken, String productUri) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<DataProductModel> result = regClient.getChildDataProducts(productUri);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retreiving the child products for "+productUri+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Group Manager and Data Sharing Related API methods
*
* @param authzToken
* @param resourceId
* @param resourceType
* @param userPermissionList
*/
@Override
@SecurityCheck
public boolean shareResourceWithUsers(AuthzToken authzToken, String resourceId, ResourceType resourceType,
Map<String, ResourcePermissionType> userPermissionList) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: first verify that authenticating user is OWNER of the resource
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
for(Map.Entry<String, ResourcePermissionType> userPermission : userPermissionList.entrySet()){
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
if(userPermission.getValue().equals(ResourcePermissionType.WRITE))
sharingClient.shareEntityWithUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE", true);
else if(userPermission.getValue().equals(ResourcePermissionType.READ))
sharingClient.shareEntityWithUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ", true);
else if(userPermission.getValue().equals(ResourcePermissionType.EXEC))
sharingClient.shareEntityWithUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "EXEC", true);
else {
logger.error("Invalid ResourcePermissionType : " + userPermission.getValue().toString());
throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION);
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return true;
} catch (Exception e) {
String msg = "Error in sharing resource with users. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean shareResourceWithGroups(AuthzToken authzToken, String resourceId, ResourceType resourceType,
Map<String, ResourcePermissionType> groupPermissionList)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: first verify that authenticating user is OWNER of the resource
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
for(Map.Entry<String, ResourcePermissionType> groupPermission : groupPermissionList.entrySet()){
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
if(groupPermission.getValue().equals(ResourcePermissionType.WRITE))
sharingClient.shareEntityWithGroups(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE", true);
else if(groupPermission.getValue().equals(ResourcePermissionType.READ))
sharingClient.shareEntityWithGroups(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ", true);
else if(groupPermission.getValue().equals(ResourcePermissionType.EXEC))
sharingClient.shareEntityWithGroups(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "EXEC", true);
else {
logger.error("Invalid ResourcePermissionType : " + groupPermission.getValue().toString());
throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION);
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return true;
} catch (Exception e) {
String msg = "Error in sharing resource with groups. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean revokeSharingOfResourceFromUsers(AuthzToken authzToken, String resourceId, ResourceType resourceType,
Map<String, ResourcePermissionType> userPermissionList) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: first verify that authenticating user is OWNER of the resource
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
for(Map.Entry<String, ResourcePermissionType> userPermission : userPermissionList.entrySet()){
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
if(userPermission.getValue().equals(ResourcePermissionType.WRITE))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE");
else if(userPermission.getValue().equals(ResourcePermissionType.READ))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ");
else if(userPermission.getValue().equals(ResourcePermissionType.EXEC))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "EXEC");
else {
logger.error("Invalid ResourcePermissionType : " + userPermission.getValue().toString());
throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION);
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return true;
} catch (Exception e) {
String msg = "Error in revoking access to resource from users. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean revokeSharingOfResourceFromGroups(AuthzToken authzToken, String resourceId, ResourceType resourceType,
Map<String, ResourcePermissionType> groupPermissionList)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: first verify that authenticating user is OWNER of the resource
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
final String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
try {
// Prevent removing Admins WRITE access and Read Only Admins READ access
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
if (groupPermissionList.containsKey(gatewayGroups.getAdminsGroupId())
&& groupPermissionList.get(gatewayGroups.getAdminsGroupId()).equals(ResourcePermissionType.WRITE)) {
throw new Exception("Not allowed to remove Admins group's WRITE access.");
}
if (groupPermissionList.containsKey(gatewayGroups.getReadOnlyAdminsGroupId())
&& groupPermissionList.get(gatewayGroups.getAdminsGroupId()).equals(ResourcePermissionType.READ)) {
throw new Exception("Not allowed to remove Read Only Admins group's READ access.");
}
for(Map.Entry<String, ResourcePermissionType> groupPermission : groupPermissionList.entrySet()){
if(groupPermission.getValue().equals(ResourcePermissionType.WRITE))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "WRITE");
else if(groupPermission.getValue().equals(ResourcePermissionType.READ))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "READ");
else if(groupPermission.getValue().equals(ResourcePermissionType.EXEC))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "EXEC");
else {
logger.error("Invalid ResourcePermissionType : " + groupPermission.getValue().toString());
throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION);
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return true;
} catch (Exception e) {
String msg = "Error in revoking access to resource from groups. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<String> getAllAccessibleUsers(AuthzToken authzToken, String resourceId, ResourceType resourceType, ResourcePermissionType permissionType) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
HashSet<String> accessibleUsers = new HashSet<>();
if (permissionType.equals(ResourcePermissionType.WRITE)) {
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":WRITE").stream().forEach(u -> accessibleUsers.add(u.userId));
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":OWNER").stream().forEach(u -> accessibleUsers.add(u.userId));
} else if (permissionType.equals(ResourcePermissionType.READ)) {
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":READ").stream().forEach(u -> accessibleUsers.add(u.userId));
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":OWNER").stream().forEach(u -> accessibleUsers.add(u.userId));
} else if (permissionType.equals(ResourcePermissionType.OWNER)) {
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":OWNER").stream().forEach(u -> accessibleUsers.add(u.userId));
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return new ArrayList<>(accessibleUsers);
} catch (Exception e) {
String msg = "Error in getting all accessible users for resource. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String createGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: verify that gatewayId in groupResourceProfile matches authzToken gatewayId
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
try {
String groupResourceProfileId = regClient.createGroupResourceProfile(groupResourceProfile);
if(ServerSettings.isEnableSharing()) {
try {
Entity entity = new Entity();
entity.setEntityId(groupResourceProfileId);
final String domainId = groupResourceProfile.getGatewayId();
entity.setDomainId(groupResourceProfile.getGatewayId());
entity.setEntityTypeId(groupResourceProfile.getGatewayId() + ":" + "GROUP_RESOURCE_PROFILE");
entity.setOwnerId(userName + "@" + groupResourceProfile.getGatewayId());
entity.setName(groupResourceProfile.getGroupResourceProfileName());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, groupResourceProfile.getGatewayId());
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
logger.error("Rolling back group resource profile creation Group Resource Profile ID : " + groupResourceProfileId);
regClient.removeGroupResourceProfile(groupResourceProfileId);
AiravataSystemException ase = new AiravataSystemException();
ase.setMessage("Failed to create sharing registry record");
throw ase;
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupResourceProfileId;
} catch (Exception e) {
String msg = "Error creating group resource profile.";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfile.getGroupResourceProfileId(), gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to update group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to update group resource profile");
}
}
regClient.updateGroupResourceProfile(groupResourceProfile);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
} catch (Exception e) {
String msg = "Error updating group resource profile. groupResourceProfileId: "+groupResourceProfile.getGroupResourceProfileId();
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public GroupResourceProfile getGroupResourceProfile(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
GroupResourceProfile groupResourceProfile = regClient.getGroupResourceProfile(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupResourceProfile;
} catch (Exception e) {
String msg = "Error retrieving group resource profile. groupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean removeGroupResourceProfile(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to remove group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to remove group resource profile");
}
}
boolean result = regClient.removeGroupResourceProfile(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
String msg = "Error removing group resource profile. groupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<GroupResourceProfile> getGroupResourceList(AuthzToken authzToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
try {
List<String> accessibleGroupResProfileIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> filters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(gatewayId + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name());
filters.add(searchCriteria);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, filters, 0, -1).stream().forEach(p -> accessibleGroupResProfileIds
.add(p.entityId));
}
List<GroupResourceProfile> groupResourceProfileList = regClient.getGroupResourceList(gatewayId, accessibleGroupResProfileIds);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupResourceProfileList;
} catch (Exception e) {
String msg = "Error retrieving list group resource profile list. GatewayId: "+ gatewayId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean removeGroupComputePrefs(AuthzToken authzToken, String computeResourceId, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to remove group compute preferences");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to remove group compute preferences");
}
}
boolean result = regClient.removeGroupComputePrefs(computeResourceId, groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
String msg = "Error removing group compute resource preferences. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean removeGroupComputeResourcePolicy(AuthzToken authzToken, String resourcePolicyId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
ComputeResourcePolicy computeResourcePolicy = regClient.getGroupComputeResourcePolicy(resourcePolicyId);
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
computeResourcePolicy.getGroupResourceProfileId(), gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to remove group compute resource policy");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to remove group compute resource policy");
}
}
boolean result = regClient.removeGroupComputeResourcePolicy(resourcePolicyId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
String msg = "Error removing group compute resource policy. ResourcePolicyId: "+ resourcePolicyId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean removeGroupBatchQueueResourcePolicy(AuthzToken authzToken, String resourcePolicyId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
BatchQueueResourcePolicy batchQueueResourcePolicy = regClient.getBatchQueueResourcePolicy(resourcePolicyId);
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
batchQueueResourcePolicy.getGroupResourceProfileId(), gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to remove batch queue resource policy");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to remove batch queue resource policy");
}
}
boolean result = regClient.removeGroupBatchQueueResourcePolicy(resourcePolicyId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
String msg = "Error removing batch queue resource policy. ResourcePolicyId: "+ resourcePolicyId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public GroupComputeResourcePreference getGroupComputeResourcePreference(AuthzToken authzToken, String computeResourceId, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
GroupComputeResourcePreference groupComputeResourcePreference = regClient.getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupComputeResourcePreference;
} catch (Exception e) {
String msg = "Error retrieving Group compute preference. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public ComputeResourcePolicy getGroupComputeResourcePolicy(AuthzToken authzToken, String resourcePolicyId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
ComputeResourcePolicy computeResourcePolicy = regClient.getGroupComputeResourcePolicy(resourcePolicyId);
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
computeResourcePolicy.getGroupResourceProfileId(), gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
ComputeResourcePolicy computeResourcePolicy = regClient.getGroupComputeResourcePolicy(resourcePolicyId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return computeResourcePolicy;
} catch (Exception e) {
String msg = "Error retrieving Group compute resource policy. ResourcePolicyId: "+ resourcePolicyId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public BatchQueueResourcePolicy getBatchQueueResourcePolicy(AuthzToken authzToken, String resourcePolicyId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
BatchQueueResourcePolicy batchQueueResourcePolicy = regClient.getBatchQueueResourcePolicy(resourcePolicyId);
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
batchQueueResourcePolicy.getGroupResourceProfileId(), gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
BatchQueueResourcePolicy batchQueueResourcePolicy = regClient.getBatchQueueResourcePolicy(resourcePolicyId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return batchQueueResourcePolicy;
} catch (Exception e) {
String msg = "Error retrieving Group batch queue resource policy. ResourcePolicyId: "+ resourcePolicyId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<GroupComputeResourcePreference> getGroupComputeResourcePrefList(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
List<GroupComputeResourcePreference> groupComputeResourcePreferenceList = regClient.getGroupComputeResourcePrefList(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupComputeResourcePreferenceList;
} catch (Exception e) {
String msg = "Error retrieving Group compute resource preference. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<BatchQueueResourcePolicy> getGroupBatchQueueResourcePolicyList(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
List<BatchQueueResourcePolicy> batchQueueResourcePolicyList = regClient.getGroupBatchQueueResourcePolicyList(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return batchQueueResourcePolicyList;
} catch (Exception e) {
String msg = "Error retrieving Group batch queue resource policy list. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<ComputeResourcePolicy> getGroupComputeResourcePolicyList(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
List<ComputeResourcePolicy> computeResourcePolicyList = regClient.getGroupComputeResourcePolicyList(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return computeResourcePolicyList;
} catch (Exception e) {
String msg = "Error retrieving Group compute resource policy list. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
private void submitExperiment(String gatewayId,String experimentId) throws AiravataException {
ExperimentSubmitEvent event = new ExperimentSubmitEvent(experimentId, gatewayId);
MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, "LAUNCH.EXP-" + UUID.randomUUID().toString(), gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
experimentPublisher.publish(messageContext);
}
private void submitCancelExperiment(String gatewayId, String experimentId) throws AiravataException {
ExperimentSubmitEvent event = new ExperimentSubmitEvent(experimentId, gatewayId);
MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT_CANCEL, "CANCEL.EXP-" + UUID.randomUUID().toString(), gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
experimentPublisher.publish(messageContext);
}
private GatewayGroups retrieveGatewayGroups(RegistryService.Client regClient, String gatewayId) throws TException {
return regClient.getGatewayGroups(gatewayId);
}
} | airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/handler/AiravataServerHandler.java | /**
*
* 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.
*/
package org.apache.airavata.api.server.handler;
import org.apache.airavata.accountprovisioning.ConfigParam;
import org.apache.airavata.accountprovisioning.SSHAccountManager;
import org.apache.airavata.accountprovisioning.SSHAccountProvisionerFactory;
import org.apache.airavata.accountprovisioning.SSHAccountProvisionerProvider;
import org.apache.airavata.api.Airavata;
import org.apache.airavata.api.airavata_apiConstants;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.common.utils.Constants;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftClientPool;
import org.apache.airavata.credential.store.cpi.CredentialStoreService;
import org.apache.airavata.messaging.core.MessageContext;
import org.apache.airavata.messaging.core.MessagingFactory;
import org.apache.airavata.messaging.core.Publisher;
import org.apache.airavata.messaging.core.Type;
import org.apache.airavata.model.WorkflowModel;
import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisioner;
import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisionerConfigParam;
import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisionerConfigParamType;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription;
import org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule;
import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.appcatalog.gatewaygroups.GatewayGroups;
import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference;
import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile;
import org.apache.airavata.model.appcatalog.gatewayprofile.StoragePreference;
import org.apache.airavata.model.appcatalog.groupresourceprofile.BatchQueueResourcePolicy;
import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile;
import org.apache.airavata.model.appcatalog.storageresource.StorageResourceDescription;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserResourceProfile;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserStoragePreference;
import org.apache.airavata.model.application.io.InputDataObjectType;
import org.apache.airavata.model.application.io.OutputDataObjectType;
import org.apache.airavata.model.commons.airavata_commonsConstants;
import org.apache.airavata.model.credential.store.*;
import org.apache.airavata.model.data.movement.DMType;
import org.apache.airavata.model.data.movement.*;
import org.apache.airavata.model.data.replica.DataProductModel;
import org.apache.airavata.model.data.replica.DataReplicaLocationModel;
import org.apache.airavata.model.error.*;
import org.apache.airavata.model.experiment.*;
import org.apache.airavata.model.group.ResourcePermissionType;
import org.apache.airavata.model.group.ResourceType;
import org.apache.airavata.model.job.JobModel;
import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent;
import org.apache.airavata.model.messaging.event.ExperimentSubmitEvent;
import org.apache.airavata.model.messaging.event.MessageType;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.model.security.AuthzToken;
import org.apache.airavata.model.status.ExperimentState;
import org.apache.airavata.model.status.ExperimentStatus;
import org.apache.airavata.model.status.JobStatus;
import org.apache.airavata.model.status.QueueStatusModel;
import org.apache.airavata.model.workspace.Gateway;
import org.apache.airavata.model.workspace.Notification;
import org.apache.airavata.model.workspace.Project;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.airavata.service.security.interceptor.SecurityCheck;
import org.apache.airavata.sharing.registry.models.*;
import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class AiravataServerHandler implements Airavata.Iface {
private static final Logger logger = LoggerFactory.getLogger(AiravataServerHandler.class);
private Publisher statusPublisher;
private Publisher experimentPublisher;
private ThriftClientPool<SharingRegistryService.Client> sharingClientPool;
private ThriftClientPool<RegistryService.Client> registryClientPool;
private ThriftClientPool<CredentialStoreService.Client> csClientPool;
public AiravataServerHandler() {
try {
statusPublisher = MessagingFactory.getPublisher(Type.STATUS);
experimentPublisher = MessagingFactory.getPublisher(Type.EXPERIMENT_LAUNCH);
GenericObjectPool.Config poolConfig = new GenericObjectPool.Config();
poolConfig.maxActive = 100;
poolConfig.minIdle = 5;
poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
poolConfig.testOnBorrow = true;
poolConfig.testWhileIdle = true;
poolConfig.numTestsPerEvictionRun = 10;
poolConfig.maxWait = 3000;
sharingClientPool = new ThriftClientPool<>(
tProtocol -> new SharingRegistryService.Client(tProtocol), poolConfig, ServerSettings.getSharingRegistryHost(),
Integer.parseInt(ServerSettings.getSharingRegistryPort()));
registryClientPool = new ThriftClientPool<>(
tProtocol -> new RegistryService.Client(tProtocol), poolConfig, ServerSettings.getRegistryServerHost(),
Integer.parseInt(ServerSettings.getRegistryServerPort()));
csClientPool = new ThriftClientPool<>(
tProtocol -> new CredentialStoreService.Client(tProtocol), poolConfig, ServerSettings.getCredentialStoreServerHost(),
Integer.parseInt(ServerSettings.getCredentialStoreServerPort()));
initSharingRegistry();
postInitDefaultGateway();
} catch (ApplicationSettingsException e) {
logger.error("Error occured while reading airavata-server properties..", e);
} catch (AiravataException e) {
logger.error("Error occured while reading airavata-server properties..", e);
} catch (TException e) {
logger.error("Error occured while reading airavata-server properties..", e);
}
}
/**
* This method creates a password token for the default gateway profile. Default gateway is originally initialized
* at the registry server but we can not add the password token at that step as the credential store is not initialized
* before registry server.
*/
private void postInitDefaultGateway() {
RegistryService.Client registryClient = registryClientPool.getResource();
try {
GatewayResourceProfile gatewayResourceProfile = registryClient.getGatewayResourceProfile(ServerSettings.getDefaultUserGateway());
if (gatewayResourceProfile != null && gatewayResourceProfile.getCredentialStoreToken() == null) {
logger.debug("Starting to add the password credential for default gateway : " +
ServerSettings.getDefaultUserGateway());
PasswordCredential passwordCredential = new PasswordCredential();
passwordCredential.setPortalUserName(ServerSettings.getDefaultUser());
passwordCredential.setGatewayId(ServerSettings.getDefaultUserGateway());
passwordCredential.setLoginUserName(ServerSettings.getDefaultUser());
passwordCredential.setPassword(ServerSettings.getDefaultUserPassword());
passwordCredential.setDescription("Credentials for default gateway");
CredentialStoreService.Client csClient = csClientPool.getResource();
String token = null;
try {
logger.info("Creating password credential for default gateway");
token = csClient.addPasswordCredential(passwordCredential);
csClientPool.returnResource(csClient);
} catch (Exception ex) {
logger.error("Failed to create the password credential for the default gateway : " +
ServerSettings.getDefaultUserGateway(), ex);
if (csClient != null) {
csClientPool.returnBrokenResource(csClient);
}
}
if (token != null) {
logger.debug("Adding password credential token " + token +" to the default gateway : " + ServerSettings.getDefaultUserGateway());
gatewayResourceProfile.setIdentityServerPwdCredToken(token);
registryClient.updateGatewayResourceProfile(ServerSettings.getDefaultUserGateway(), gatewayResourceProfile);
}
registryClientPool.returnResource(registryClient);
}
} catch (Exception e) {
logger.error("Failed to add the password credentials for the default gateway", e);
if (registryClient != null) {
registryClientPool.returnBrokenResource(registryClient);
}
}
}
private void initSharingRegistry() throws ApplicationSettingsException, TException {
SharingRegistryService.Client client = sharingClientPool.getResource();
try {
if (!client.isDomainExists(ServerSettings.getDefaultUserGateway())) {
Domain domain = new Domain();
domain.setDomainId(ServerSettings.getDefaultUserGateway());
domain.setName(ServerSettings.getDefaultUserGateway());
domain.setDescription("Domain entry for " + domain.name);
client.createDomain(domain);
User user = new User();
user.setDomainId(domain.domainId);
user.setUserId(ServerSettings.getDefaultUser() + "@" + ServerSettings.getDefaultUserGateway());
user.setUserName(ServerSettings.getDefaultUser());
client.createUser(user);
//Creating Entity Types for each domain
EntityType entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId + ":PROJECT");
entityType.setDomainId(domain.domainId);
entityType.setName("PROJECT");
entityType.setDescription("Project entity type");
client.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId + ":EXPERIMENT");
entityType.setDomainId(domain.domainId);
entityType.setName("EXPERIMENT");
entityType.setDescription("Experiment entity type");
client.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId + ":FILE");
entityType.setDomainId(domain.domainId);
entityType.setName("FILE");
entityType.setDescription("File entity type");
client.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":"+ResourceType.APPLICATION_DEPLOYMENT.name());
entityType.setDomainId(domain.domainId);
entityType.setName("APPLICATION-DEPLOYMENT");
entityType.setDescription("Application Deployment entity type");
client.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":"+ResourceType.GROUP_RESOURCE_PROFILE.name());
entityType.setDomainId(domain.domainId);
entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name());
entityType.setDescription("Group Resource Profile entity type");
client.createEntityType(entityType);
//Creating Permission Types for each domain
PermissionType permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId + ":READ");
permissionType.setDomainId(domain.domainId);
permissionType.setName("READ");
permissionType.setDescription("Read permission type");
client.createPermissionType(permissionType);
permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId + ":WRITE");
permissionType.setDomainId(domain.domainId);
permissionType.setName("WRITE");
permissionType.setDescription("Write permission type");
client.createPermissionType(permissionType);
permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId+":EXEC");
permissionType.setDomainId(domain.domainId);
permissionType.setName("EXEC");
permissionType.setDescription("Execute permission type");
client.createPermissionType(permissionType);
}
sharingClientPool.returnResource(client);
} catch (Exception ex) {
sharingClientPool.returnBrokenResource(client);
throw ex;
}
}
/**
* Query Airavata to fetch the API version
*/
@Override
@SecurityCheck
public String getAPIVersion(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException,
AiravataSystemException, AuthorizationException, TException {
return airavata_apiConstants.AIRAVATA_API_VERSION;
}
/**
* Verify if User Exists within Airavata.
*
* @param authzToken
* @param gatewayId
* @param userName
* @return true/false
*/
@Override
public boolean isUserExists(AuthzToken authzToken, String gatewayId, String userName) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client client = registryClientPool.getResource();
try {
boolean isExists = client.isUserExists(gatewayId, userName);
registryClientPool.returnResource(client);
return isExists;
} catch (Exception e) {
logger.error("Error while verifying user", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while verifying user. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(client);
throw exception;
}
}
@Override
@SecurityCheck
public String addGateway(AuthzToken authzToken, Gateway gateway) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
RegistryService.Client registryClient = registryClientPool.getResource();
try {
String gatewayId = registryClient.addGateway(gateway);
Domain domain = new Domain();
domain.setDomainId(gateway.getGatewayId());
domain.setName(gateway.getGatewayName());
domain.setDescription("Domain entry for " + domain.name);
sharingClient.createDomain(domain);
//Creating Entity Types for each domain
EntityType entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":PROJECT");
entityType.setDomainId(domain.domainId);
entityType.setName("PROJECT");
entityType.setDescription("Project entity type");
sharingClient.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":EXPERIMENT");
entityType.setDomainId(domain.domainId);
entityType.setName("EXPERIMENT");
entityType.setDescription("Experiment entity type");
sharingClient.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":FILE");
entityType.setDomainId(domain.domainId);
entityType.setName("FILE");
entityType.setDescription("File entity type");
sharingClient.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":"+ResourceType.APPLICATION_DEPLOYMENT.name());
entityType.setDomainId(domain.domainId);
entityType.setName("APPLICATION-DEPLOYMENT");
entityType.setDescription("Application Deployment entity type");
sharingClient.createEntityType(entityType);
entityType = new EntityType();
entityType.setEntityTypeId(domain.domainId+":"+ResourceType.GROUP_RESOURCE_PROFILE.name());
entityType.setDomainId(domain.domainId);
entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name());
entityType.setDescription("Group Resource Profile entity type");
sharingClient.createEntityType(entityType);
//Creating Permission Types for each domain
PermissionType permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId+":READ");
permissionType.setDomainId(domain.domainId);
permissionType.setName("READ");
permissionType.setDescription("Read permission type");
sharingClient.createPermissionType(permissionType);
permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId+":WRITE");
permissionType.setDomainId(domain.domainId);
permissionType.setName("WRITE");
permissionType.setDescription("Write permission type");
sharingClient.createPermissionType(permissionType);
permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.domainId+":EXEC");
permissionType.setDomainId(domain.domainId);
permissionType.setName("EXEC");
permissionType.setDescription("Execute permission type");
sharingClient.createPermissionType(permissionType);
//Create an "everyone" group for the domain
String groupId = "everyone@" + domain.domainId;
UserGroup userGroup = new UserGroup();
userGroup.setGroupId(groupId);
userGroup.setDomainId(domain.domainId);
userGroup.setGroupCardinality(GroupCardinality.MULTI_USER);
userGroup.setCreatedTime(System.currentTimeMillis());
userGroup.setUpdatedTime(System.currentTimeMillis());
userGroup.setOwnerId(authzToken.getClaimsMap().get(Constants.USER_NAME) + "@" + domain.domainId);
userGroup.setName("everyone");
userGroup.setDescription("Default Group");
userGroup.setGroupType(GroupType.DOMAIN_LEVEL_GROUP);
sharingClient.createGroup(userGroup);
registryClientPool.returnResource(registryClient);
sharingClientPool.returnResource(sharingClient);
return gatewayId;
} catch (Exception e) {
logger.error("Error while adding gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding gateway. More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(registryClient);
throw exception;
}
}
/**
* Get all users in the gateway
*
* @param authzToken
* @param gatewayId The gateway data model.
* @return users
* list of usernames of the users in the gateway
*/
@Override
public List<String> getAllUsersInGateway(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<String> result = regClient.getAllUsersInGateway(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving users", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving users. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateGateway(AuthzToken authzToken, String gatewayId, Gateway updatedGateway)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGateway(gatewayId, updatedGateway);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while updating the gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating the gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public Gateway getGateway(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Gateway result = regClient.getGateway(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while getting the gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting the gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteGateway(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteGateway(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while deleting the gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting the gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<Gateway> getAllGateways(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException,
AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<Gateway> result = regClient.getAllGateways();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while getting all the gateways", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting all the gateways. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean isGatewayExist(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.isGatewayExist(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while getting gateway", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* * API methods to retrieve notifications
* *
*
* @param authzToken
* @param notification
*/
@Override
@SecurityCheck
public String createNotification(AuthzToken authzToken, Notification notification) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.createNotification(notification);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while creating notification", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while creating notification. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateNotification(AuthzToken authzToken, Notification notification) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateNotification(notification);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while updating notification", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting gateway. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteNotification(AuthzToken authzToken, String gatewayId, String notificationId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteNotification(gatewayId, notificationId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while deleting notification", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting notification. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
// No security check
@Override
public Notification getNotification(AuthzToken authzToken, String gatewayId, String notificationId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Notification result = regClient.getNotification(gatewayId, notificationId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving notification", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retreiving notification. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
// No security check
@Override
public List<Notification> getAllNotifications(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<Notification> result = regClient.getAllNotifications(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while getting all notifications", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting all notifications. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String generateAndRegisterSSHKeys(AuthzToken authzToken, String gatewayId, String userName, String description, CredentialOwnerType credentialOwnerType) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
SSHCredential sshCredential = new SSHCredential();
sshCredential.setUsername(userName);
sshCredential.setGatewayId(gatewayId);
sshCredential.setDescription(description);
if (credentialOwnerType != null) {
sshCredential.setCredentialOwnerType(credentialOwnerType);
}
String key = csClient.addSSHCredential(sshCredential);
logger.debug("Airavata generated SSH keys for gateway : " + gatewayId + " and for user : " + userName);
csClientPool.returnResource(csClient);
return key;
}catch (Exception e){
logger.error("Error occurred while registering SSH Credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while registering SSH Credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
/**
* Generate and Register Username PWD Pair with Airavata Credential Store.
*
* @param authzToken
* @param gatewayId The identifier for the requested Gateway.
* @param portalUserName The User for which the credential should be registered. For community accounts, this user is the name of the
* community user name. For computational resources, this user name need not be the same user name on resoruces.
* @param password
* @return airavataCredStoreToken
* An SSH Key pair is generated and stored in the credential store and associated with users or community account
* belonging to a Gateway.
*/
@Override
@SecurityCheck
public String registerPwdCredential(AuthzToken authzToken, String gatewayId, String portalUserName,
String loginUserName, String password, String description) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
PasswordCredential pwdCredential = new PasswordCredential();
pwdCredential.setPortalUserName(portalUserName);
pwdCredential.setLoginUserName(loginUserName);
pwdCredential.setPassword(password);
pwdCredential.setDescription(description);
pwdCredential.setGatewayId(gatewayId);
String key = csClient.addPasswordCredential(pwdCredential);
logger.debug("Airavata generated PWD credential for gateway : " + gatewayId + " and for user : " + loginUserName);
csClientPool.returnResource(csClient);
return key;
}catch (Exception e){
logger.error("Error occurred while registering PWD Credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while registering PWD Credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public String getSSHPubKey(AuthzToken authzToken, String airavataCredStoreToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
SSHCredential sshCredential = csClient.getSSHCredential(airavataCredStoreToken, gatewayId);
logger.debug("Airavata retrieved SSH pub key for gateway id : " + gatewayId + " and for token : " + airavataCredStoreToken);
csClientPool.returnResource(csClient);
return sshCredential.getPublicKey();
}catch (Exception e){
logger.error("Error occurred while retrieving SSH credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public Map<String, String> getAllGatewaySSHPubKeys(AuthzToken authzToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
Map<String, String> allSSHKeysForGateway = csClient.getAllSSHKeysForGateway(gatewayId);
logger.debug("Airavata retrieved all SSH pub keys for gateway Id : " + gatewayId);
csClientPool.returnResource(csClient);
return allSSHKeysForGateway;
}catch (Exception e){
logger.error("Error occurred while retrieving SSH public keys for gateway : " + gatewayId , e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH public keys for gateway : " + gatewayId + ". More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<CredentialSummary> getAllCredentialSummaryForGateway(AuthzToken authzToken, SummaryType type, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
if(type.equals(SummaryType.SSH)){
logger.debug("Airavata will retrieve all SSH pub keys summaries for gateway Id : " + gatewayId);
List<CredentialSummary> result = csClient.getAllCredentialSummaryForGateway(type, gatewayId);
csClientPool.returnResource(csClient);
return result;
} else {
logger.info("Summay Type"+ type.toString() + " not supported by Airavata");
AiravataSystemException ex = new AiravataSystemException();
ex.setAiravataErrorType(AiravataErrorType.UNSUPPORTED_OPERATION);
ex.setMessage("Summay Type"+ type.toString() + " not supported by Airavata");
csClientPool.returnResource(csClient);
throw ex;
}
}catch (Exception e){
logger.error("Error occurred while retrieving SSH public keys summaries for gateway : " + gatewayId , e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH public keys summaries for gateway : " + gatewayId + ". More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<CredentialSummary> getAllCredentialSummaryForUsersInGateway(AuthzToken authzToken,SummaryType type, String gatewayId, String userId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
if(type.equals(SummaryType.SSH)){
logger.debug("Airavata will retrieve all SSH pub keys summaries for gateway Id : " + gatewayId);
List<CredentialSummary> result = csClient.getAllCredentialSummaryForUserInGateway(type, gatewayId, userId);
csClientPool.returnResource(csClient);
return result;
} else {
logger.info("Summay Type"+ type.toString() + " not supported by Airavata");
AiravataSystemException ex = new AiravataSystemException();
ex.setAiravataErrorType(AiravataErrorType.UNSUPPORTED_OPERATION);
ex.setMessage("Summay Type"+ type.toString() + " not supported by Airavata");
csClientPool.returnResource(csClient);
throw ex;
}
}catch (Exception e){
logger.error("Error occurred while retrieving SSH public keys summaries for user : " + userId , e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH public keys summaries for user : " + userId + ". More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public Map<String, String> getAllGatewayPWDCredentials(AuthzToken authzToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
Map<String, String> allPwdCredentials = csClient.getAllPWDCredentialsForGateway(gatewayId);
logger.debug("Airavata retrieved all PWD Credentials for gateway Id : " + gatewayId);
csClientPool.returnResource(csClient);
return allPwdCredentials;
}catch (Exception e){
logger.error("Error occurred while retrieving PWD Credentials for gateway : " + gatewayId , e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving PWD Credentials for gateway : " + gatewayId + ". More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteSSHPubKey(AuthzToken authzToken, String airavataCredStoreToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
logger.debug("Airavata deleted SSH pub key for gateway Id : " + gatewayId + " and with token id : " + airavataCredStoreToken);
boolean result = csClient.deleteSSHCredential(airavataCredStoreToken, gatewayId);
csClientPool.returnResource(csClient);
return result;
}catch (Exception e){
logger.error("Error occurred while deleting SSH credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while deleting SSH credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deletePWDCredential(AuthzToken authzToken, String airavataCredStoreToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException {
CredentialStoreService.Client csClient = csClientPool.getResource();
try {
logger.debug("Airavata deleted PWD credential for gateway Id : " + gatewayId + " and with token id : " + airavataCredStoreToken);
boolean result = csClient.deletePWDCredential(airavataCredStoreToken, gatewayId);
csClientPool.returnResource(csClient);
return result;
}catch (Exception e){
logger.error("Error occurred while deleting PWD credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while deleting PWD credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
}
/**
* Create a Project
*
* @param project
*/
@Override
@SecurityCheck
public String createProject(AuthzToken authzToken, String gatewayId, Project project) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: verify that gatewayId and project.gatewayId match authzToken
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
String projectId = regClient.createProject(gatewayId, project);
if(ServerSettings.isEnableSharing()){
try {
Entity entity = new Entity();
entity.setEntityId(projectId);
final String domainId = project.getGatewayId();
entity.setDomainId(domainId);
entity.setEntityTypeId(domainId + ":" + "PROJECT");
entity.setOwnerId(project.getOwner() + "@" + domainId);
entity.setName(project.getName());
entity.setDescription(project.getDescription());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
logger.error("Rolling back project creation Proj ID : " + projectId);
regClient.deleteProject(projectId);
AiravataSystemException ase = new AiravataSystemException();
ase.setMessage("Failed to create entry for project in Sharing Registry");
throw ase;
}
}
logger.debug("Airavata created project with project Id : " + projectId + " for gateway Id : " + gatewayId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return projectId;
} catch (Exception e) {
logger.error("Error while creating the project", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while creating the project. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateProject(AuthzToken authzToken, String projectId, Project updatedProject) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, ProjectNotFoundException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
Project existingProject = regClient.getProject(projectId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(existingProject.getOwner())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(existingProject.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
projectId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
if(!updatedProject.getOwner().equals(existingProject.getOwner())){
throw new InvalidRequestException("Owner of a project cannot be changed");
}
if(!updatedProject.getGatewayId().equals(existingProject.getGatewayId())){
throw new InvalidRequestException("Gateway ID of a project cannot be changed");
}
regClient.updateProject(projectId, updatedProject);
logger.debug("Airavata updated project with project Id : " + projectId );
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
} catch (Exception e) {
logger.error("Error while updating the project", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating the project. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteProject(AuthzToken authzToken, String projectId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, ProjectNotFoundException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
Project existingProject = regClient.getProject(projectId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(existingProject.getOwner())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(existingProject.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
projectId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
boolean ret = regClient.deleteProject(projectId);
logger.debug("Airavata deleted project with project Id : " + projectId );
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return ret;
} catch (Exception e) {
logger.error("Error while removing the project", e);
ProjectNotFoundException exception = new ProjectNotFoundException();
exception.setMessage("Error while removing the project. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
private boolean validateString(String name){
boolean valid = true;
if (name == null || name.equals("") || name.trim().length() == 0){
valid = false;
}
return valid;
}
/**
* Get a Project by ID
*
* @param projectId
*/
@Override
@SecurityCheck
public Project getProject(AuthzToken authzToken, String projectId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, ProjectNotFoundException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
Project project = regClient.getProject(projectId);
if(authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(project.getOwner())
&& authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(project.getGatewayId())){
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return project;
}else if (ServerSettings.isEnableSharing()){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
projectId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access this resource");
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return project;
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
} else {
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return null;
}
} catch (Exception e) {
logger.error("Error while retrieving the project", e);
ProjectNotFoundException exception = new ProjectNotFoundException();
exception.setMessage("Error while retrieving the project. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Get all Project by user with pagination. Results will be ordered based
* on creation time DESC
*
* @param gatewayId
* The identifier for the requested gateway.
* @param userName
* The identifier of the user
* @param limit
* The amount results to be fetched
* @param offset
* The starting point of the results to be fetched
**/
@Override
@SecurityCheck
public List<Project> getUserProjects(AuthzToken authzToken, String gatewayId, String userName,
int limit, int offset)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if (ServerSettings.isEnableSharing()){
// user projects + user accessible projects
List<String> accessibleProjectIds = new ArrayList<>();
List<SearchCriteria> filters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(gatewayId + ":PROJECT");
filters.add(searchCriteria);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, filters, 0, -1).stream().forEach(p -> accessibleProjectIds
.add(p.entityId));
List<Project> result = regClient.searchProjects(gatewayId, userName, accessibleProjectIds, new HashMap<>(), limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}else{
List<Project> result = regClient.getUserProjects(gatewayId, userName, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}
} catch (Exception e) {
logger.error("Error while retrieving projects", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving projects. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
*
* Search User Projects
* Search and get all Projects for user by project description or/and project name with pagination.
* Results will be ordered based on creation time DESC.
*
* @param gatewayId
* The unique identifier of the gateway making the request.
*
* @param userName
* The identifier of the user.
*
* @param filters
* Map of multiple filter criteria. Currenlt search filters includes Project Name and Project Description
*
* @param limit
* The amount results to be fetched.
*
* @param offset
* The starting point of the results to be fetched.
*
*/
@Override
public List<Project> searchProjects(AuthzToken authzToken, String gatewayId, String userName, Map<ProjectSearchFields,
String> filters, int limit, int offset) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<String> accessibleProjIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> sharingFilters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(gatewayId + ":PROJECT");
sharingFilters.add(searchCriteria);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, sharingFilters, 0, -1).stream().forEach(e -> accessibleProjIds.add(e.entityId));
}
List<Project> result = regClient.searchProjects(gatewayId, userName, accessibleProjIds, filters, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}catch (Exception e) {
logger.error("Error while retrieving projects", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving projects. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Search Experiments by using multiple filter criteria with pagination. Results will be sorted
* based on creation time DESC
*
* @param gatewayId
* Identifier of the requested gateway
* @param userName
* Username of the requested user
* @param filters
* map of multiple filter criteria.
* @param limit
* Amount of results to be fetched
* @param offset
* The starting point of the results to be fetched
*/
@Override
@SecurityCheck
public List<ExperimentSummaryModel> searchExperiments(AuthzToken authzToken, String gatewayId, String userName, Map<ExperimentSearchFields,
String> filters, int limit, int offset)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<String> accessibleExpIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> sharingFilters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(gatewayId + ":EXPERIMENT");
sharingFilters.add(searchCriteria);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, sharingFilters, 0, -1).forEach(e -> accessibleExpIds.add(e.entityId));
}
List<ExperimentSummaryModel> result = regClient.searchExperiments(gatewayId, userName, accessibleExpIds, filters, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}catch (Exception e) {
logger.error("Error while retrieving experiments", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving experiments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Get Experiment execution statisitics by sending the gateway id and the time period interested in.
* This method will retrun an ExperimentStatistics object which contains the number of successfully
* completed experiments, failed experiments etc.
* @param gatewayId
* @param fromTime
* @param toTime
* @return
* @throws InvalidRequestException
* @throws AiravataClientException
* @throws AiravataSystemException
* @throws TException
*/
@Override
@SecurityCheck
public ExperimentStatistics getExperimentStatistics(AuthzToken authzToken, String gatewayId, long fromTime, long toTime,
String userName, String applicationName, String resourceHostName)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentStatistics result = regClient.getExperimentStatistics(gatewayId, fromTime, toTime, userName, applicationName, resourceHostName);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
}catch (Exception e) {
logger.error("Error while retrieving experiments", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving experiments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Get Experiments within project with pagination. Results will be sorted
* based on creation time DESC
*
* @param projectId
* Identifier of the project
* @param limit
* Amount of results to be fetched
* @param offset
* The starting point of the results to be fetched
*/
@Override
@SecurityCheck
public List<ExperimentModel> getExperimentsInProject(AuthzToken authzToken, String projectId, int limit, int offset)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, ProjectNotFoundException,
AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
Project project = regClient.getProject(projectId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(project.getOwner())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(project.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
projectId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
List<ExperimentModel> result = regClient.getExperimentsInProject(projectId, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving the experiments", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the experiments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Get Experiments by user pagination. Results will be sorted
* based on creation time DESC
*
* @param gatewayId
* Identifier of the requesting gateway
* @param userName
* Username of the requested user
* @param limit
* Amount of results to be fetched
* @param offset
* The starting point of the results to be fetched
*/
@Override
@SecurityCheck
public List<ExperimentModel> getUserExperiments(AuthzToken authzToken, String gatewayId, String userName, int limit,
int offset) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<ExperimentModel> result = regClient.getUserExperiments(gatewayId, userName, limit, offset);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving the experiments", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the experiments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Create an experiment for the specified user belonging to the gateway. The gateway identity is not explicitly passed
* but inferred from the authentication header. This experiment is just a persistent place holder. The client
* has to subsequently configure and launch the created experiment. No action is taken on Airavata Server except
* registering the experiment in a persistent store.
*
* @param experiment@return The server-side generated.airavata.registry.core.experiment.globally unique identifier.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public String createExperiment(AuthzToken authzToken, String gatewayId, ExperimentModel experiment) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: verify that gatewayId and experiment.gatewayId match authzToken
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
String experimentId = regClient.createExperiment(gatewayId, experiment);
if(ServerSettings.isEnableSharing()) {
try {
Entity entity = new Entity();
entity.setEntityId(experimentId);
final String domainId = experiment.getGatewayId();
entity.setDomainId(domainId);
entity.setEntityTypeId(domainId + ":" + "EXPERIMENT");
entity.setOwnerId(experiment.getUserName() + "@" + domainId);
entity.setName(experiment.getExperimentName());
entity.setDescription(experiment.getDescription());
entity.setParentEntityId(experiment.getProjectId());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
logger.error("Rolling back experiment creation Exp ID : " + experimentId);
regClient.deleteExperiment(experimentId);
AiravataSystemException ase = new AiravataSystemException();
ase.setMessage("Failed to create sharing registry record");
throw ase;
}
}
ExperimentStatusChangeEvent event = new ExperimentStatusChangeEvent(ExperimentState.CREATED,
experimentId,
gatewayId);
String messageId = AiravataUtils.getId("EXPERIMENT");
MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
if(statusPublisher !=null) {
statusPublisher.publish(messageContext);
}
logger.debug(experimentId, "Created new experiment with experiment name {}", experiment.getExperimentName());
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return experimentId;
} catch (Exception e) {
logger.error("Error while creating the experiment with experiment name {}", experiment.getExperimentName());
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while creating the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* If the experiment is not already launched experiment can be deleted.
* @param authzToken
* @param experimentId
* @return
* @throws InvalidRequestException
* @throws AiravataClientException
* @throws AiravataSystemException
* @throws AuthorizationException
* @throws TException
*/
@Override
@SecurityCheck
public boolean deleteExperiment(AuthzToken authzToken, String experimentId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentModel experimentModel = regClient.getExperiment(experimentId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(experimentModel.getUserName())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(experimentModel.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
experimentId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
if(!(experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED)){
logger.error("Error while deleting the experiment");
throw new RegistryServiceException("Experiment is not in CREATED state. Hence cannot deleted. ID:"+ experimentId);
}
boolean result = regClient.deleteExperiment(experimentId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while deleting the experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Fetch previously created experiment metadata.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return experimentMetada
* This method will return the previously stored experiment metadata.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public ExperimentModel getExperiment(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException,
ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
ExperimentModel experimentModel = null;
try {
experimentModel = regClient.getExperiment(airavataExperimentId);
if(authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(experimentModel.getUserName())
&& authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(experimentModel.getGatewayId())){
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return experimentModel;
}else if(ServerSettings.isEnableSharing()){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
airavataExperimentId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access this resource");
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return experimentModel;
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}else{
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return null;
}
} catch (Exception e) {
logger.error("Error while getting the experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public ExperimentModel getExperimentByAdmin(AuthzToken authzToken, String airavataExperimentId)
throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
ExperimentModel experimentModel = null;
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
experimentModel = regClient.getExperiment(airavataExperimentId);
registryClientPool.returnResource(regClient);
if(gatewayId.equals(experimentModel.getGatewayId())){
return experimentModel;
} else {
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
logger.error("Error while getting the experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while getting the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the completed nested tree structue of previously created experiment metadata which includes processes ->
* tasks -> jobs information.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return experimentMetada
* This method will return the previously stored experiment metadata.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public ExperimentModel getDetailedExperimentTree(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException,
ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentModel result = regClient.getDetailedExperimentTree(airavataExperimentId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving the experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Configure a previously created experiment with required inputs, scheduling and other quality of service
* parameters. This method only updates the experiment object within the registry. The experiment has to be launched
* to make it actionable by the server.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @param experiment
* @return This method call does not have a return value.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public void updateExperiment(AuthzToken authzToken, String airavataExperimentId, ExperimentModel experiment)
throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, AiravataSystemException,
AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentModel experimentModel = regClient.getExperiment(airavataExperimentId);
if(ServerSettings.isEnableSharing() && !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.USER_NAME).equals(experimentModel.getUserName())
|| !authzToken.getClaimsMap().get(org.apache.airavata.common.utils.Constants.GATEWAY_ID).equals(experimentModel.getGatewayId())){
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
airavataExperimentId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to access this resource");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access this resource");
}
}
regClient.updateExperiment(airavataExperimentId, experiment);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while updating experiment", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateExperimentConfiguration(AuthzToken authzToken, String airavataExperimentId, UserConfigurationDataModel userConfiguration)
throws AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
regClient.send_updateExperimentConfiguration(airavataExperimentId, userConfiguration);
registryClientPool.returnResource(regClient);
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while updating user configuration", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user configuration. " +
"Update experiment is only valid for experiments " +
"with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " +
"experiment is in one of above statuses... " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateResourceScheduleing(AuthzToken authzToken, String airavataExperimentId,
ComputationalResourceSchedulingModel resourceScheduling) throws AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
regClient.updateResourceScheduleing(airavataExperimentId, resourceScheduling);
registryClientPool.returnResource(regClient);
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while updating scheduling info", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating scheduling info. " +
"Update experiment is only valid for experiments " +
"with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " +
"experiment is in one of above statuses... " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* *
* * Validate experiment configuration. A true in general indicates, the experiment is ready to be launched.
* *
* * @param experimentID
* * @return sucess/failure
* *
* *
*
* @param airavataExperimentId
*/
@Override
@SecurityCheck
public boolean validateExperiment(AuthzToken authzToken, String airavataExperimentId) throws TException {
// TODO - call validation module and validate experiment
/* try {
ExperimentModel experimentModel = regClient.getExperiment(airavataExperimentId);
if (experimentModel == null) {
logger.error(airavataExperimentId, "Experiment validation failed , experiment {} doesn't exist.", airavataExperimentId);
throw new ExperimentNotFoundException("Requested experiment id " + airavataExperimentId + " does not exist in the system..");
}
} catch (RegistryServiceException | ApplicationSettingsException e1) {
logger.error(airavataExperimentId, "Error while retrieving projects", e1);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving projects. More info : " + e1.getMessage());
throw exception;
}
Client orchestratorClient = getOrchestratorClient();
try{
if (orchestratorClient.validateExperiment(airavataExperimentId)) {
logger.debug(airavataExperimentId, "Experiment validation succeed.");
return true;
} else {
logger.debug(airavataExperimentId, "Experiment validation failed.");
return false;
}}catch (TException e){
throw e;
}finally {
orchestratorClient.getOutputProtocol().getTransport().close();
orchestratorClient.getInputProtocol().getTransport().close();
}*/
return true;
}
/**
* Fetch the previously configured experiment configuration information.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return This method returns the previously configured experiment configuration data.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
*<p/>
*UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
*step, then Airavata Registry will not have a provenance area setup. The client has to follow
*gateway registration steps and retry this request.
*<p/>
*AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
*For now this is a place holder.
*<p/>
*INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
*is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any
* Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public ExperimentStatus getExperimentStatus(AuthzToken authzToken, String airavataExperimentId) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ExperimentStatus result = regClient.getExperimentStatus(airavataExperimentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
AiravataSystemException exception = new AiravataSystemException();
exception.setMessage(e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<OutputDataObjectType> getExperimentOutputs(AuthzToken authzToken, String airavataExperimentId)
throws AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<OutputDataObjectType> result = regClient.getExperimentOutputs(airavataExperimentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while retrieving the experiment outputs", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the experiment outputs. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<OutputDataObjectType> getIntermediateOutputs(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException,
ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return null;
}
@SecurityCheck
public Map<String, JobStatus> getJobStatuses(AuthzToken authzToken, String airavataExperimentId)
throws AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, JobStatus> result = regClient.getJobStatuses(airavataExperimentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while retrieving the job statuses", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the job statuses. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<JobModel> getJobDetails(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException,
ExperimentNotFoundException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<JobModel> result = regClient.getJobDetails(airavataExperimentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(airavataExperimentId, "Error while retrieving the job details", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the job details. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Launch a previously created and configured experiment. Airavata Server will then start processing the request and appropriate
* notifications and intermediate and output data will be subsequently available for this experiment.
*
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return This method call does not have a return value.
* @throws org.apache.airavata.model.error.InvalidRequestException
* For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException
* If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException
* The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException
* This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public void launchExperiment(AuthzToken authzToken, final String airavataExperimentId, String gatewayId)
throws AuthorizationException, AiravataSystemException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
ExperimentModel experiment = regClient.getExperiment(airavataExperimentId);
// TODO: fix checking if the user has access to the deployment of this application, should check for entity type APPLICATION_DEPLOYMENT and permission type EXEC
// String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
// String appInterfaceId = experiment.getExecutionId();
// ApplicationInterfaceDescription applicationInterfaceDescription = regClient.getApplicationInterface(appInterfaceId);
// List<String> entityIds = applicationInterfaceDescription.getApplicationModules();
// if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId, entityIds.get(0),gatewayId + ":READ")) {
// logger.error(airavataExperimentId, "User does not have access to application module {}.", entityIds.get(0));
// throw new AuthorizationException("User does not have permission to access this resource");
// }
if (experiment == null) {
logger.error(airavataExperimentId, "Error while launching experiment, experiment {} doesn't exist.", airavataExperimentId);
throw new ExperimentNotFoundException("Requested experiment id " + airavataExperimentId + " does not exist in the system..");
}
submitExperiment(gatewayId, airavataExperimentId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
} catch (Exception e1) {
logger.error(airavataExperimentId, "Error while instantiate the registry instance", e1);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while instantiate the registry instance. More info : " + e1.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
// private OrchestratorService.Client getOrchestratorClient() throws TException {
// try {
// final String serverHost = ServerSettings.getOrchestratorServerHost();
// final int serverPort = ServerSettings.getOrchestratorServerPort();
// return OrchestratorClientFactory.createOrchestratorClient(serverHost, serverPort);
// } catch (AiravataException e) {
// throw new TException(e);
// }
// }
/**
* Clone an specified experiment with a new name. A copy of the experiment configuration is made and is persisted with new metadata.
* The client has to subsequently update this configuration if needed and launch the cloned experiment.
*
* @param existingExperimentID
* This is the experiment identifier that already exists in the system. Will use this experimentID to retrieve
* user configuration which is used with the clone experiment.
*
* @param newExperimentName
* experiment name that should be used in the cloned experiment
*
* @return
* The server-side generated.airavata.registry.core.experiment.globally unique identifier for the newly cloned experiment.
*
* @throws org.apache.airavata.model.error.InvalidRequestException
* For any incorrect forming of the request itself.
*
* @throws org.apache.airavata.model.error.ExperimentNotFoundException
* If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
*
* @throws org.apache.airavata.model.error.AiravataClientException
* The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
*
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
*
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
*
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
*
* @throws org.apache.airavata.model.error.AiravataSystemException
* This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*
*
* @param existingExperimentID
* @param newExperimentName
*/
@Override
@SecurityCheck
public String cloneExperiment(AuthzToken authzToken, String existingExperimentID, String newExperimentName, String newExperimentProjectId)
throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, AiravataSystemException,
AuthorizationException, ProjectNotFoundException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
// getExperiment will apply sharing permissions
ExperimentModel existingExperiment = this.getExperiment(authzToken, existingExperimentID);
String result = cloneExperimentInternal(regClient, sharingClient, authzToken, existingExperimentID, newExperimentName, newExperimentProjectId, existingExperiment);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error(existingExperimentID, "Error while cloning the experiment with existing configuration...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while cloning the experiment with existing configuration. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public String cloneExperimentByAdmin(AuthzToken authzToken, String existingExperimentID, String newExperimentName, String newExperimentProjectId)
throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, AiravataSystemException,
AuthorizationException, ProjectNotFoundException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
// get existing experiment by bypassing normal sharing permissions for the admin user
ExperimentModel existingExperiment = this.getExperimentByAdmin(authzToken, existingExperimentID);
String result = cloneExperimentInternal(regClient, sharingClient, authzToken, existingExperimentID, newExperimentName, newExperimentProjectId, existingExperiment);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error(existingExperimentID, "Error while cloning the experiment with existing configuration...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while cloning the experiment with existing configuration. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
private String cloneExperimentInternal(RegistryService.Client regClient, SharingRegistryService.Client sharingClient,
AuthzToken authzToken, String existingExperimentID, String newExperimentName, String newExperimentProjectId, ExperimentModel existingExperiment)
throws ExperimentNotFoundException, ProjectNotFoundException, TException, AuthorizationException, ApplicationSettingsException {
if (existingExperiment == null){
logger.error(existingExperimentID, "Error while cloning experiment {}, experiment doesn't exist.", existingExperimentID);
throw new ExperimentNotFoundException("Requested experiment id " + existingExperimentID + " does not exist in the system..");
}
if (newExperimentProjectId != null) {
// getProject will apply sharing permissions
Project project = this.getProject(authzToken, newExperimentProjectId);
if (project == null){
logger.error("Error while cloning experiment {}, project {} doesn't exist.", existingExperimentID, newExperimentProjectId);
throw new ProjectNotFoundException("Requested project id " + newExperimentProjectId + " does not exist in the system..");
}
existingExperiment.setProjectId(project.getProjectID());
}
// make sure user has write access to the project
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
existingExperiment.getProjectId(), gatewayId + ":WRITE")){
logger.error("Error while cloning experiment {}, user doesn't have write access to project {}", existingExperimentID, existingExperiment.getProjectId());
throw new AuthorizationException("User does not have permission to clone an experiment in this project");
}
existingExperiment.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime());
if (existingExperiment.getExecutionId() != null){
List<OutputDataObjectType> applicationOutputs = regClient.getApplicationOutputs(existingExperiment.getExecutionId());
existingExperiment.setExperimentOutputs(applicationOutputs);
}
if (validateString(newExperimentName)){
existingExperiment.setExperimentName(newExperimentName);
}
if (existingExperiment.getErrors() != null ){
existingExperiment.getErrors().clear();
}
if(existingExperiment.getUserConfigurationData() != null && existingExperiment.getUserConfigurationData()
.getComputationalResourceScheduling() != null){
String compResourceId = existingExperiment.getUserConfigurationData()
.getComputationalResourceScheduling().getResourceHostId();
ComputeResourceDescription computeResourceDescription = regClient.getComputeResource(compResourceId);
if(!computeResourceDescription.isEnabled()){
existingExperiment.getUserConfigurationData().setComputationalResourceScheduling(null);
}
}
logger.debug("Airavata cloned experiment with experiment id : " + existingExperimentID);
existingExperiment.setUserName(userId);
String expId = regClient.createExperiment(gatewayId, existingExperiment);
if(ServerSettings.isEnableSharing()){
try {
Entity entity = new Entity();
entity.setEntityId(expId);
final String domainId = existingExperiment.getGatewayId();
entity.setDomainId(domainId);
entity.setEntityTypeId(domainId + ":" + "EXPERIMENT");
entity.setOwnerId(existingExperiment.getUserName() + "@" + domainId);
entity.setName(existingExperiment.getExperimentName());
entity.setDescription(existingExperiment.getDescription());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
logger.error("rolling back experiment creation Exp ID : " + expId);
regClient.deleteExperiment(expId);
}
}
return expId;
}
/**
* Terminate a running experiment.
*
* @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step.
* @return This method call does not have a return value.
* @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself.
* @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown.
* @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve:
* <p/>
* UNKNOWN_GATEWAY_ID - If a Gateway is not registered with Airavata as a one time administrative
* step, then Airavata Registry will not have a provenance area setup. The client has to follow
* gateway registration steps and retry this request.
* <p/>
* AUTHENTICATION_FAILURE - How Authentication will be implemented is yet to be determined.
* For now this is a place holder.
* <p/>
* INVALID_AUTHORIZATION - This will throw an authorization exception. When a more robust security hand-shake
* is implemented, the authorization will be more substantial.
* @throws org.apache.airavata.model.error.AiravataSystemException This exception will be thrown for any Airavata Server side issues and if the problem cannot be corrected by the client
* rather an Airavata Administrator will be notified to take corrective action.
*/
@Override
@SecurityCheck
public void terminateExperiment(AuthzToken authzToken, String airavataExperimentId, String gatewayId)
throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ExperimentModel existingExperiment = regClient.getExperiment(airavataExperimentId);
if (existingExperiment == null){
logger.error(airavataExperimentId, "Error while cancelling experiment {}, experiment doesn't exist.", airavataExperimentId);
throw new ExperimentNotFoundException("Requested experiment id " + airavataExperimentId + " does not exist in the system..");
}
switch (existingExperiment.getExperimentStatus().get(0).getState()) {
case COMPLETED: case CANCELED: case FAILED: case CANCELING:
logger.warn("Can't terminate already {} experiment", existingExperiment.getExperimentStatus().get(0).getState().name());
break;
case CREATED:
logger.warn("Experiment termination is only allowed for launched experiments.");
break;
default:
submitCancelExperiment(gatewayId, airavataExperimentId);
logger.debug("Airavata cancelled experiment with experiment id : " + airavataExperimentId);
break;
}
registryClientPool.returnResource(regClient);
} catch (RegistryServiceException | AiravataException e) {
logger.error(airavataExperimentId, "Error while cancelling the experiment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while cancelling the experiment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Application Module.
*
* @param applicationModule Application Module Object created from the datamodel.
* @return appModuleId
* Returns a server-side generated airavata appModule globally unique identifier.
*/
@Override
@SecurityCheck
public String registerApplicationModule(AuthzToken authzToken, String gatewayId, ApplicationModule applicationModule)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerApplicationModule(gatewayId, applicationModule);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while adding application module...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding application module. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a Application Module.
*
* @param appModuleId The identifier for the requested application module
* @return applicationModule
* Returns a application Module Object.
*/
@Override
@SecurityCheck
public ApplicationModule getApplicationModule(AuthzToken authzToken, String appModuleId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ApplicationModule result = regClient.getApplicationModule(appModuleId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appModuleId, "Error while retrieving application module...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving the adding application module. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Application Module.
*
* @param appModuleId The identifier for the requested application module to be updated.
* @param applicationModule Application Module Object created from the datamodel.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateApplicationModule(AuthzToken authzToken, String appModuleId, ApplicationModule applicationModule)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateApplicationModule(appModuleId, applicationModule);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appModuleId, "Error while updating application module...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating application module. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all Application Module Descriptions.
*
* @return list applicationModule.
* Returns the list of all Application Module Objects.
*/
@Override
@SecurityCheck
public List<ApplicationModule> getAllAppModules(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<ApplicationModule> result = regClient.getAllAppModules(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving all application modules...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving all application modules. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all accessible Application Module Descriptions.
*
* @return list applicationModule.
* Returns the list of Application Module Objects that are accessible to the user.
*/
@Override
@SecurityCheck
public List<ApplicationModule> getAccessibleAppModules(AuthzToken authzToken, String gatewayId, ResourcePermissionType permissionType) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<String> accessibleAppDeploymentIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> sharingFilters = new ArrayList<>();
SearchCriteria entityTypeFilter = new SearchCriteria();
entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
entityTypeFilter.setSearchCondition(SearchCondition.EQUAL);
entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name());
sharingFilters.add(entityTypeFilter);
SearchCriteria permissionTypeFilter = new SearchCriteria();
permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL);
permissionTypeFilter.setValue(gatewayId + ":" + permissionType.name());
sharingFilters.add(permissionTypeFilter);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, sharingFilters, 0, -1).forEach(a -> accessibleAppDeploymentIds.add(a.entityId));
}
List<String> accessibleComputeResourceIds = new ArrayList<>();
List<GroupResourceProfile> groupResourceProfileList = getGroupResourceList(authzToken, gatewayId);
for(GroupResourceProfile groupResourceProfile : groupResourceProfileList) {
List<GroupComputeResourcePreference> groupComputeResourcePreferenceList = groupResourceProfile.getComputePreferences();
for(GroupComputeResourcePreference groupComputeResourcePreference : groupComputeResourcePreferenceList) {
accessibleComputeResourceIds.add(groupComputeResourcePreference.getComputeResourceId());
}
}
List<ApplicationModule> result = regClient.getAccessibleAppModules(gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving all application modules...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving all application modules. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Delete a Application Module.
*
* @param appModuleId The identifier for the requested application module to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteApplicationModule(AuthzToken authzToken, String appModuleId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteApplicationModule(appModuleId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appModuleId, "Error while deleting application module...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting the application module. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Application Deployment.
*
* @param applicationDeployment@return appModuleId
* Returns a server-side generated airavata appModule globally unique identifier.
*/
@Override
@SecurityCheck
public String registerApplicationDeployment(AuthzToken authzToken, String gatewayId, ApplicationDeploymentDescription applicationDeployment)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: verify that gatewayId matches authzToken gatewayId
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
String result = regClient.registerApplicationDeployment(gatewayId, applicationDeployment);
Entity entity = new Entity();
entity.setEntityId(result);
final String domainId = gatewayId;
entity.setDomainId(domainId);
entity.setEntityTypeId(domainId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name());
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
entity.setOwnerId(userName + "@" + domainId);
entity.setName(result);
entity.setDescription(applicationDeployment.getAppDeploymentDescription());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while adding application deployment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Fetch a Application Deployment.
*
* @param appDeploymentId The identifier for the requested application module
* @return applicationDeployment
* Returns a application Deployment Object.
*/
@Override
@SecurityCheck
public ApplicationDeploymentDescription getApplicationDeployment(AuthzToken authzToken, String appDeploymentId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ApplicationDeploymentDescription result = regClient.getApplicationDeployment(appDeploymentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appDeploymentId, "Error while retrieving application deployment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Application Deployment.
*
* @param appDeploymentId The identifier for the requested application deployment to be updated.
* @param applicationDeployment
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateApplicationDeployment(AuthzToken authzToken, String appDeploymentId,
ApplicationDeploymentDescription applicationDeployment)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateApplicationDeployment(appDeploymentId, applicationDeployment);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appDeploymentId, "Error while updating application deployment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a Application deployment.
*
* @param appDeploymentId The identifier for the requested application deployment to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteApplicationDeployment(AuthzToken authzToken, String appDeploymentId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteApplicationDeployment(appDeploymentId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appDeploymentId, "Error while deleting application deployment...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all Application Deployment Descriptions.
*
* @return list applicationDeployment.
* Returns the list of all Application Deployment Objects.
*/
@Override
@SecurityCheck
public List<ApplicationDeploymentDescription> getAllApplicationDeployments(AuthzToken authzToken, String gatewayId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<ApplicationDeploymentDescription> result = regClient.getAllApplicationDeployments(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving application deployments...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all accessible Application Deployment Descriptions.
*
* @return list applicationDeployment.
* Returns the list of Application Deployment Objects that are accessible to the user.
*/
@Override
@SecurityCheck
public List<ApplicationDeploymentDescription> getAccessibleApplicationDeployments(AuthzToken authzToken, String gatewayId, ResourcePermissionType permissionType)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
List<String> accessibleAppDeploymentIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> sharingFilters = new ArrayList<>();
SearchCriteria entityTypeFilter = new SearchCriteria();
entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
entityTypeFilter.setSearchCondition(SearchCondition.EQUAL);
entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name());
sharingFilters.add(entityTypeFilter);
SearchCriteria permissionTypeFilter = new SearchCriteria();
permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL);
permissionTypeFilter.setValue(gatewayId + ":" + permissionType.name());
sharingFilters.add(permissionTypeFilter);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, sharingFilters, 0, -1).forEach(a -> accessibleAppDeploymentIds.add(a.entityId));
}
List<String> accessibleComputeResourceIds = new ArrayList<>();
List<GroupResourceProfile> groupResourceProfileList = getGroupResourceList(authzToken, gatewayId);
for(GroupResourceProfile groupResourceProfile : groupResourceProfileList) {
List<GroupComputeResourcePreference> groupComputeResourcePreferenceList = groupResourceProfile.getComputePreferences();
for(GroupComputeResourcePreference groupComputeResourcePreference : groupComputeResourcePreferenceList) {
accessibleComputeResourceIds.add(groupComputeResourcePreference.getComputeResourceId());
}
}
List<ApplicationDeploymentDescription> result = regClient.getAccessibleApplicationDeployments(gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving application deployments...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
/**
* Fetch a list of Deployed Compute Hosts.
*
* @param appModuleId The identifier for the requested application module
* @return list<string>
* Returns a list of Deployed Resources.
*/
@Override
@SecurityCheck
public List<String> getAppModuleDeployedResources(AuthzToken authzToken, String appModuleId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<String> result = regClient.getAppModuleDeployedResources(appModuleId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appModuleId, "Error while retrieving application deployments...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Application Interface.
*
* @param applicationInterface@return appInterfaceId
* Returns a server-side generated airavata application interface globally unique identifier.
*/
@Override
@SecurityCheck
public String registerApplicationInterface(AuthzToken authzToken, String gatewayId,
ApplicationInterfaceDescription applicationInterface) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerApplicationInterface(gatewayId, applicationInterface);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while adding application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String cloneApplicationInterface(AuthzToken authzToken, String existingAppInterfaceID, String newApplicationName, String gatewayId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ApplicationInterfaceDescription existingInterface = regClient.getApplicationInterface(existingAppInterfaceID);
if (existingInterface == null){
logger.error("Provided application interface does not exist.Please provide a valid application interface id...");
throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
}
existingInterface.setApplicationName(newApplicationName);
existingInterface.setApplicationInterfaceId(airavata_commonsConstants.DEFAULT_ID);
String interfaceId = regClient.registerApplicationInterface(gatewayId, existingInterface);
logger.debug("Airavata cloned application interface : " + existingAppInterfaceID + " for gateway id : " + gatewayId );
registryClientPool.returnResource(regClient);
return interfaceId;
} catch (Exception e) {
logger.error("Error while adding application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a Application Interface.
*
* @param appInterfaceId The identifier for the requested application module
* @return applicationInterface
* Returns a application Interface Object.
*/
@Override
@SecurityCheck
public ApplicationInterfaceDescription getApplicationInterface(AuthzToken authzToken, String appInterfaceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ApplicationInterfaceDescription result = regClient.getApplicationInterface(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while retrieving application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Application Interface.
*
* @param appInterfaceId The identifier for the requested application deployment to be updated.
* @param applicationInterface
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateApplicationInterface(AuthzToken authzToken, String appInterfaceId,
ApplicationInterfaceDescription applicationInterface) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateApplicationInterface(appInterfaceId, applicationInterface);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while updating application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a Application Interface.
*
* @param appInterfaceId The identifier for the requested application interface to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteApplicationInterface(AuthzToken authzToken, String appInterfaceId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteApplicationInterface(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while deleting application interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting application interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch name and id of Application Interface documents.
*
* @return map<applicationId, applicationInterfaceNames>
* Returns a list of application interfaces with corresponsing id's
*/
@Override
@SecurityCheck
public Map<String, String> getAllApplicationInterfaceNames(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, String> result = regClient.getAllApplicationInterfaceNames(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving application interfaces...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application interfaces. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all Application Interface documents.
*
* @return map<applicationId, applicationInterfaceNames>
* Returns a list of application interfaces documents
*/
@Override
@SecurityCheck
public List<ApplicationInterfaceDescription> getAllApplicationInterfaces(AuthzToken authzToken, String gatewayId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<ApplicationInterfaceDescription> result = regClient.getAllApplicationInterfaces(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving application interfaces...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application interfaces. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the list of Application Inputs.
*
* @param appInterfaceId The identifier for the requested application interface
* @return list<applicationInterfaceModel.InputDataObjectType>
* Returns a list of application inputs.
*/
@Override
@SecurityCheck
public List<InputDataObjectType> getApplicationInputs(AuthzToken authzToken, String appInterfaceId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<InputDataObjectType> result = regClient.getApplicationInputs(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while retrieving application inputs...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving application inputs. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the list of Application Outputs.
*
* @param appInterfaceId The identifier for the requested application interface
* @return list<applicationInterfaceModel.OutputDataObjectType>
* Returns a list of application outputs.
*/
@Override
@SecurityCheck
public List<OutputDataObjectType> getApplicationOutputs(AuthzToken authzToken, String appInterfaceId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<OutputDataObjectType> result = regClient.getApplicationOutputs(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
AiravataSystemException exception = new AiravataSystemException();
exception.setMessage(e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a list of all deployed Compute Hosts for a given application interfaces.
*
* @param appInterfaceId The identifier for the requested application interface
* @return map<computeResourceId, computeResourceName>
* A map of registered compute resource id's and their corresponding hostnames.
* Deployments of each modules listed within the interfaces will be listed.
*/
@Override
@SecurityCheck
public Map<String, String> getAvailableAppInterfaceComputeResources(AuthzToken authzToken, String appInterfaceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, String> result = regClient.getAvailableAppInterfaceComputeResources(appInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(appInterfaceId, "Error while saving compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while saving compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Compute Resource.
*
* @param computeResourceDescription Compute Resource Object created from the datamodel.
* @return computeResourceId
* Returns a server-side generated airavata compute resource globally unique identifier.
*/
@Override
@SecurityCheck
public String registerComputeResource(AuthzToken authzToken, ComputeResourceDescription computeResourceDescription)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerComputeResource(computeResourceDescription);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while saving compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while saving compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the given Compute Resource.
*
* @param computeResourceId The identifier for the requested compute resource
* @return computeResourceDescription
* Compute Resource Object created from the datamodel..
*/
@Override
@SecurityCheck
public ComputeResourceDescription getComputeResource(AuthzToken authzToken, String computeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ComputeResourceDescription result = regClient.getComputeResource(computeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while retrieving compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all registered Compute Resources.
*
* @return A map of registered compute resource id's and thier corresponding hostnames.
* Compute Resource Object created from the datamodel..
*/
@Override
@SecurityCheck
public Map<String, String> getAllComputeResourceNames(AuthzToken authzToken) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, String> result = regClient.getAllComputeResourceNames();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Compute Resource.
*
* @param computeResourceId The identifier for the requested compute resource to be updated.
* @param computeResourceDescription Compute Resource Object created from the datamodel.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateComputeResource(AuthzToken authzToken, String computeResourceId, ComputeResourceDescription computeResourceDescription)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateComputeResource(computeResourceId, computeResourceDescription);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while updating compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updaing compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a Compute Resource.
*
* @param computeResourceId The identifier for the requested compute resource to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteComputeResource(AuthzToken authzToken, String computeResourceId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteComputeResource(computeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while deleting compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Storage Resource.
*
* @param authzToken
* @param storageResourceDescription Storge Resource Object created from the datamodel.
* @return storageResourceId
* Returns a server-side generated airavata storage resource globally unique identifier.
*/
@Override
@SecurityCheck
public String registerStorageResource(AuthzToken authzToken, StorageResourceDescription storageResourceDescription)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerStorageResource(storageResourceDescription);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while saving storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while saving storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the given Storage Resource.
*
* @param authzToken
* @param storageResourceId The identifier for the requested storage resource
* @return storageResourceDescription
* Storage Resource Object created from the datamodel..
*/
@Override
@SecurityCheck
public StorageResourceDescription getStorageResource(AuthzToken authzToken, String storageResourceId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
StorageResourceDescription result = regClient.getStorageResource(storageResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(storageResourceId, "Error while retrieving storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all registered Storage Resources.
*
* @param authzToken
* @return A map of registered compute resource id's and thier corresponding hostnames.
* Compute Resource Object created from the datamodel..
*/
@Override
@SecurityCheck
public Map<String, String> getAllStorageResourceNames(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
Map<String, String> result = regClient.getAllStorageResourceNames();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while retrieving storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Compute Resource.
*
* @param authzToken
* @param storageResourceId The identifier for the requested compute resource to be updated.
* @param storageResourceDescription Storage Resource Object created from the datamodel.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateStorageResource(AuthzToken authzToken, String storageResourceId, StorageResourceDescription storageResourceDescription) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateStorageResource(storageResourceId, storageResourceDescription);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(storageResourceId, "Error while updating storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updaing storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a Storage Resource.
*
* @param authzToken
* @param storageResourceId The identifier for the requested compute resource to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteStorageResource(AuthzToken authzToken, String storageResourceId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteStorageResource(storageResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(storageResourceId, "Error while deleting storage resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting storage resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Local Job Submission details to a compute resource
* App catalog will return a jobSubmissionInterfaceId which will be added to the jobSubmissionInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param localSubmission The LOCALSubmission object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addLocalSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder, LOCALSubmission localSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addLocalSubmissionDetails(computeResourceId, priorityOrder, localSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given Local Job Submission details
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param localSubmission The LOCALSubmission object to be updated.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean updateLocalSubmissionDetails(AuthzToken authzToken, String jobSubmissionInterfaceId, LOCALSubmission localSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateLocalSubmissionDetails(jobSubmissionInterfaceId, localSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public LOCALSubmission getLocalJobSubmission(AuthzToken authzToken, String jobSubmissionId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
LOCALSubmission result = regClient.getLocalJobSubmission(jobSubmissionId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving local job submission interface to resource compute resource...";
logger.error(jobSubmissionId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a SSH Job Submission details to a compute resource
* App catalog will return a jobSubmissionInterfaceId which will be added to the jobSubmissionInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param sshJobSubmission The SSHJobSubmission object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addSSHJobSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addSSHJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a SSH_FORK Job Submission details to a compute resource
* App catalog will return a jobSubmissionInterfaceId which will be added to the jobSubmissionInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param sshJobSubmission The SSHJobSubmission object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addSSHForkJobSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addSSHForkJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public SSHJobSubmission getSSHJobSubmission(AuthzToken authzToken, String jobSubmissionId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
SSHJobSubmission result = regClient.getSSHJobSubmission(jobSubmissionId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving SSH job submission interface to resource compute resource...";
logger.error(jobSubmissionId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Cloud Job Submission details to a compute resource
* App catalog will return a jobSubmissionInterfaceId which will be added to the jobSubmissionInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param cloudJobSubmission The SSHJobSubmission object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addCloudJobSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder,
CloudJobSubmission cloudJobSubmission) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addCloudJobSubmissionDetails(computeResourceId, priorityOrder, cloudJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public CloudJobSubmission getCloudJobSubmission(AuthzToken authzToken, String jobSubmissionId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
CloudJobSubmission result = regClient.getCloudJobSubmission(jobSubmissionId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving Cloud job submission interface to resource compute resource...";
logger.error(jobSubmissionId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String addUNICOREJobSubmissionDetails(AuthzToken authzToken, String computeResourceId, int priorityOrder,
UnicoreJobSubmission unicoreJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addUNICOREJobSubmissionDetails(computeResourceId, priorityOrder, unicoreJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public UnicoreJobSubmission getUnicoreJobSubmission(AuthzToken authzToken, String jobSubmissionId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UnicoreJobSubmission result = regClient.getUnicoreJobSubmission(jobSubmissionId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving Unicore job submission interface to resource compute resource...";
logger.error(jobSubmissionId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given SSH Job Submission details
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param sshJobSubmission The SSHJobSubmission object to be updated.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean updateSSHJobSubmissionDetails(AuthzToken authzToken, String jobSubmissionInterfaceId, SSHJobSubmission sshJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateSSHJobSubmissionDetails(jobSubmissionInterfaceId, sshJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given cloud Job Submission details
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param cloudJobSubmission The SSHJobSubmission object to be updated.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean updateCloudJobSubmissionDetails(AuthzToken authzToken, String jobSubmissionInterfaceId, CloudJobSubmission cloudJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateCloudJobSubmissionDetails(jobSubmissionInterfaceId, cloudJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateUnicoreJobSubmissionDetails(AuthzToken authzToken, String jobSubmissionInterfaceId, UnicoreJobSubmission unicoreJobSubmission)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUnicoreJobSubmissionDetails(jobSubmissionInterfaceId, unicoreJobSubmission);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Local data moevement details to a compute resource
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param resourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param localDataMovement The LOCALDataMovement object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addLocalDataMovementDetails(AuthzToken authzToken, String resourceId, DMType dmType, int priorityOrder,
LOCALDataMovement localDataMovement) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addLocalDataMovementDetails(resourceId, dmType, priorityOrder, localDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceId, "Error while adding data movement interface to resource resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding data movement interface to resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given Local data movement details
*
* @param dataMovementInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param localDataMovement The LOCALDataMovement object to be updated.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateLocalDataMovementDetails(AuthzToken authzToken, String dataMovementInterfaceId, LOCALDataMovement localDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateLocalDataMovementDetails(dataMovementInterfaceId, localDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while updating local data movement interface..", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating local data movement interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public LOCALDataMovement getLocalDataMovement(AuthzToken authzToken, String dataMovementId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
LOCALDataMovement result = regClient.getLocalDataMovement(dataMovementId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving local data movement interface to resource compute resource...";
logger.error(dataMovementId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a SCP data moevement details to a compute resource
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param resourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param scpDataMovement The SCPDataMovement object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addSCPDataMovementDetails(AuthzToken authzToken, String resourceId, DMType dmType, int priorityOrder, SCPDataMovement scpDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addSCPDataMovementDetails(resourceId, dmType, priorityOrder, scpDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceId, "Error while adding data movement interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given scp data movement details
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param dataMovementInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param scpDataMovement The SCPDataMovement object to be updated.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateSCPDataMovementDetails(AuthzToken authzToken, String dataMovementInterfaceId, SCPDataMovement scpDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateSCPDataMovementDetails(dataMovementInterfaceId, scpDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public SCPDataMovement getSCPDataMovement(AuthzToken authzToken, String dataMovementId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
SCPDataMovement result = regClient.getSCPDataMovement(dataMovementId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving SCP data movement interface to resource compute resource...";
logger.error(dataMovementId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String addUnicoreDataMovementDetails(AuthzToken authzToken, String resourceId, DMType dmType, int priorityOrder, UnicoreDataMovement unicoreDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addUnicoreDataMovementDetails(resourceId, dmType, priorityOrder, unicoreDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceId, "Error while adding data movement interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateUnicoreDataMovementDetails(AuthzToken authzToken, String dataMovementInterfaceId, UnicoreDataMovement unicoreDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUnicoreDataMovementDetails(dataMovementInterfaceId, unicoreDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while updating unicore data movement to compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating unicore data movement to compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public UnicoreDataMovement getUnicoreDataMovement(AuthzToken authzToken, String dataMovementId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UnicoreDataMovement result = regClient.getUnicoreDataMovement(dataMovementId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving UNICORE data movement interface...";
logger.error(dataMovementId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a GridFTP data moevement details to a compute resource
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param computeResourceId The identifier of the compute resource to which JobSubmission protocol to be added
* @param priorityOrder Specify the priority of this job manager. If this is the only jobmanager, the priority can be zero.
* @param gridFTPDataMovement The GridFTPDataMovement object to be added to the resource.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public String addGridFTPDataMovementDetails(AuthzToken authzToken, String computeResourceId, DMType dmType, int priorityOrder,
GridFTPDataMovement gridFTPDataMovement) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.addGridFTPDataMovementDetails(computeResourceId, dmType, priorityOrder, gridFTPDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while adding data movement interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update the given GridFTP data movement details to a compute resource
* App catalog will return a dataMovementInterfaceId which will be added to the dataMovementInterfaces.
*
* @param dataMovementInterfaceId The identifier of the JobSubmission Interface to be updated.
* @param gridFTPDataMovement The GridFTPDataMovement object to be updated.
* @return status
* Returns a success/failure of the updation.
*/
@Override
@SecurityCheck
public boolean updateGridFTPDataMovementDetails(AuthzToken authzToken, String dataMovementInterfaceId, GridFTPDataMovement gridFTPDataMovement)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGridFTPDataMovementDetails(dataMovementInterfaceId, gridFTPDataMovement);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while adding job submission interface to resource compute resource...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding job submission interface to resource compute resource. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public GridFTPDataMovement getGridFTPDataMovement(AuthzToken authzToken, String dataMovementId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
GridFTPDataMovement result = regClient.getGridFTPDataMovement(dataMovementId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String errorMsg = "Error while retrieving GridFTP data movement interface to resource compute resource...";
logger.error(dataMovementId, errorMsg, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMsg + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Change the priority of a given job submisison interface
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be changed
* @param newPriorityOrder
* @return status
* Returns a success/failure of the change.
*/
@Override
@SecurityCheck
public boolean changeJobSubmissionPriority(AuthzToken authzToken, String jobSubmissionInterfaceId, int newPriorityOrder) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return false;
}
/**
* Change the priority of a given data movement interface
*
* @param dataMovementInterfaceId The identifier of the DataMovement Interface to be changed
* @param newPriorityOrder
* @return status
* Returns a success/failure of the change.
*/
@Override
@SecurityCheck
public boolean changeDataMovementPriority(AuthzToken authzToken, String dataMovementInterfaceId, int newPriorityOrder)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return false;
}
/**
* Change the priorities of a given set of job submission interfaces
*
* @param jobSubmissionPriorityMap A Map of identifiers of the JobSubmission Interfaces and thier associated priorities to be set.
* @return status
* Returns a success/failure of the changes.
*/
@Override
@SecurityCheck
public boolean changeJobSubmissionPriorities(AuthzToken authzToken, Map<String, Integer> jobSubmissionPriorityMap)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return false;
}
/**
* Change the priorities of a given set of data movement interfaces
*
* @param dataMovementPriorityMap A Map of identifiers of the DataMovement Interfaces and thier associated priorities to be set.
* @return status
* Returns a success/failure of the changes.
*/
@Override
@SecurityCheck
public boolean changeDataMovementPriorities(AuthzToken authzToken, Map<String, Integer> dataMovementPriorityMap)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
return false;
}
/**
* Delete a given job submisison interface
*
* @param jobSubmissionInterfaceId The identifier of the JobSubmission Interface to be changed
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteJobSubmissionInterface(AuthzToken authzToken, String computeResourceId, String jobSubmissionInterfaceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteJobSubmissionInterface(computeResourceId, jobSubmissionInterfaceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(jobSubmissionInterfaceId, "Error while deleting job submission interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting job submission interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete a given data movement interface
*
* @param dataMovementInterfaceId The identifier of the DataMovement Interface to be changed
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteDataMovementInterface(AuthzToken authzToken, String resourceId, String dataMovementInterfaceId, DMType dmType)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteDataMovementInterface(resourceId, dataMovementInterfaceId, dmType);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(dataMovementInterfaceId, "Error while deleting data movement interface...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting data movement interface. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String registerResourceJobManager(AuthzToken authzToken, ResourceJobManager resourceJobManager) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerResourceJobManager(resourceJobManager);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceJobManager.getResourceJobManagerId(), "Error while adding resource job manager...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while adding resource job manager. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateResourceJobManager(AuthzToken authzToken, String resourceJobManagerId, ResourceJobManager updatedResourceJobManager)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateResourceJobManager(resourceJobManagerId, updatedResourceJobManager);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceJobManagerId, "Error while updating resource job manager...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating resource job manager. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public ResourceJobManager getResourceJobManager(AuthzToken authzToken,String resourceJobManagerId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ResourceJobManager result = regClient.getResourceJobManager(resourceJobManagerId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceJobManagerId, "Error while retrieving resource job manager...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving resource job manager. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteResourceJobManager(AuthzToken authzToken, String resourceJobManagerId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteResourceJobManager(resourceJobManagerId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(resourceJobManagerId, "Error while deleting resource job manager...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting resource job manager. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteBatchQueue(AuthzToken authzToken, String computeResourceId, String queueName) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteBatchQueue(computeResourceId, queueName);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(computeResourceId, "Error while deleting batch queue...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while deleting batch queue. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Register a Gateway Resource Profile.
*
* @param gatewayResourceProfile Gateway Resource Profile Object.
* The GatewayID should be obtained from Airavata gateway registration and passed to register a corresponding
* resource profile.
* @return status.
* Returns a success/failure of the registration.
*/
@Override
@SecurityCheck
public String registerGatewayResourceProfile(AuthzToken authzToken, GatewayResourceProfile gatewayResourceProfile)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerGatewayResourceProfile(gatewayResourceProfile);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while registering gateway resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering gateway resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the given Gateway Resource Profile.
*
* @param gatewayID The identifier for the requested gateway resource
* @return gatewayResourceProfile
* Gateway Resource Profile Object.
*/
@Override
@SecurityCheck
public GatewayResourceProfile getGatewayResourceProfile(AuthzToken authzToken, String gatewayID) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
GatewayResourceProfile result = regClient.getGatewayResourceProfile(gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while retrieving gateway resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving gateway resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Gateway Resource Profile.
*
* @param gatewayID The identifier for the requested gateway resource to be updated.
* @param gatewayResourceProfile Gateway Resource Profile Object.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateGatewayResourceProfile(AuthzToken authzToken,
String gatewayID,
GatewayResourceProfile gatewayResourceProfile) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGatewayResourceProfile(gatewayID, gatewayResourceProfile);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while updating gateway resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete the given Gateway Resource Profile.
*
* @param gatewayID The identifier for the requested gateway resource to be deleted.
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteGatewayResourceProfile(AuthzToken authzToken, String gatewayID) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteGatewayResourceProfile(gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while removing gateway resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while removing gateway resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Compute Resource Preference to a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be added.
* @param computeResourceId Preferences related to a particular compute resource
* @param computeResourcePreference The ComputeResourcePreference object to be added to the resource profile.
* @return status
* Returns a success/failure of the addition. If a profile already exists, this operation will fail.
* Instead an update should be used.
*/
@Override
@SecurityCheck
public boolean addGatewayComputeResourcePreference(AuthzToken authzToken, String gatewayID, String computeResourceId,
ComputeResourcePreference computeResourcePreference) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.addGatewayComputeResourcePreference(gatewayID, computeResourceId, computeResourcePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while registering gateway resource profile preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering gateway resource profile preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean addGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageResourceId, StoragePreference dataStoragePreference)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.addGatewayStoragePreference(gatewayID, storageResourceId, dataStoragePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while registering gateway resource profile preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering gateway resource profile preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a Compute Resource Preference of a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be requested
* @param computeResourceId Preferences related to a particular compute resource
* @return computeResourcePreference
* Returns the ComputeResourcePreference object.
*/
@Override
@SecurityCheck
public ComputeResourcePreference getGatewayComputeResourcePreference(AuthzToken authzToken, String gatewayID, String computeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
ComputeResourcePreference result = regClient.getGatewayComputeResourcePreference(gatewayID, computeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading gateway compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public StoragePreference getGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
StoragePreference result = regClient.getGatewayStoragePreference(gatewayID, storageId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading gateway data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all Compute Resource Preferences of a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be requested
* @return computeResourcePreference
* Returns the ComputeResourcePreference object.
*/
@Override
@SecurityCheck
public List<ComputeResourcePreference> getAllGatewayComputeResourcePreferences(AuthzToken authzToken, String gatewayID)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<ComputeResourcePreference> result = regClient.getAllGatewayComputeResourcePreferences(gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway compute resource preferences...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading gateway compute resource preferences. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<StoragePreference> getAllGatewayStoragePreferences(AuthzToken authzToken, String gatewayID) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<StoragePreference> result = regClient.getAllGatewayStoragePreferences(gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway data storage preferences...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading gateway data storage preferences. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<GatewayResourceProfile> getAllGatewayResourceProfiles(AuthzToken authzToken) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<GatewayResourceProfile> result = regClient.getAllGatewayResourceProfiles();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading retrieving all gateway profiles. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Compute Resource Preference to a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be updated.
* @param computeResourceId Preferences related to a particular compute resource
* @param computeResourcePreference The ComputeResourcePreference object to be updated to the resource profile.
* @return status
* Returns a success/failure of the updation.
*/
@Override
@SecurityCheck
public boolean updateGatewayComputeResourcePreference(AuthzToken authzToken, String gatewayID, String computeResourceId,
ComputeResourcePreference computeResourcePreference)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGatewayComputeResourcePreference(gatewayID, computeResourceId, computeResourcePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageId, StoragePreference dataStoragePreference) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateGatewayStoragePreference(gatewayID, storageId, dataStoragePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete the Compute Resource Preference of a registered gateway profile.
*
* @param gatewayID The identifier for the gateway profile to be deleted.
* @param computeResourceId Preferences related to a particular compute resource
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteGatewayComputeResourcePreference(AuthzToken authzToken, String gatewayID, String computeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteGatewayComputeResourcePreference(gatewayID, computeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteGatewayStoragePreference(gatewayID, storageId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(gatewayID, "Error while reading gateway data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating gateway data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<SSHAccountProvisioner> getSSHAccountProvisioners(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
List<SSHAccountProvisioner> sshAccountProvisioners = new ArrayList<>();
List<SSHAccountProvisionerProvider> sshAccountProvisionerProviders = SSHAccountProvisionerFactory.getSSHAccountProvisionerProviders();
for (SSHAccountProvisionerProvider provider : sshAccountProvisionerProviders) {
// TODO: Move this Thrift conversion to utility class
SSHAccountProvisioner sshAccountProvisioner = new SSHAccountProvisioner();
sshAccountProvisioner.setCanCreateAccount(provider.canCreateAccount());
sshAccountProvisioner.setCanInstallSSHKey(provider.canInstallSSHKey());
sshAccountProvisioner.setName(provider.getName());
List<SSHAccountProvisionerConfigParam> sshAccountProvisionerConfigParams = new ArrayList<>();
for (ConfigParam configParam : provider.getConfigParams()) {
SSHAccountProvisionerConfigParam sshAccountProvisionerConfigParam = new SSHAccountProvisionerConfigParam();
sshAccountProvisionerConfigParam.setName(configParam.getName());
sshAccountProvisionerConfigParam.setDescription(configParam.getDescription());
sshAccountProvisionerConfigParam.setIsOptional(configParam.isOptional());
switch (configParam.getType()){
case STRING:
sshAccountProvisionerConfigParam.setType(SSHAccountProvisionerConfigParamType.STRING);
break;
case CRED_STORE_PASSWORD_TOKEN:
sshAccountProvisionerConfigParam.setType(SSHAccountProvisionerConfigParamType.CRED_STORE_PASSWORD_TOKEN);
break;
}
sshAccountProvisionerConfigParams.add(sshAccountProvisionerConfigParam);
}
sshAccountProvisioner.setConfigParams(sshAccountProvisionerConfigParams);
sshAccountProvisioners.add(sshAccountProvisioner);
}
return sshAccountProvisioners;
}
@Override
@SecurityCheck
public boolean doesUserHaveSSHAccount(AuthzToken authzToken, String computeResourceId, String userId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
return SSHAccountManager.doesUserHaveSSHAccount(gatewayId, computeResourceId, userId);
} catch (Exception e) {
String errorMessage = "Error occurred while checking if [" + userId + "] has an SSH Account on [" +
computeResourceId + "].";
logger.error(errorMessage, e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(errorMessage + " More info : " + e.getMessage());
throw exception;
}
}
@Override
@SecurityCheck
public UserComputeResourcePreference setupUserComputeResourcePreferencesForSSH(AuthzToken authzToken, String computeResourceId, String userId, String airavataCredStoreToken) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
CredentialStoreService.Client csClient = csClientPool.getResource();
SSHCredential sshCredential = null;
try {
sshCredential = csClient.getSSHCredential(airavataCredStoreToken, gatewayId);
}catch (Exception e){
logger.error("Error occurred while retrieving SSH Credential", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while retrieving SSH Credential. More info : " + e.getMessage());
csClientPool.returnBrokenResource(csClient);
throw exception;
}
try {
UserComputeResourcePreference userComputeResourcePreference = SSHAccountManager.setupSSHAccount(gatewayId, computeResourceId, userId, sshCredential);
return userComputeResourcePreference;
}catch (Exception e){
logger.error("Error occurred while automatically setting up SSH account for user [" + userId + "]", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error occurred while automatically setting up SSH account for user [" + userId + "]. More info : " + e.getMessage());
throw exception;
}
}
/**
* Register a User Resource Profile.
*
* @param userResourceProfile User Resource Profile Object.
* The userId should be obtained from Airavata user profile registration and passed to register a corresponding
* resource profile.
* @return status.
* Returns a success/failure of the registration.
*/
@Override
@SecurityCheck
public String registerUserResourceProfile(AuthzToken authzToken, UserResourceProfile userResourceProfile)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerUserResourceProfile(userResourceProfile);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error("Error while registering user resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering user resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch the given User Resource Profile.
*
* @param userId The identifier for the requested User resource
*
* @param gatewayID The identifier to link a gateway for the requested User resource
*
* @return userResourceProfile
* User Resource Profile Object.
*/
@Override
@SecurityCheck
public UserResourceProfile getUserResourceProfile(AuthzToken authzToken, String userId, String gatewayID) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UserResourceProfile result = regClient.getUserResourceProfile(userId, gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while retrieving user resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a User Resource Profile.
*
* @param userId : The identifier for the requested user resource profile to be updated.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userResourceProfile User Resource Profile Object.
* @return status
* Returns a success/failure of the update.
*/
@Override
@SecurityCheck
public boolean updateUserResourceProfile(AuthzToken authzToken,
String userId,
String gatewayID,
UserResourceProfile userResourceProfile) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUserResourceProfile(userId, gatewayID, userResourceProfile);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while updating user resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete the given User Resource Profile.
*
* @param userId : The identifier for the requested userId resource to be deleted.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteUserResourceProfile(AuthzToken authzToken, String userId, String gatewayID) throws TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteUserResourceProfile(userId, gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while removing user resource profile...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while removing user resource profile. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Add a Compute Resource Preference to a registered User Resource profile.
*
* @param userId The identifier for the User Resource profile to be added.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userComputeResourceId Preferences related to a particular compute resource
* @param userComputeResourcePreference The ComputeResourcePreference object to be added to the resource profile.
* @return status
* Returns a success/failure of the addition. If a profile already exists, this operation will fail.
* Instead an update should be used.
*/
@Override
@SecurityCheck
public boolean addUserComputeResourcePreference(AuthzToken authzToken, String userId, String gatewayID, String userComputeResourceId,
UserComputeResourcePreference userComputeResourcePreference) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.addUserComputeResourcePreference(userId, gatewayID, userComputeResourceId, userComputeResourcePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while registering user resource profile preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering user resource profile preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean addUserStoragePreference(AuthzToken authzToken, String userId, String gatewayID, String userStorageResourceId, UserStoragePreference dataStoragePreference)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.addUserStoragePreference(userId, gatewayID, userStorageResourceId, dataStoragePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while registering user storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while registering user storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch a Compute Resource Preference of a registered User Resource profile.
*
* @param userId : The identifier for the User Resource profile to be requested
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userComputeResourceId Preferences related to a particular compute resource
* @return computeResourcePreference
* Returns the ComputeResourcePreference object.
*/
@Override
@SecurityCheck
public UserComputeResourcePreference getUserComputeResourcePreference(AuthzToken authzToken, String userId, String gatewayID, String userComputeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UserComputeResourcePreference result = regClient.getUserComputeResourcePreference(userId, gatewayID, userComputeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading user compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public UserStoragePreference getUserStoragePreference(AuthzToken authzToken, String userId, String gatewayID, String userStorageId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
UserStoragePreference result = regClient.getUserStoragePreference(userId, gatewayID, userStorageId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading user data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Fetch all User Compute Resource Preferences of a registered gateway profile.
*
* @param userId
* @param gatewayID The identifier for the gateway profile to be requested
* @return computeResourcePreference
* Returns the ComputeResourcePreference object.
*/
@Override
@SecurityCheck
public List<UserComputeResourcePreference> getAllUserComputeResourcePreferences(AuthzToken authzToken, String userId, String gatewayID)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<UserComputeResourcePreference> result = regClient.getAllUserComputeResourcePreferences(userId, gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading User compute resource preferences...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading User compute resource preferences. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<UserStoragePreference> getAllUserStoragePreferences(AuthzToken authzToken, String userId, String gatewayID) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<UserStoragePreference> result = regClient.getAllUserStoragePreferences(userId, gatewayID);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading User data storage preferences...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading User data storage preferences. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<UserResourceProfile> getAllUserResourceProfiles(AuthzToken authzToken) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<UserResourceProfile> result = regClient.getAllUserResourceProfiles();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while reading retrieving all user resource profiles. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Update a Compute Resource Preference to a registered User Resource profile.
*
* @param userId : The identifier for the User Resource profile to be updated.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userComputeResourceId Preferences related to a particular compute resource
* @param userComputeResourcePreference The ComputeResourcePreference object to be updated to the resource profile.
* @return status
* Returns a success/failure of the updation.
*/
@Override
@SecurityCheck
public boolean updateUserComputeResourcePreference(AuthzToken authzToken, String userId, String gatewayID, String userComputeResourceId,
UserComputeResourcePreference userComputeResourcePreference)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUserComputeResourcePreference(userId, gatewayID, userComputeResourceId, userComputeResourcePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean updateUserStoragePreference(AuthzToken authzToken, String userId, String gatewayID, String userStorageId, UserStoragePreference dataStoragePreference) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.updateUserStoragePreference(userId, gatewayID, userStorageId, dataStoragePreference);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Delete the Compute Resource Preference of a registered User Resource profile.
*
* @param userId The identifier for the User profile to be deleted.
* @param gatewayID The identifier to link a gateway for the requested User resource
* @param userComputeResourceId Preferences related to a particular compute resource
* @return status
* Returns a success/failure of the deletion.
*/
@Override
@SecurityCheck
public boolean deleteUserComputeResourcePreference(AuthzToken authzToken, String userId,String gatewayID, String userComputeResourceId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteUserComputeResourcePreference(userId, gatewayID, userComputeResourceId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user compute resource preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user compute resource preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean deleteUserStoragePreference(AuthzToken authzToken, String userId, String gatewayID, String userStorageId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.deleteUserStoragePreference(userId, gatewayID, userStorageId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
logger.error(userId, "Error while reading user data storage preference...", e);
AiravataSystemException exception = new AiravataSystemException();
exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage("Error while updating user data storage preference. More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<String> getAllWorkflows(AuthzToken authzToken, String gatewayId) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<String> result = regClient.getAllWorkflows(gatewayId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retrieving all workflow template Ids.";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
public List<QueueStatusModel> getLatestQueueStatuses(AuthzToken authzToken) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<QueueStatusModel> result = regClient.getLatestQueueStatuses();
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retrieving queue statuses";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public WorkflowModel getWorkflow(AuthzToken authzToken, String workflowTemplateId)
throws InvalidRequestException, AiravataClientException, AuthorizationException, AiravataSystemException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
WorkflowModel result = regClient.getWorkflow(workflowTemplateId);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retrieving the workflow "+workflowTemplateId+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public void deleteWorkflow(AuthzToken authzToken, String workflowTemplateId)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
regClient.deleteWorkflow(workflowTemplateId);
registryClientPool.returnResource(regClient);
return;
} catch (Exception e) {
String msg = "Error in deleting the workflow "+workflowTemplateId+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String registerWorkflow(AuthzToken authzToken, String gatewayId, WorkflowModel workflow)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerWorkflow(gatewayId, workflow);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in registering the workflow "+workflow.getName()+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateWorkflow(AuthzToken authzToken, String workflowTemplateId, WorkflowModel workflow)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
regClient.updateWorkflow(workflowTemplateId, workflow);
registryClientPool.returnResource(regClient);
return;
} catch (Exception e) {
String msg = "Error in updating the workflow "+workflow.getName()+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String getWorkflowTemplateId(AuthzToken authzToken, String workflowName)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.getWorkflowTemplateId(workflowName);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retrieving the workflow template id for "+workflowName+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean isWorkflowExistWithName(AuthzToken authzToken, String workflowName)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
boolean result = regClient.isWorkflowExistWithName(workflowName);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in veriying the workflow for workflow name "+workflowName+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* ReplicaCatalog Related Methods
* @return
* @throws TException
* @throws ApplicationSettingsException
*/
@Override
@SecurityCheck
public String registerDataProduct(AuthzToken authzToken, DataProductModel dataProductModel) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerDataProduct(dataProductModel);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in registering the data resource"+dataProductModel.getProductName()+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public DataProductModel getDataProduct(AuthzToken authzToken, String productUri) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
DataProductModel result = regClient.getDataProduct(productUri);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retreiving the data product "+productUri+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String registerReplicaLocation(AuthzToken authzToken, DataReplicaLocationModel replicaLocationModel) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
String result = regClient.registerReplicaLocation(replicaLocationModel);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retreiving the replica "+replicaLocationModel.getReplicaName()+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public DataProductModel getParentDataProduct(AuthzToken authzToken, String productUri) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
DataProductModel result = regClient.getParentDataProduct(productUri);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retreiving the parent data product for "+ productUri+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<DataProductModel> getChildDataProducts(AuthzToken authzToken, String productUri) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
try {
List<DataProductModel> result = regClient.getChildDataProducts(productUri);
registryClientPool.returnResource(regClient);
return result;
} catch (Exception e) {
String msg = "Error in retreiving the child products for "+productUri+".";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
/**
* Group Manager and Data Sharing Related API methods
*
* @param authzToken
* @param resourceId
* @param resourceType
* @param userPermissionList
*/
@Override
@SecurityCheck
public boolean shareResourceWithUsers(AuthzToken authzToken, String resourceId, ResourceType resourceType,
Map<String, ResourcePermissionType> userPermissionList) throws InvalidRequestException,
AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: first verify that authenticating user is OWNER of the resource
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
for(Map.Entry<String, ResourcePermissionType> userPermission : userPermissionList.entrySet()){
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
if(userPermission.getValue().equals(ResourcePermissionType.WRITE))
sharingClient.shareEntityWithUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE", true);
else if(userPermission.getValue().equals(ResourcePermissionType.READ))
sharingClient.shareEntityWithUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ", true);
else if(userPermission.getValue().equals(ResourcePermissionType.EXEC))
sharingClient.shareEntityWithUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "EXEC", true);
else {
logger.error("Invalid ResourcePermissionType : " + userPermission.getValue().toString());
throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION);
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return true;
} catch (Exception e) {
String msg = "Error in sharing resource with users. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
public boolean shareResourceWithGroups(AuthzToken authzToken, String resourceId, ResourceType resourceType,
Map<String, ResourcePermissionType> groupPermissionList)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: first verify that authenticating user is OWNER of the resource
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
for(Map.Entry<String, ResourcePermissionType> groupPermission : groupPermissionList.entrySet()){
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
if(groupPermission.getValue().equals(ResourcePermissionType.WRITE))
sharingClient.shareEntityWithGroups(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE", true);
else if(groupPermission.getValue().equals(ResourcePermissionType.READ))
sharingClient.shareEntityWithGroups(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ", true);
else if(groupPermission.getValue().equals(ResourcePermissionType.EXEC))
sharingClient.shareEntityWithGroups(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "EXEC", true);
else {
logger.error("Invalid ResourcePermissionType : " + groupPermission.getValue().toString());
throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION);
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return true;
} catch (Exception e) {
String msg = "Error in sharing resource with groups. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean revokeSharingOfResourceFromUsers(AuthzToken authzToken, String resourceId, ResourceType resourceType,
Map<String, ResourcePermissionType> userPermissionList) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: first verify that authenticating user is OWNER of the resource
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
for(Map.Entry<String, ResourcePermissionType> userPermission : userPermissionList.entrySet()){
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
if(userPermission.getValue().equals(ResourcePermissionType.WRITE))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE");
else if(userPermission.getValue().equals(ResourcePermissionType.READ))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ");
else if(userPermission.getValue().equals(ResourcePermissionType.EXEC))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(userPermission.getKey()), authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "EXEC");
else {
logger.error("Invalid ResourcePermissionType : " + userPermission.getValue().toString());
throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION);
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return true;
} catch (Exception e) {
String msg = "Error in revoking access to resource from users. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
public boolean revokeSharingOfResourceFromGroups(AuthzToken authzToken, String resourceId, ResourceType resourceType,
Map<String, ResourcePermissionType> groupPermissionList)
throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: first verify that authenticating user is OWNER of the resource
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
final String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
try {
// Prevent removing Admins WRITE access and Read Only Admins READ access
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId);
if (groupPermissionList.containsKey(gatewayGroups.getAdminsGroupId())
&& groupPermissionList.get(gatewayGroups.getAdminsGroupId()).equals(ResourcePermissionType.WRITE)) {
throw new Exception("Not allowed to remove Admins group's WRITE access.");
}
if (groupPermissionList.containsKey(gatewayGroups.getReadOnlyAdminsGroupId())
&& groupPermissionList.get(gatewayGroups.getAdminsGroupId()).equals(ResourcePermissionType.READ)) {
throw new Exception("Not allowed to remove Read Only Admins group's READ access.");
}
for(Map.Entry<String, ResourcePermissionType> groupPermission : groupPermissionList.entrySet()){
if(groupPermission.getValue().equals(ResourcePermissionType.WRITE))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "WRITE");
else if(groupPermission.getValue().equals(ResourcePermissionType.READ))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "READ");
else if(groupPermission.getValue().equals(ResourcePermissionType.EXEC))
sharingClient.revokeEntitySharingFromUsers(gatewayId, resourceId,
Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "EXEC");
else {
logger.error("Invalid ResourcePermissionType : " + groupPermission.getValue().toString());
throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION);
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return true;
} catch (Exception e) {
String msg = "Error in revoking access to resource from groups. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<String> getAllAccessibleUsers(AuthzToken authzToken, String resourceId, ResourceType resourceType, ResourcePermissionType permissionType) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
HashSet<String> accessibleUsers = new HashSet<>();
if (permissionType.equals(ResourcePermissionType.WRITE)) {
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":WRITE").stream().forEach(u -> accessibleUsers.add(u.userId));
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":OWNER").stream().forEach(u -> accessibleUsers.add(u.userId));
} else if (permissionType.equals(ResourcePermissionType.READ)) {
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":READ").stream().forEach(u -> accessibleUsers.add(u.userId));
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":OWNER").stream().forEach(u -> accessibleUsers.add(u.userId));
} else if (permissionType.equals(ResourcePermissionType.OWNER)) {
sharingClient.getListOfSharedUsers(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
resourceId, authzToken.getClaimsMap().get(Constants.GATEWAY_ID)
+ ":OWNER").stream().forEach(u -> accessibleUsers.add(u.userId));
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return new ArrayList<>(accessibleUsers);
} catch (Exception e) {
String msg = "Error in getting all accessible users for resource. Resource ID : " + resourceId + " Resource Type : " + resourceType.toString() ;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg + " More info : " + e.getMessage());
sharingClientPool.returnBrokenResource(sharingClient);
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public String createGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
// TODO: verify that gatewayId in groupResourceProfile matches authzToken gatewayId
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
try {
String groupResourceProfileId = regClient.createGroupResourceProfile(groupResourceProfile);
if(ServerSettings.isEnableSharing()) {
try {
Entity entity = new Entity();
entity.setEntityId(groupResourceProfileId);
final String domainId = groupResourceProfile.getGatewayId();
entity.setDomainId(groupResourceProfile.getGatewayId());
entity.setEntityTypeId(groupResourceProfile.getGatewayId() + ":" + "GROUP_RESOURCE_PROFILE");
entity.setOwnerId(userName + "@" + groupResourceProfile.getGatewayId());
entity.setName(groupResourceProfile.getGroupResourceProfileName());
sharingClient.createEntity(entity);
GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, groupResourceProfile.getGatewayId());
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getAdminsGroupId()), domainId + ":WRITE", true);
sharingClient.shareEntityWithGroups(domainId, entity.getEntityId(), Arrays.asList(gatewayGroups.getReadOnlyAdminsGroupId()), domainId + ":READ", true);
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
logger.error("Rolling back group resource profile creation Group Resource Profile ID : " + groupResourceProfileId);
regClient.removeGroupResourceProfile(groupResourceProfileId);
AiravataSystemException ase = new AiravataSystemException();
ase.setMessage("Failed to create sharing registry record");
throw ase;
}
}
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupResourceProfileId;
} catch (Exception e) {
String msg = "Error creating group resource profile.";
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public void updateGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfile.getGroupResourceProfileId(), gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to update group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to update group resource profile");
}
}
regClient.updateGroupResourceProfile(groupResourceProfile);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
} catch (Exception e) {
String msg = "Error updating group resource profile. groupResourceProfileId: "+groupResourceProfile.getGroupResourceProfileId();
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public GroupResourceProfile getGroupResourceProfile(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
GroupResourceProfile groupResourceProfile = regClient.getGroupResourceProfile(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupResourceProfile;
} catch (Exception e) {
String msg = "Error retrieving group resource profile. groupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean removeGroupResourceProfile(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to remove group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to remove group resource profile");
}
}
boolean result = regClient.removeGroupResourceProfile(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
String msg = "Error removing group resource profile. groupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<GroupResourceProfile> getGroupResourceList(AuthzToken authzToken, String gatewayId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
String userName = authzToken.getClaimsMap().get(Constants.USER_NAME);
try {
List<String> accessibleGroupResProfileIds = new ArrayList<>();
if (ServerSettings.isEnableSharing()) {
List<SearchCriteria> filters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(gatewayId + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name());
filters.add(searchCriteria);
sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID),
userName + "@" + gatewayId, filters, 0, -1).stream().forEach(p -> accessibleGroupResProfileIds
.add(p.entityId));
}
List<GroupResourceProfile> groupResourceProfileList = regClient.getGroupResourceList(gatewayId, accessibleGroupResProfileIds);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupResourceProfileList;
} catch (Exception e) {
String msg = "Error retrieving list group resource profile list. GatewayId: "+ gatewayId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
sharingClientPool.returnBrokenResource(sharingClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean removeGroupComputePrefs(AuthzToken authzToken, String computeResourceId, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to remove group compute preferences");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to remove group compute preferences");
}
}
boolean result = regClient.removeGroupComputePrefs(computeResourceId, groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
String msg = "Error removing group compute resource preferences. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean removeGroupComputeResourcePolicy(AuthzToken authzToken, String resourcePolicyId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
ComputeResourcePolicy computeResourcePolicy = regClient.getGroupComputeResourcePolicy(resourcePolicyId);
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
computeResourcePolicy.getGroupResourceProfileId(), gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to remove group compute resource policy");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to remove group compute resource policy");
}
}
boolean result = regClient.removeGroupComputeResourcePolicy(resourcePolicyId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
String msg = "Error removing group compute resource policy. ResourcePolicyId: "+ resourcePolicyId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public boolean removeGroupBatchQueueResourcePolicy(AuthzToken authzToken, String resourcePolicyId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
BatchQueueResourcePolicy batchQueueResourcePolicy = regClient.getBatchQueueResourcePolicy(resourcePolicyId);
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
batchQueueResourcePolicy.getGroupResourceProfileId(), gatewayId + ":WRITE")){
throw new AuthorizationException("User does not have permission to remove batch queue resource policy");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to remove batch queue resource policy");
}
}
boolean result = regClient.removeGroupBatchQueueResourcePolicy(resourcePolicyId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return result;
} catch (Exception e) {
String msg = "Error removing batch queue resource policy. ResourcePolicyId: "+ resourcePolicyId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public GroupComputeResourcePreference getGroupComputeResourcePreference(AuthzToken authzToken, String computeResourceId, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
GroupComputeResourcePreference groupComputeResourcePreference = regClient.getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupComputeResourcePreference;
} catch (Exception e) {
String msg = "Error retrieving Group compute preference. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public ComputeResourcePolicy getGroupComputeResourcePolicy(AuthzToken authzToken, String resourcePolicyId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
ComputeResourcePolicy computeResourcePolicy = regClient.getGroupComputeResourcePolicy(resourcePolicyId);
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
computeResourcePolicy.getGroupResourceProfileId(), gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
ComputeResourcePolicy computeResourcePolicy = regClient.getGroupComputeResourcePolicy(resourcePolicyId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return computeResourcePolicy;
} catch (Exception e) {
String msg = "Error retrieving Group compute resource policy. ResourcePolicyId: "+ resourcePolicyId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public BatchQueueResourcePolicy getBatchQueueResourcePolicy(AuthzToken authzToken, String resourcePolicyId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
BatchQueueResourcePolicy batchQueueResourcePolicy = regClient.getBatchQueueResourcePolicy(resourcePolicyId);
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
batchQueueResourcePolicy.getGroupResourceProfileId(), gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
BatchQueueResourcePolicy batchQueueResourcePolicy = regClient.getBatchQueueResourcePolicy(resourcePolicyId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return batchQueueResourcePolicy;
} catch (Exception e) {
String msg = "Error retrieving Group batch queue resource policy. ResourcePolicyId: "+ resourcePolicyId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<GroupComputeResourcePreference> getGroupComputeResourcePrefList(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
List<GroupComputeResourcePreference> groupComputeResourcePreferenceList = regClient.getGroupComputeResourcePrefList(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return groupComputeResourcePreferenceList;
} catch (Exception e) {
String msg = "Error retrieving Group compute resource preference. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<BatchQueueResourcePolicy> getGroupBatchQueueResourcePolicyList(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
List<BatchQueueResourcePolicy> batchQueueResourcePolicyList = regClient.getGroupBatchQueueResourcePolicyList(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return batchQueueResourcePolicyList;
} catch (Exception e) {
String msg = "Error retrieving Group batch queue resource policy list. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
@Override
@SecurityCheck
public List<ComputeResourcePolicy> getGroupComputeResourcePolicyList(AuthzToken authzToken, String groupResourceProfileId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
RegistryService.Client regClient = registryClientPool.getResource();
SharingRegistryService.Client sharingClient = sharingClientPool.getResource();
try {
if(ServerSettings.isEnableSharing()) {
try {
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String userId = authzToken.getClaimsMap().get(Constants.USER_NAME);
if (!sharingClient.userHasAccess(gatewayId, userId + "@" + gatewayId,
groupResourceProfileId, gatewayId + ":READ")){
throw new AuthorizationException("User does not have permission to access group resource profile");
}
} catch (Exception e) {
throw new AuthorizationException("User does not have permission to access group resource profile");
}
}
List<ComputeResourcePolicy> computeResourcePolicyList = regClient.getGroupComputeResourcePolicyList(groupResourceProfileId);
registryClientPool.returnResource(regClient);
sharingClientPool.returnResource(sharingClient);
return computeResourcePolicyList;
} catch (Exception e) {
String msg = "Error retrieving Group compute resource policy list. GroupResourceProfileId: "+ groupResourceProfileId;
logger.error(msg, e);
AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR);
exception.setMessage(msg+" More info : " + e.getMessage());
registryClientPool.returnBrokenResource(regClient);
throw exception;
}
}
private void submitExperiment(String gatewayId,String experimentId) throws AiravataException {
ExperimentSubmitEvent event = new ExperimentSubmitEvent(experimentId, gatewayId);
MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, "LAUNCH.EXP-" + UUID.randomUUID().toString(), gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
experimentPublisher.publish(messageContext);
}
private void submitCancelExperiment(String gatewayId, String experimentId) throws AiravataException {
ExperimentSubmitEvent event = new ExperimentSubmitEvent(experimentId, gatewayId);
MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT_CANCEL, "CANCEL.EXP-" + UUID.randomUUID().toString(), gatewayId);
messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp());
experimentPublisher.publish(messageContext);
}
private GatewayGroups retrieveGatewayGroups(RegistryService.Client regClient, String gatewayId) throws TException {
return regClient.getGatewayGroups(gatewayId);
}
} | AIRAVATA-2793 Adding @SecurityCheck annotations
| airavata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/handler/AiravataServerHandler.java | AIRAVATA-2793 Adding @SecurityCheck annotations | <ide><path>iravata-api/airavata-api-server/src/main/java/org/apache/airavata/api/server/handler/AiravataServerHandler.java
<ide> }
<ide>
<ide> @Override
<add> @SecurityCheck
<ide> public boolean shareResourceWithGroups(AuthzToken authzToken, String resourceId, ResourceType resourceType,
<ide> Map<String, ResourcePermissionType> groupPermissionList)
<ide> throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException {
<ide> }
<ide>
<ide> @Override
<add> @SecurityCheck
<ide> public boolean revokeSharingOfResourceFromGroups(AuthzToken authzToken, String resourceId, ResourceType resourceType,
<ide> Map<String, ResourcePermissionType> groupPermissionList)
<ide> throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, TException { |
|
JavaScript | apache-2.0 | 56121d15db8a0ce105f29c0625a16723e55b0b02 | 0 | googleinterns/measurement-library | goog.module('measurementLibrary.eventProcessor.testing.GoogleAnalyticsEventProcessor.buildRequestUrl');
goog.setTestOnly();
const GoogleAnalyticsEventProcessor = goog.require('measurementLibrary.eventProcessor.GoogleAnalyticsEventProcessor');
describe('The `buildRequestUrl_` method ' +
'of GoogleAnalyticsEventProcessor', () => {
/**
* Builds expectation object for the `buildRequestUrl_` function by passing
* in an API secret, measurement ID, and measurement URL to construct the
* event processor with for the function call.
* @param {string|undefined} apiSecret
* @param {string|undefined} measurementId
* @param {string|undefined} measurementUrl
* @return {!Expectation}
*/
function expectRequestUrl(apiSecret, measurementId, measurementUrl) {
const eventProcessor = new GoogleAnalyticsEventProcessor({
'api_secret': apiSecret,
'measurement_id': measurementId,
'measurement_url': measurementUrl,
});
return expect(eventProcessor.buildRequestUrl_());
}
it('creates the correct query string when using the default ' +
'measurement url', () => {
expectRequestUrl(
/* apiSecret */ '123',
/* measurementId */ '456',
/* measurementUrl */ undefined
).toBe('https://www.google-analytics.com/mp/collect?' +
'measurement_id=456&api_secret=123');
expectRequestUrl(
/* apiSecret */ undefined,
/* measurementId */ '456',
/* measurementUrl */ undefined
).toBe('https://www.google-analytics.com/mp/collect?measurement_id=456');
expectRequestUrl(
/* apiSecret */ '123',
/* measurementId */ undefined,
/* measurementUrl */ undefined
).toBe('https://www.google-analytics.com/mp/collect?api_secret=123');
expectRequestUrl(
/* apiSecret */ undefined,
/* measurementId */ undefined,
/* measurementUrl */ undefined
).toBe('https://www.google-analytics.com/mp/collect');
});
it('creates the correct query string when using an overriden ' +
'measurement url', () => {
expectRequestUrl(
/* apiSecret */ '123',
/* measurementId */ '456',
/* measurementUrl */ 'https://test.com'
).toBe('https://test.com?measurement_id=456&api_secret=123');
expectRequestUrl(
/* apiSecret */ undefined,
/* measurementId */ '456',
/* measurementUrl */ 'https://test.com'
).toBe('https://test.com?measurement_id=456');
expectRequestUrl(
/* apiSecret */ '123',
/* measurementId */ undefined,
/* measurementUrl */ 'https://test.com'
).toBe('https://test.com?api_secret=123');
expectRequestUrl(
/* apiSecret */ undefined,
/* measurementId */ undefined,
/* measurementUrl */ 'https://test.com'
).toBe('https://test.com');
});
it('encodes query parameters', () => {
expectRequestUrl(
/* apiSecret */ '12 3',
/* measurementId */ '45 6',
/* measurementUrl */ 'https://test.com'
).toBe('https://test.com?measurement_id=45%206&api_secret=12%203');
});
it('does not add empty strings as query parameters', () => {
expectRequestUrl(
/* apiSecret */ '',
/* measurementId */ undefined,
/* measurementUrl */ 'https://test.com'
).toBe('https://test.com');
expectRequestUrl(
/* apiSecret */ undefined,
/* measurementId */ '',
/* measurementUrl */ 'https://test.com'
).toBe('https://test.com');
expectRequestUrl(
/* apiSecret */ '',
/* measurementId */ '',
/* measurementUrl */ 'https://test.com'
).toBe('https://test.com');
});
});
| test/unit/GoogleAnalyticsEventProcessor/buildRequestUrl_test.js | goog.module('measurementLibrary.eventProcessor.testing.GoogleAnalyticsEventProcessor.buildRequestUrl');
goog.setTestOnly();
const GoogleAnalyticsEventProcessor = goog.require('measurementLibrary.eventProcessor.GoogleAnalyticsEventProcessor');
describe('The `buildRequestUrl` method ' +
'of GoogleAnalyticsEventProcessor', () => {
/**
* Tests the `buildRequestUrl` function by passing in an API secret,
* measurement ID, and measurement URL to construct the event processor
* with and comparing the result of the function with the expected result.
* @param {string} apiSecret
* @param {string} measurementId
* @param {string} measurementUrl
* @return {string} expected
*/
function expectRequestUrl(apiSecret, measurementId, measurementUrl) {
const eventProcessor = new GoogleAnalyticsEventProcessor({
'api_secret': apiSecret,
'measurement_id': measurementId,
'measurement_url': measurementUrl,
});
return expect(eventProcessor.buildRequestUrl_());
}
it('creates the correct query string when using the default ' +
'measurement url', () => {
expectRequestUrl(
/* apiSecret */ '123',
/* measurementId */ '456',
/* measurementUrl */ undefined)
.toBe('https://www.google-analytics.com/mp/collect?' +
'measurement_id=456&api_secret=123');
expectRequestUrl(
/* apiSecret */ '',
/* measurementId */ '456',
/* measurementUrl */ undefined)
.toBe('https://www.google-analytics.com/mp/collect?measurement_id=456');
expectRequestUrl(
/* apiSecret */ '123',
/* measurementId */ '',
/* measurementUrl */ undefined)
.toBe('https://www.google-analytics.com/mp/collect?api_secret=123');
expectRequestUrl(
/* apiSecret */ '',
/* measurementId */ '',
/* measurementUrl */ undefined)
.toBe('https://www.google-analytics.com/mp/collect');
});
it('creates the correct query string when using an overriden ' +
'measurement url', () => {
expectRequestUrl(
/* apiSecret */ '123',
/* measurementId */ '456',
/* measurementUrl */ 'https://test.com')
.toBe('https://test.com?measurement_id=456&api_secret=123');
expectRequestUrl(
/* apiSecret */ '',
/* measurementId */ '456',
/* measurementUrl */ 'https://test.com')
.toBe('https://test.com?measurement_id=456');
expectRequestUrl(
/* apiSecret */ '123',
/* measurementId */ '',
/* measurementUrl */ 'https://test.com')
.toBe('https://test.com?api_secret=123');
expectRequestUrl(
/* apiSecret */ '',
/* measurementId */ '',
/* measurementUrl */ 'https://test.com')
.toBe('https://test.com');
});
it('encodes query parameters', () => {
expectRequestUrl(
/* apiSecret */ '12 3',
/* measurementId */ '45 6',
/* measurementUrl */ 'https://test.com')
.toBe('https://test.com?measurement_id=45%206&api_secret=12%203');
});
});
| update test
| test/unit/GoogleAnalyticsEventProcessor/buildRequestUrl_test.js | update test | <ide><path>est/unit/GoogleAnalyticsEventProcessor/buildRequestUrl_test.js
<ide>
<ide> const GoogleAnalyticsEventProcessor = goog.require('measurementLibrary.eventProcessor.GoogleAnalyticsEventProcessor');
<ide>
<del>describe('The `buildRequestUrl` method ' +
<add>describe('The `buildRequestUrl_` method ' +
<ide> 'of GoogleAnalyticsEventProcessor', () => {
<ide> /**
<del> * Tests the `buildRequestUrl` function by passing in an API secret,
<del> * measurement ID, and measurement URL to construct the event processor
<del> * with and comparing the result of the function with the expected result.
<del> * @param {string} apiSecret
<del> * @param {string} measurementId
<del> * @param {string} measurementUrl
<del> * @return {string} expected
<add> * Builds expectation object for the `buildRequestUrl_` function by passing
<add> * in an API secret, measurement ID, and measurement URL to construct the
<add> * event processor with for the function call.
<add> * @param {string|undefined} apiSecret
<add> * @param {string|undefined} measurementId
<add> * @param {string|undefined} measurementUrl
<add> * @return {!Expectation}
<ide> */
<ide> function expectRequestUrl(apiSecret, measurementId, measurementUrl) {
<ide> const eventProcessor = new GoogleAnalyticsEventProcessor({
<ide> expectRequestUrl(
<ide> /* apiSecret */ '123',
<ide> /* measurementId */ '456',
<del> /* measurementUrl */ undefined)
<del> .toBe('https://www.google-analytics.com/mp/collect?' +
<del> 'measurement_id=456&api_secret=123');
<add> /* measurementUrl */ undefined
<add> ).toBe('https://www.google-analytics.com/mp/collect?' +
<add> 'measurement_id=456&api_secret=123');
<ide>
<ide> expectRequestUrl(
<del> /* apiSecret */ '',
<add> /* apiSecret */ undefined,
<ide> /* measurementId */ '456',
<del> /* measurementUrl */ undefined)
<del> .toBe('https://www.google-analytics.com/mp/collect?measurement_id=456');
<add> /* measurementUrl */ undefined
<add> ).toBe('https://www.google-analytics.com/mp/collect?measurement_id=456');
<ide>
<ide> expectRequestUrl(
<ide> /* apiSecret */ '123',
<del> /* measurementId */ '',
<del> /* measurementUrl */ undefined)
<del> .toBe('https://www.google-analytics.com/mp/collect?api_secret=123');
<add> /* measurementId */ undefined,
<add> /* measurementUrl */ undefined
<add> ).toBe('https://www.google-analytics.com/mp/collect?api_secret=123');
<ide>
<ide> expectRequestUrl(
<del> /* apiSecret */ '',
<del> /* measurementId */ '',
<del> /* measurementUrl */ undefined)
<del> .toBe('https://www.google-analytics.com/mp/collect');
<add> /* apiSecret */ undefined,
<add> /* measurementId */ undefined,
<add> /* measurementUrl */ undefined
<add> ).toBe('https://www.google-analytics.com/mp/collect');
<ide> });
<ide>
<ide> it('creates the correct query string when using an overriden ' +
<ide> expectRequestUrl(
<ide> /* apiSecret */ '123',
<ide> /* measurementId */ '456',
<del> /* measurementUrl */ 'https://test.com')
<del> .toBe('https://test.com?measurement_id=456&api_secret=123');
<add> /* measurementUrl */ 'https://test.com'
<add> ).toBe('https://test.com?measurement_id=456&api_secret=123');
<ide>
<ide> expectRequestUrl(
<del> /* apiSecret */ '',
<add> /* apiSecret */ undefined,
<ide> /* measurementId */ '456',
<del> /* measurementUrl */ 'https://test.com')
<del> .toBe('https://test.com?measurement_id=456');
<add> /* measurementUrl */ 'https://test.com'
<add> ).toBe('https://test.com?measurement_id=456');
<ide>
<ide> expectRequestUrl(
<ide> /* apiSecret */ '123',
<del> /* measurementId */ '',
<del> /* measurementUrl */ 'https://test.com')
<del> .toBe('https://test.com?api_secret=123');
<add> /* measurementId */ undefined,
<add> /* measurementUrl */ 'https://test.com'
<add> ).toBe('https://test.com?api_secret=123');
<ide>
<ide> expectRequestUrl(
<del> /* apiSecret */ '',
<del> /* measurementId */ '',
<del> /* measurementUrl */ 'https://test.com')
<del> .toBe('https://test.com');
<add> /* apiSecret */ undefined,
<add> /* measurementId */ undefined,
<add> /* measurementUrl */ 'https://test.com'
<add> ).toBe('https://test.com');
<ide> });
<ide>
<ide> it('encodes query parameters', () => {
<ide> expectRequestUrl(
<ide> /* apiSecret */ '12 3',
<ide> /* measurementId */ '45 6',
<del> /* measurementUrl */ 'https://test.com')
<del> .toBe('https://test.com?measurement_id=45%206&api_secret=12%203');
<add> /* measurementUrl */ 'https://test.com'
<add> ).toBe('https://test.com?measurement_id=45%206&api_secret=12%203');
<add> });
<add>
<add> it('does not add empty strings as query parameters', () => {
<add> expectRequestUrl(
<add> /* apiSecret */ '',
<add> /* measurementId */ undefined,
<add> /* measurementUrl */ 'https://test.com'
<add> ).toBe('https://test.com');
<add>
<add> expectRequestUrl(
<add> /* apiSecret */ undefined,
<add> /* measurementId */ '',
<add> /* measurementUrl */ 'https://test.com'
<add> ).toBe('https://test.com');
<add>
<add> expectRequestUrl(
<add> /* apiSecret */ '',
<add> /* measurementId */ '',
<add> /* measurementUrl */ 'https://test.com'
<add> ).toBe('https://test.com');
<ide> });
<ide> }); |
|
JavaScript | mit | 77b4a60e836e21eeb8cced192f65bdeedd486f12 | 0 | MircoT/Simulation-Parallel-Project,MircoT/Simulation-Parallel-Project | 'use strict';
const cluster = require('cluster');
class Message
{
constructor (sender, time, point)
{
this.sender = sender;
this.data =
{
'time': time,
'point': point
}
}
}
class Point
{
static fromJSon(json)
{
return new Point(json.x,json.y);
}
constructor(x,y)
{
this.x = x || 0;
this.y = y || 0;
}
add(point)
{
return new Point(this.x+point.x,this.y+point.y);
}
sub(point)
{
return new Point(this.x-point.x,this.y-point.y);
}
abs()
{
return new Point( Math.abs(this.x), Math.abs(this.y) );
}
positive()
{
return new Point( this.x < 0 ? this.x : 0,
this.y < 0 ? this.y : 0 );
}
}
class Grid
{
static fromJSon(json)
{
//copy meta data
var grid = new Grid({
pos : Point.fromJSon(json.pos),
size: Point.fromJSon(json.size),
values: json.values
});
//return
return grid;
}
constructor( info )
{
this.pos = info.pos;
this.size = info.size;
this.boundaries = info.boundaries;
this.time = info.time || 0;
//set prototype
this.pos.__proto__ = Point.prototype;
this.size.__proto__ = Point.prototype;
if("values" in info)
{
this.values = info.values;
}
else
{
this.values = new Array(this.size.y + 2).fill(0);
for (let i = 0; i != this.size.y + 2 ; ++i)
{
this.values[i] = new Array(this.size.x + 2).fill(0);
}
}
}
get(index)
{
if(!this.isInside(index)) return 0;
var relative = index.sub(this.pos).add(new Point(1,1));
var value = this.values[relative.x][relative.y]
return value;
}
set(index, val)
{
if(!this.isInside(index)) return;
var relative = index.sub(this.pos).add(new Point(1,1));
this.values[relative.x][relative.y] = val;
}
endPoint()
{
return this.pos.add(this.size).add(new Point(-1,-1));
}
haveEndBorder()
{
return this.pos.add(this.size)
}
global(index)
{
return index.add(this.pos);
}
isInside(index)
{
var relative = index.sub(this.pos).add(new Point(1,1));
return relative.x >= 0 &&
relative.y >= 0 &&
relative.x < this.values.length &&
relative.y < this.values[0].length;
}
isDifferent(grid,index)
{
return this.isInside(index) &&
grid.isInside(index) &&
this.get(index) != grid.get(index);
}
getBoundary(index)
{
//gloabl end point
var pos = this.pos;
var end = this.endPoint();
//send to
var to =[]
//left / right
if(index.y >= pos.y && index.y <=end.y)
{
if( index.x == pos.x && this.boundaries.hasOwnProperty("left"))
to.push(this.boundaries.left)
if(index.x == end.x && this.boundaries.hasOwnProperty("right"))
to.push(this.boundaries.right)
}
//top / bottom
if(index.x >= pos.x && index.x <=end.x)
{
if(index.y == pos.y && this.boundaries.hasOwnProperty("top"))
{
to.push(this.boundaries.top)
if(index.x == pos.x && this.boundaries.hasOwnProperty("topLeft"))
to.push(this.boundaries.topLeft);
if(index.x == end.x && this.boundaries.hasOwnProperty("topRight"))
to.push(this.boundaries.topRight);
}
if(index.y == end.y && this.boundaries.hasOwnProperty("bottom"))
{
to.push(this.boundaries.bottom)
if(index.x == pos.x && this.boundaries.hasOwnProperty("bottomLeft"))
to.push(this.boundaries.bottomLeft);
if(index.x == end.x && this.boundaries.hasOwnProperty("bottompRight"))
to.push(this.boundaries.bottompRight);
}
}
if(to.length == 0) return null;
return to;
}
getDifferent(grid)
{
var points = [];
var top = this.pos;
var bottom = this.endPoint();
for(var x = top.x; x <= bottom.x; ++x)
{
//diff top line
var pointTop = new Point(x,top.y);
if(this.isDifferent(grid,pointTop))
{
var wid = this.getBoundary(pointTop);
if(wid != null)
points.push
({
pos : pointTop,
value : this.get(pointTop),
worker : wid
});
}
//diff bottom line
var pointBottom = new Point(x,bottom.y);
if(this.isDifferent(grid,pointBottom))
{
var wid = this.getBoundary(pointBottom);
if(wid != null)
points.push
({
pos : pointBottom,
value : this.get(pointBottom),
worker : wid
});
}
}
for(var y = top.y+1; y < bottom.y; ++y)
{
//diff left colunm
var pointLeft = new Point(top.x,y);
if(this.isDifferent(grid,pointLeft))
{
var wid = this.getBoundary(pointLeft);
if(wid != null)
points.push
({
pos : pointLeft,
value : this.get(pointLeft),
worker : wid
});
}
//diff right colunm
var pointRight = new Point(bottom.x,y);
if(this.isDifferent(grid,pointRight))
{
var wid = this.getBoundary(pointRight);
if(wid != null)
points.push
({
pos : pointRight,
value : this.get(pointRight),
worker : wid
});
}
}
return points;
}
toString()
{
var output = "";
var xSize= this.values.length;
var ySize= this.values[0].length;
for (var x = 0; x < ySize; ++x)
{
for (var y = 0; y < xSize; ++y)
{
output += this.values[y][x]+" ";
}
output+="\n";
}
return output;
}
print()
{
console.log(this.toString())
}
}
function main()
{
if(cluster.isMaster)
{
for(var i = 0; i < 4; ++i)
{
cluster.fork();
}
var info =
[
{
pos : new Point(0,0),
size : new Point(4,4),
boundaries :
{
right : 2,
bottom : 3,
bottomRight : 4
}
},
{
pos : new Point(4,0),
size : new Point(4,4),
boundaries :
{
left : 1,
bottom : 4,
bottomLeft : 3
}
},
{
pos : new Point(0,4),
size : new Point(4,4),
boundaries :
{
top: 1,
right: 4,
topRight:2
}
},
{
pos : new Point(4,4),
size : new Point(4,4),
boundaries :
{
top: 2,
left: 3,
topLeft: 1
}
},
]
//test grid
var leftGrid = new Grid(info[0]);
var rightGrid = new Grid(info[1]);
//print tables
leftGrid.print();
//add diff
rightGrid.set(new Point(7,3),1);
//print
rightGrid.print();
//diff
console.log(rightGrid.getDifferent(leftGrid));
for(let id in cluster.workers)
{
cluster.workers[id].on('message',
function (msg)
{
console.log("master: +"+msg);
});
//send info
cluster.workers[id].send(
{
type : 'start',
value : info[id-1]
});
//send diff
cluster.workers[id].send(
{
type : 'grid',
value : testGrid
});
}
console.log("I am master");
}
else if(cluster.isWorker)
{
console.log("I am worker:"+cluster.worker.id);
//attribute
var info =
{
pos : new Point(),
size : new Point()
}
//global grid
var this_grid = null;
//...
process.on('message',function(msg)
{
switch (msg.type)
{
case 'start':
//start
info = msg.value;
console.log("start, "+info);
//alloc
this_grid = new Grid(info);
break;
case 'grid':
//get new grid
var newGrid = Grid.fromJSon(msg.value);
//diff
console.log("I'm ["+String(cluster.worker.id)+"] and diff:\n");
console.log(this_grid.getDifferent(newGrid));
break;
default: break;
}
});
}
}
//call main
main(); | main_3.js | 'use strict';
const cluster = require('cluster');
class Message
{
constructor (sender, time, point)
{
this.sender = sender;
this.data =
{
'time': time,
'point': point
}
}
}
class Point
{
static fromJSon(json)
{
return new Point(json.x,json.y);
}
constructor(x,y)
{
this.x = x || 0;
this.y = y || 0;
}
add(point)
{
return new Point(this.x+point.x,this.y+point.y);
}
sub(point)
{
return new Point(this.x-point.x,this.y-point.y);
}
abs()
{
return new Point( Math.abs(this.x), Math.abs(this.y) );
}
positive()
{
return new Point( this.x < 0 ? this.x : 0,
this.y < 0 ? this.y : 0 );
}
}
class Grid
{
static fromJSon(json)
{
//copy meta data
var grid = new Grid({
pos : Point.fromJSon(json.pos),
size: Point.fromJSon(json.size),
values: json.values
});
//return
return grid;
}
constructor( info )
{
this.pos = info.pos;
this.size = info.size;
this.pos.__proto__ = Point.prototype;
this.size.__proto__ = Point.prototype;
if("values" in info)
{
this.values = info.values;
}
else
{
this.values = new Array(this.size.y + 2).fill(0);
for (let i = 0; i != this.size.y + 2 ; ++i)
{
this.values[i] = new Array(this.size.x + 2).fill(0);
}
}
}
get(index)
{
if(!this.isInside(index)) return 0;
var relative = index.sub(this.pos).add(new Point(1,1));
return this.values[relative.x][relative.y];
}
set(index, val)
{
if(!this.isInside(index)) return;
var relative = index.sub(this.pos).add(new Point(1,1));
this.values[relative.x][relative.y] = val;
}
endPoint()
{
return this.pos.add(this.size).add(new Point(-1,-1));
}
haveEndBorder()
{
return this.pos.add(this.size)
}
global(index)
{
return index.add(this.pos);
}
isInside(index)
{
var relative = index.sub(this.pos).add(new Point(1,1));
return relative.x >= 0 &&
relative.y >= 0 &&
relative.x < this.values.length &&
relative.y < this.values[0].length;
}
isDifferent(grid,point)
{
return this.isInside(point) &&
grid.isInside(point) &&
this.get(point) != grid.get(point);
}
getDifferent(grid)
{
var points = [];
var top = this.pos.add(new Point(-1,-1));
var bottom = this.endPoint();
for(var x = top.x; x < bottom.x; ++x)
{
//diff top line
var pointTop = new Point(x,top.y);
if(this.isDifferent(grid,pointTop))
{
points.push
({
pos : pointTop,
value : this.get(pointTop)
});
}
//diff bottom line
var pointBottom = new Point(x,bottom.y);
if(this.isDifferent(grid,pointBottom))
{
points.push
({
pos : pointBottom,
value : this.get(pointBottom)
});
}
}
for(var y = top.y; y < bottom.y; ++y)
{
//diff left colunm
var pointLeft = new Point(top.x,y);
if(this.isDifferent(grid,pointLeft))
{
points.push
({
pos : pointLeft,
value : this.get(pointLeft)
});
}
//diff right colunm
var pointRight = new Point(bottom.x,y);
if(this.isDifferent(grid,pointRight))
{
points.push
({
pos : pointRight,
value : this.get(pointRight)
});
}
}
return points;
}
toString()
{
var output = "";
var xSize= this.values.length;
var ySize= this.values[0].length;
for (var x = 0; x < ySize; ++x)
{
for (var y = 0; y < xSize; ++y)
{
output += this.values[y][x]+" ";
}
output+="\n";
}
return output;
}
print()
{
console.log(this.toString())
}
}
function main()
{
if(cluster.isMaster)
{
for(var i = 0; i < 4; ++i)
{
cluster.fork();
}
var info =
[
{
pos : new Point(0,0),
size : new Point(4,4)
},
{
pos : new Point(0,4),
size : new Point(4,4)
},
{
pos : new Point(4,0),
size : new Point(4,4)
},
{
pos : new Point(4,4),
size : new Point(4,4)
},
]
//test grid
var leftGrid = new Grid(info[0]);
var rightGrid = new Grid(info[2]);
//print tables
leftGrid.print();
//add diff
rightGrid.set(new Point(3,0),1);
//print
rightGrid.print();
//diff
console.log(rightGrid.getDifferent(leftGrid));
for(let id in cluster.workers)
{
cluster.workers[id].on('message',
function (msg)
{
console.log("master: +"+msg);
});
//send info
cluster.workers[id].send(
{
type : 'start',
value : info[id-1]
});
//send diff
cluster.workers[id].send(
{
type : 'grid',
value : testGrid
});
}
console.log("I am master");
}
else if(cluster.isWorker)
{
console.log("I am worker:"+cluster.worker.id);
//attribute
var info =
{
pos : new Point(),
size : new Point()
}
//global grid
var this_grid = null;
//...
process.on('message',function(msg)
{
switch (msg.type)
{
case 'start':
//start
info = msg.value;
console.log("start, "+info);
//alloc
this_grid = new Grid(info);
break;
case 'grid':
//get new grid
var newGrid = Grid.fromJSon(msg.value);
//diff
console.log("I'm ["+String(cluster.worker.id)+"] and diff:\n");
console.log(this_grid.getDifferent(newGrid));
break;
default: break;
}
});
}
}
//call main
main(); | Changed difference beetwin 2 grid
| main_3.js | Changed difference beetwin 2 grid | <ide><path>ain_3.js
<ide> {
<ide> this.pos = info.pos;
<ide> this.size = info.size;
<del>
<add> this.boundaries = info.boundaries;
<add> this.time = info.time || 0;
<add> //set prototype
<ide> this.pos.__proto__ = Point.prototype;
<ide> this.size.__proto__ = Point.prototype;
<ide>
<ide> {
<ide> if(!this.isInside(index)) return 0;
<ide> var relative = index.sub(this.pos).add(new Point(1,1));
<del> return this.values[relative.x][relative.y];
<add> var value = this.values[relative.x][relative.y]
<add> return value;
<ide> }
<ide>
<ide> set(index, val)
<ide> relative.y < this.values[0].length;
<ide> }
<ide>
<del> isDifferent(grid,point)
<del> {
<del> return this.isInside(point) &&
<del> grid.isInside(point) &&
<del> this.get(point) != grid.get(point);
<add> isDifferent(grid,index)
<add> {
<add> return this.isInside(index) &&
<add> grid.isInside(index) &&
<add> this.get(index) != grid.get(index);
<add> }
<add>
<add> getBoundary(index)
<add> {
<add> //gloabl end point
<add> var pos = this.pos;
<add> var end = this.endPoint();
<add> //send to
<add> var to =[]
<add> //left / right
<add> if(index.y >= pos.y && index.y <=end.y)
<add> {
<add> if( index.x == pos.x && this.boundaries.hasOwnProperty("left"))
<add> to.push(this.boundaries.left)
<add>
<add> if(index.x == end.x && this.boundaries.hasOwnProperty("right"))
<add> to.push(this.boundaries.right)
<add> }
<add> //top / bottom
<add> if(index.x >= pos.x && index.x <=end.x)
<add> {
<add> if(index.y == pos.y && this.boundaries.hasOwnProperty("top"))
<add> {
<add> to.push(this.boundaries.top)
<add>
<add> if(index.x == pos.x && this.boundaries.hasOwnProperty("topLeft"))
<add> to.push(this.boundaries.topLeft);
<add> if(index.x == end.x && this.boundaries.hasOwnProperty("topRight"))
<add> to.push(this.boundaries.topRight);
<add>
<add> }
<add>
<add> if(index.y == end.y && this.boundaries.hasOwnProperty("bottom"))
<add> {
<add> to.push(this.boundaries.bottom)
<add>
<add> if(index.x == pos.x && this.boundaries.hasOwnProperty("bottomLeft"))
<add> to.push(this.boundaries.bottomLeft);
<add> if(index.x == end.x && this.boundaries.hasOwnProperty("bottompRight"))
<add> to.push(this.boundaries.bottompRight);
<add> }
<add> }
<add>
<add> if(to.length == 0) return null;
<add> return to;
<ide> }
<ide>
<ide> getDifferent(grid)
<ide> {
<ide> var points = [];
<del> var top = this.pos.add(new Point(-1,-1));
<add> var top = this.pos;
<ide> var bottom = this.endPoint();
<ide>
<del> for(var x = top.x; x < bottom.x; ++x)
<add> for(var x = top.x; x <= bottom.x; ++x)
<ide> {
<ide> //diff top line
<ide> var pointTop = new Point(x,top.y);
<ide> if(this.isDifferent(grid,pointTop))
<ide> {
<del> points.push
<del> ({
<del> pos : pointTop,
<del> value : this.get(pointTop)
<del> });
<add> var wid = this.getBoundary(pointTop);
<add>
<add> if(wid != null)
<add> points.push
<add> ({
<add> pos : pointTop,
<add> value : this.get(pointTop),
<add> worker : wid
<add> });
<ide> }
<ide> //diff bottom line
<ide> var pointBottom = new Point(x,bottom.y);
<ide> if(this.isDifferent(grid,pointBottom))
<ide> {
<del> points.push
<del> ({
<del> pos : pointBottom,
<del> value : this.get(pointBottom)
<del> });
<del> }
<del> }
<del>
<del> for(var y = top.y; y < bottom.y; ++y)
<add> var wid = this.getBoundary(pointBottom);
<add>
<add> if(wid != null)
<add> points.push
<add> ({
<add> pos : pointBottom,
<add> value : this.get(pointBottom),
<add> worker : wid
<add> });
<add> }
<add> }
<add>
<add> for(var y = top.y+1; y < bottom.y; ++y)
<ide> {
<ide> //diff left colunm
<ide> var pointLeft = new Point(top.x,y);
<ide> if(this.isDifferent(grid,pointLeft))
<ide> {
<del> points.push
<del> ({
<del> pos : pointLeft,
<del> value : this.get(pointLeft)
<del> });
<add> var wid = this.getBoundary(pointLeft);
<add>
<add> if(wid != null)
<add> points.push
<add> ({
<add> pos : pointLeft,
<add> value : this.get(pointLeft),
<add> worker : wid
<add> });
<ide> }
<ide> //diff right colunm
<ide> var pointRight = new Point(bottom.x,y);
<ide> if(this.isDifferent(grid,pointRight))
<ide> {
<del> points.push
<del> ({
<del> pos : pointRight,
<del> value : this.get(pointRight)
<del> });
<add> var wid = this.getBoundary(pointRight);
<add>
<add> if(wid != null)
<add> points.push
<add> ({
<add> pos : pointRight,
<add> value : this.get(pointRight),
<add> worker : wid
<add> });
<ide> }
<ide> }
<ide> return points;
<ide> [
<ide> {
<ide> pos : new Point(0,0),
<del> size : new Point(4,4)
<add> size : new Point(4,4),
<add> boundaries :
<add> {
<add> right : 2,
<add> bottom : 3,
<add> bottomRight : 4
<add> }
<ide> },
<ide> {
<add> pos : new Point(4,0),
<add> size : new Point(4,4),
<add> boundaries :
<add> {
<add> left : 1,
<add> bottom : 4,
<add> bottomLeft : 3
<add> }
<add> },
<add> {
<ide> pos : new Point(0,4),
<del> size : new Point(4,4)
<add> size : new Point(4,4),
<add> boundaries :
<add> {
<add> top: 1,
<add> right: 4,
<add> topRight:2
<add> }
<ide> },
<ide> {
<del> pos : new Point(4,0),
<del> size : new Point(4,4)
<del> },
<del> {
<ide> pos : new Point(4,4),
<del> size : new Point(4,4)
<add> size : new Point(4,4),
<add> boundaries :
<add> {
<add> top: 2,
<add> left: 3,
<add> topLeft: 1
<add> }
<ide> },
<ide> ]
<ide> //test grid
<ide> var leftGrid = new Grid(info[0]);
<del> var rightGrid = new Grid(info[2]);
<add> var rightGrid = new Grid(info[1]);
<ide> //print tables
<ide> leftGrid.print();
<ide> //add diff
<del> rightGrid.set(new Point(3,0),1);
<add> rightGrid.set(new Point(7,3),1);
<ide> //print
<ide> rightGrid.print();
<ide> //diff |
|
Java | apache-2.0 | 219b779cbe4809d6d91cecd5eac27274f88dce01 | 0 | awoodworth/appinventor-sources,ZachLamb/appinventor-sources,thequixotic/appinventor-sources,ZachLamb/appinventor-sources,Mateopato/appinventor-sources,josmas/app-inventor,William-Byrne/appinventor-sources,weihuali0509/appinventor-sources,jisqyv/appinventor-sources,bxie/appinventor-sources,marksherman/appinventor-sources,GodUseVPN/appinventor-sources,mit-cml/appinventor-sources,weihuali0509/web-appinventor,farxinu/appinventor-sources,liyucun/appinventor-sources,nickboucart/appinventor-sources,KeithGalli/appinventor-sources,spefley/appinventor-sources,ajcolter/appinventor-sources,lizlooney/appinventor-sources,wanddy/appinventor-sources,nmcalabroso/appinventor-sources,kannan-usf/AppInventorJavaBridge,jsheldonmit/appinventor-sources,jsheldonmit/appinventor-sources,ewpatton/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,farxinu/appinventor-sources,wanddy/appinventor-sources,jisqyv/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,sujianping/appinventor-sources,tatuzaumm/app-inventor2-custom,Mateopato/appinventor-sources,JalexChang/appinventor-sources,kannan-usf/AppInventorJavaBridge,marksherman/appinventor-sources,krishc90/APP-INVENTOR,wadleo/appinventor-sources,frfranca/appinventor-sources,graceRyu/appinventor-sources,barreeeiroo/appinventor-sources,ewpatton/appinventor-sources,mit-cml/appinventor-sources,bitsecure/appinventor1-sources,Edeleon4/punya,CoderDojoLX/appinventor-sources,hasi96/appinventor-sources,youprofit/appinventor-sources,warren922/appinventor-sources,frfranca/appinventor-sources,afmckinney/appinventor-sources,mintingle/appinventor-sources,warren922/appinventor-sources,wicedfast/appinventor-sources,DRavnaas/appinventor-clone,ram8647/appinventor-sources,krishc90/APP-INVENTOR,spefley/appinventor-sources,afmckinney/appinventor-sources,RachaelT/appinventor-sources,sujianping/appinventor-sources,afmckinney/appinventor-sources,onyeka/AppInventor-WebApp,nmcalabroso/appinventor-sources,fturbak/appinventor-sources,youprofit/appinventor-sources,toropeza/appinventor-sources,krishc90/APP-INVENTOR,wicedfast/appinventor-sources,tvomf/appinventor-mapps,joshaham/latest_app_inventor,RachaelT/appinventor-sources,wadleo/appinventor-sources,farxinu/appinventor-sources,gitars/appinventor-sources,GodUseVPN/appinventor-sources,aouskaroui/appinventor-sources,wanddy/appinventor-sources,emeryotopalik/appinventor-sources,bxie/appinventor-sources,krishc90/APP-INVENTOR,FIRST-Tech-Challenge/appinventor-sources,tiffanyle/appinventor-sources,youprofit/appinventor-sources,aouskaroui/appinventor-sources,thilankam/appinventor-sources,GodUseVPN/appinventor-sources,tvomf/appinventor-mapps,DRavnaas/appinventor-clone,onyeka/AppInventor-WebApp,jsheldonmit/appinventor-sources,awoodworth/appinventor-sources,William-Byrne/appinventor-sources,mintingle/appinventor-sources,William-Byrne/appinventor-sources,dengxinyue0420/appinventor-sources,liyucun/appinventor-sources,jithinbp/appinventor-sources,graceRyu/appinventor-sources,kkashi01/appinventor-sources,jisqyv/appinventor-sources,Momoumar/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,frfranca/appinventor-sources,toropeza/appinventor-sources,ajcolter/appinventor-sources,JalexChang/appinventor-sources,josmas/app-inventor,ram8647/appinventor-sources,mintingle/appinventor-sources,tvomf/appinventor-mapps,LaboratoryForPlayfulComputation/appinventor-sources,ewpatton/appinventor-sources,JalexChang/appinventor-sources,graceRyu/appinventor-sources,mark-friedman/web-appinventor,lizlooney/appinventor-sources,barreeeiroo/appinventor-sources,kidebit/AudioBlurp,warren922/appinventor-sources,tatuzaumm/app-inventor2-custom,cs6510/CS6510-LiveEdit-Onyeka,DRavnaas/appinventor-clone,spefley/appinventor-sources,gitars/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,thequixotic/appinventor-sources,fturbak/appinventor-sources,emeryotopalik/appinventor-sources,aouskaroui/appinventor-sources,joshaham/latest_app_inventor,ZachLamb/appinventor-sources,aouskaroui/appinventor-sources,JalexChang/appinventor-sources,gitars/appinventor-sources,mit-dig/punya,lizlooney/appinventor-sources,emeryotopalik/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,mark-friedman/web-appinventor,ZachLamb/appinventor-sources,awoodworth/appinventor-sources,bxie/appinventor-sources,dengxinyue0420/appinventor-sources,tatuzaumm/app-inventor2-custom,spefley/appinventor-sources,marksherman/appinventor-sources,marksherman/appinventor-sources,mit-cml/appinventor-sources,egiurleo/appinventor-sources,frfranca/appinventor-sources,tatuzaumm/app-inventor2-custom,hasi96/appinventor-sources,kkashi01/appinventor-sources,farxinu/appinventor-sources,ram8647/appinventor-sources,egiurleo/appinventor-sources,themadrobot/appinventor-sources,tiffanyle/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,marksherman/appinventor-sources,halatmit/appinventor-sources,egiurleo/appinventor-sources,fmntf/appinventor-sources,tiffanyle/appinventor-sources,jsheldonmit/appinventor-sources,puravidaapps/appinventor-sources,liyucun/appinventor-sources,CoderDojoLX/appinventor-sources,gitars/appinventor-sources,ewpatton/appinventor-sources,KeithGalli/appinventor-sources,emeryotopalik/appinventor-sources,puravidaapps/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,tvomf/appinventor-mapps,kidebit/AudioBlurp,nickboucart/appinventor-sources,mit-dig/punya,wadleo/appinventor-sources,warren922/appinventor-sources,wicedfast/appinventor-sources,liyucun/appinventor-sources,mintingle/appinventor-sources,Momoumar/appinventor-sources,halatmit/appinventor-sources,tiffanyle/appinventor-sources,doburaimo/appinventor-sources,weihuali0509/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,themadrobot/appinventor-sources,DRavnaas/appinventor-clone,awoodworth/appinventor-sources,ZachLamb/appinventor-sources,KeithGalli/appinventor-sources,jisqyv/appinventor-sources,halatmit/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,hasi96/appinventor-sources,Klomi/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,gitars/appinventor-sources,fmntf/appinventor-sources,tatuzaumm/app-inventor2-custom,dengxinyue0420/appinventor-sources,nickboucart/appinventor-sources,puravidaapps/appinventor-sources,RachaelT/appinventor-sources,thilankam/appinventor-sources,wicedfast/appinventor-sources,nickboucart/appinventor-sources,awoodworth/appinventor-sources,ram8647/appinventor-sources,E-Hon/appinventor-sources,bxie/appinventor-sources,joshaham/latest_app_inventor,ewpatton/appinventor-sources,ajcolter/appinventor-sources,doburaimo/appinventor-sources,wanddy/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,puravidaapps/appinventor-sources,Edeleon4/punya,bitsecure/appinventor1-sources,kkashi01/appinventor-sources,liyucun/appinventor-sources,sujianping/appinventor-sources,wadleo/appinventor-sources,warren922/appinventor-sources,ajcolter/appinventor-sources,onyeka/AppInventor-WebApp,kidebit/https-github.com-wicedfast-appinventor-sources,fmntf/appinventor-sources,jithinbp/appinventor-sources,hasi96/appinventor-sources,Mateopato/appinventor-sources,thilankam/appinventor-sources,Momoumar/appinventor-sources,KeithGalli/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,weihuali0509/web-appinventor,toropeza/appinventor-sources,mit-cml/appinventor-sources,CoderDojoLX/appinventor-sources,GodUseVPN/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,nmcalabroso/appinventor-sources,joshaham/latest_app_inventor,youprofit/appinventor-sources,Klomi/appinventor-sources,kidebit/AudioBlurp,barreeeiroo/appinventor-sources,bitsecure/appinventor1-sources,doburaimo/appinventor-sources,graceRyu/appinventor-sources,CoderDojoLX/appinventor-sources,kidebit/AudioBlurp,doburaimo/appinventor-sources,joshaham/latest_app_inventor,Klomi/appinventor-sources,Momoumar/appinventor-sources,wicedfast/appinventor-sources,RachaelT/appinventor-sources,wadleo/appinventor-sources,frfranca/appinventor-sources,JalexChang/appinventor-sources,emeryotopalik/appinventor-sources,mark-friedman/web-appinventor,William-Byrne/appinventor-sources,hasi96/appinventor-sources,wanddy/appinventor-sources,kkashi01/appinventor-sources,thilankam/appinventor-sources,Klomi/appinventor-sources,jithinbp/appinventor-sources,youprofit/appinventor-sources,sujianping/appinventor-sources,Klomi/appinventor-sources,barreeeiroo/appinventor-sources,jsheldonmit/appinventor-sources,Momoumar/appinventor-sources,fturbak/appinventor-sources,weihuali0509/appinventor-sources,dengxinyue0420/appinventor-sources,mintingle/appinventor-sources,marksherman/appinventor-sources,krishc90/APP-INVENTOR,nmcalabroso/appinventor-sources,jisqyv/appinventor-sources,weihuali0509/appinventor-sources,weihuali0509/web-appinventor,mark-friedman/web-appinventor,jisqyv/appinventor-sources,toropeza/appinventor-sources,GodUseVPN/appinventor-sources,afmckinney/appinventor-sources,doburaimo/appinventor-sources,toropeza/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,mit-dig/punya,kannan-usf/AppInventorJavaBridge,sujianping/appinventor-sources,josmas/app-inventor,mit-cml/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,kidebit/https-github.com-wicedfast-appinventor-sources,spefley/appinventor-sources,ewpatton/appinventor-sources,josmas/app-inventor,weihuali0509/appinventor-sources,mintingle/appinventor-sources,E-Hon/appinventor-sources,fturbak/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,tiffanyle/appinventor-sources,Mateopato/appinventor-sources,mit-dig/punya,kkashi01/appinventor-sources,tvomf/appinventor-mapps,mit-dig/punya,CoderDojoLX/appinventor-sources,thequixotic/appinventor-sources,ram8647/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,lizlooney/appinventor-sources,Edeleon4/punya,barreeeiroo/appinventor-sources,thequixotic/appinventor-sources,jithinbp/appinventor-sources,Edeleon4/punya,bitsecure/appinventor1-sources,lizlooney/appinventor-sources,josmas/app-inventor,nmcalabroso/appinventor-sources,jithinbp/appinventor-sources,aouskaroui/appinventor-sources,bxie/appinventor-sources,weihuali0509/web-appinventor,thilankam/appinventor-sources,halatmit/appinventor-sources,nickboucart/appinventor-sources,Mateopato/appinventor-sources,afmckinney/appinventor-sources,dengxinyue0420/appinventor-sources,Edeleon4/punya,fmntf/appinventor-sources,DRavnaas/appinventor-clone,fmntf/appinventor-sources,William-Byrne/appinventor-sources,thequixotic/appinventor-sources,themadrobot/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,egiurleo/appinventor-sources,bitsecure/appinventor1-sources,E-Hon/appinventor-sources,egiurleo/appinventor-sources,KeithGalli/appinventor-sources,onyeka/AppInventor-WebApp,RachaelT/appinventor-sources,mit-cml/appinventor-sources,onyeka/AppInventor-WebApp,puravidaapps/appinventor-sources,josmas/app-inventor,ajcolter/appinventor-sources,themadrobot/appinventor-sources,kannan-usf/AppInventorJavaBridge,mark-friedman/web-appinventor,farxinu/appinventor-sources,themadrobot/appinventor-sources,Edeleon4/punya,mit-dig/punya,halatmit/appinventor-sources,kannan-usf/AppInventorJavaBridge,kkashi01/appinventor-sources,halatmit/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,mit-dig/punya,E-Hon/appinventor-sources,E-Hon/appinventor-sources,weihuali0509/web-appinventor,fturbak/appinventor-sources,graceRyu/appinventor-sources | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
package com.google.appinventor.server;
import com.google.appinventor.server.util.CacheHeaders;
import com.google.appinventor.server.util.CacheHeadersImpl;
import com.google.appinventor.shared.rpc.ServerLayout;
import com.google.appinventor.shared.rpc.UploadResponse;
import com.google.appinventor.shared.rpc.project.UserProject;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet for handling gallery's app publishing.
*
*/
public class GalleryServlet extends OdeServlet {
/*
* URIs for upload requests are structured as follows:
* /<baseurl>/gallery_servlet/<filePath>
*/
// Constants for accessing split URI
/*
* Upload kind can be: "project", "file", or "userfile".
* Constants for these are defined in ServerLayout.
*/
// Constants used when upload kind is "file".
// Since the file path may contain slashes, it must be the last component in the URI.
private static final int FILE_PATH_INDEX = 3;
// Logging support
private static final Logger LOG = Logger.getLogger(UploadServlet.class.getName());
// Object used to safely set cache headers in responses
private static final CacheHeaders CACHE_HEADERS = new CacheHeadersImpl();
// Content type for response header (to avoid security vulnerabilities)
private static final String CONTENT_TYPE = "text/html; charset=utf-8";
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
setDefaultHeader(resp);
UploadResponse uploadResponse;
String uri = req.getRequestURI();
// First, call split with no limit parameter.
String[] uriComponents = uri.split("/");
if (true) {
// long projectId = Long.parseLong(uriComponents[PROJECT_ID_INDEX]);
String fileName = uriComponents[FILE_PATH_INDEX];
InputStream uploadedStream;
try {
uploadedStream = getRequestStream(req, ServerLayout.UPLOAD_FILE_FORM_ELEMENT);
StringWriter writer = new StringWriter();
IOUtils.copy(uploadedStream, writer, null);
String readableStream = writer.toString();
LOG.info("################# TRYING UPLOAD STREAM ###############");
LOG.info(readableStream);
LOG.info("################# ENDING UPLOAD STREAM ###############");
} catch (Exception e) {
throw CrashReport.createAndLogError(LOG, req, null, e);
}
} else {
throw CrashReport.createAndLogError(LOG, req, null,
new IllegalArgumentException("Unknown upload kind: "));
}
// Now, get the PrintWriter for the servlet response and print the UploadResponse.
// On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the
// UploadResponse value will be retrieved as a String via the
// FormSubmitCompleteEvent.getResults() method.
// PrintWriter out = resp.getWriter();
// out.print(uploadResponse.formatAsHtml());
// Set http response information
resp.setStatus(HttpServletResponse.SC_OK);
}
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName)
throws Exception {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
if (item.getFieldName().equals(expectedFieldName)) {
return item.openStream();
}
}
throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
}
/**
* Set a default http header to avoid security vulnerabilities.
*/
private static void setDefaultHeader(HttpServletResponse resp) {
CACHE_HEADERS.setNotCacheable(resp);
resp.setContentType(CONTENT_TYPE);
}
}
| appinventor/appengine/src/com/google/appinventor/server/GalleryServlet.java | // -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
package com.google.appinventor.server;
import com.google.appinventor.server.util.CacheHeaders;
import com.google.appinventor.server.util.CacheHeadersImpl;
import com.google.appinventor.shared.rpc.ServerLayout;
import com.google.appinventor.shared.rpc.UploadResponse;
import com.google.appinventor.shared.rpc.project.UserProject;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet for handling gallery's app publishing.
*
*/
public class GalleryServlet extends OdeServlet {
/*
* URIs for upload requests are structured as follows:
* /<baseurl>/publish/<projectId>/<filePath>
*/
// Logging support
private static final Logger LOG = Logger.getLogger(UploadServlet.class.getName());
// Object used to safely set cache headers in responses
private static final CacheHeaders CACHE_HEADERS = new CacheHeadersImpl();
// Content type for response header (to avoid security vulnerabilities)
private static final String CONTENT_TYPE = "text/html; charset=utf-8";
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
setDefaultHeader(resp);
UploadResponse uploadResponse;
/*
try {
String uri = req.getRequestURI();
// First, call split with no limit parameter.
String[] uriComponents = uri.split("/");
String uploadKind = uriComponents[UPLOAD_KIND_INDEX];
if (uploadKind.equals(ServerLayout.UPLOAD_FILE)) {
uriComponents = uri.split("/", SPLIT_LIMIT_FILE);
long projectId = Long.parseLong(uriComponents[PROJECT_ID_INDEX]);
String fileName = uriComponents[FILE_PATH_INDEX];
InputStream uploadedStream;
try {
uploadedStream = getRequestStream(req, ServerLayout.UPLOAD_FILE_FORM_ELEMENT);
} catch (Exception e) {
throw CrashReport.createAndLogError(LOG, req, null, e);
}
try {
long modificationDate = fileImporter.importFile(userInfoProvider.getUserId(),
projectId, fileName, uploadedStream);
uploadResponse = new UploadResponse(UploadResponse.Status.SUCCESS, modificationDate);
} catch (FileImporterException e) {
uploadResponse = e.uploadResponse;
}
} else {
throw CrashReport.createAndLogError(LOG, req, null,
new IllegalArgumentException("Unknown upload kind: " + uploadKind));
}
// Now, get the PrintWriter for the servlet response and print the UploadResponse.
// On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the
// UploadResponse value will be retrieved as a String via the
// FormSubmitCompleteEvent.getResults() method.
PrintWriter out = resp.getWriter();
out.print(uploadResponse.formatAsHtml());
} catch (IOException e) {
throw CrashReport.createAndLogError(LOG, req, null, e);
}
*/
// Set http response information
resp.setStatus(HttpServletResponse.SC_OK);
}
private InputStream getRequestStream(HttpServletRequest req, String expectedFieldName)
throws Exception {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
if (item.getFieldName().equals(expectedFieldName)) {
return item.openStream();
}
}
throw new IllegalArgumentException("Field " + expectedFieldName + " not found in upload");
}
/**
* Set a default http header to avoid security vulnerabilities.
*/
private static void setDefaultHeader(HttpServletResponse resp) {
CACHE_HEADERS.setNotCacheable(resp);
resp.setContentType(CONTENT_TYPE);
}
}
| Poked servlet input stream
| appinventor/appengine/src/com/google/appinventor/server/GalleryServlet.java | Poked servlet input stream | <ide><path>ppinventor/appengine/src/com/google/appinventor/server/GalleryServlet.java
<ide> import org.apache.commons.fileupload.FileItemStream;
<ide> import org.apache.commons.fileupload.FileItemIterator;
<ide> import org.apache.commons.fileupload.servlet.ServletFileUpload;
<add>import org.apache.commons.io.IOUtils;
<ide>
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide> import java.io.PrintWriter;
<add>import java.io.StringWriter;
<ide> import java.util.logging.Logger;
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide> */
<ide> public class GalleryServlet extends OdeServlet {
<ide>
<add>
<ide> /*
<ide> * URIs for upload requests are structured as follows:
<del> * /<baseurl>/publish/<projectId>/<filePath>
<add> * /<baseurl>/gallery_servlet/<filePath>
<ide> */
<ide>
<add> // Constants for accessing split URI
<add> /*
<add> * Upload kind can be: "project", "file", or "userfile".
<add> * Constants for these are defined in ServerLayout.
<add> */
<add>
<add> // Constants used when upload kind is "file".
<add> // Since the file path may contain slashes, it must be the last component in the URI.
<add> private static final int FILE_PATH_INDEX = 3;
<add>
<ide> // Logging support
<ide> private static final Logger LOG = Logger.getLogger(UploadServlet.class.getName());
<ide>
<ide> @Override
<ide> public void doPost(HttpServletRequest req, HttpServletResponse resp) {
<ide> setDefaultHeader(resp);
<del>
<ide> UploadResponse uploadResponse;
<del>
<del> /*
<del> try {
<del> String uri = req.getRequestURI();
<del> // First, call split with no limit parameter.
<del> String[] uriComponents = uri.split("/");
<del>
<del>
<del> String uploadKind = uriComponents[UPLOAD_KIND_INDEX];
<del>
<del> if (uploadKind.equals(ServerLayout.UPLOAD_FILE)) {
<del> uriComponents = uri.split("/", SPLIT_LIMIT_FILE);
<del> long projectId = Long.parseLong(uriComponents[PROJECT_ID_INDEX]);
<del> String fileName = uriComponents[FILE_PATH_INDEX];
<del> InputStream uploadedStream;
<del> try {
<del> uploadedStream = getRequestStream(req, ServerLayout.UPLOAD_FILE_FORM_ELEMENT);
<del> } catch (Exception e) {
<del> throw CrashReport.createAndLogError(LOG, req, null, e);
<del> }
<del>
<del> try {
<del> long modificationDate = fileImporter.importFile(userInfoProvider.getUserId(),
<del> projectId, fileName, uploadedStream);
<del> uploadResponse = new UploadResponse(UploadResponse.Status.SUCCESS, modificationDate);
<del> } catch (FileImporterException e) {
<del> uploadResponse = e.uploadResponse;
<del> }
<del> } else {
<del> throw CrashReport.createAndLogError(LOG, req, null,
<del> new IllegalArgumentException("Unknown upload kind: " + uploadKind));
<add>
<add> String uri = req.getRequestURI();
<add> // First, call split with no limit parameter.
<add> String[] uriComponents = uri.split("/");
<add>
<add> if (true) {
<add>// long projectId = Long.parseLong(uriComponents[PROJECT_ID_INDEX]);
<add> String fileName = uriComponents[FILE_PATH_INDEX];
<add> InputStream uploadedStream;
<add> try {
<add> uploadedStream = getRequestStream(req, ServerLayout.UPLOAD_FILE_FORM_ELEMENT);
<add> StringWriter writer = new StringWriter();
<add> IOUtils.copy(uploadedStream, writer, null);
<add> String readableStream = writer.toString();
<add> LOG.info("################# TRYING UPLOAD STREAM ###############");
<add> LOG.info(readableStream);
<add> LOG.info("################# ENDING UPLOAD STREAM ###############");
<add> } catch (Exception e) {
<add> throw CrashReport.createAndLogError(LOG, req, null, e);
<ide> }
<ide>
<del> // Now, get the PrintWriter for the servlet response and print the UploadResponse.
<del> // On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the
<del> // UploadResponse value will be retrieved as a String via the
<del> // FormSubmitCompleteEvent.getResults() method.
<del> PrintWriter out = resp.getWriter();
<del> out.print(uploadResponse.formatAsHtml());
<add> } else {
<add> throw CrashReport.createAndLogError(LOG, req, null,
<add> new IllegalArgumentException("Unknown upload kind: "));
<add> }
<ide>
<del> } catch (IOException e) {
<del> throw CrashReport.createAndLogError(LOG, req, null, e);
<del> }
<del> */
<add> // Now, get the PrintWriter for the servlet response and print the UploadResponse.
<add> // On the client side, in the onSubmitComplete method in ode/client/utils/Uploader.java, the
<add> // UploadResponse value will be retrieved as a String via the
<add> // FormSubmitCompleteEvent.getResults() method.
<add>// PrintWriter out = resp.getWriter();
<add>// out.print(uploadResponse.formatAsHtml());
<ide>
<ide> // Set http response information
<ide> resp.setStatus(HttpServletResponse.SC_OK); |
|
JavaScript | mit | a89b27981209f666c94938a1dc3f1b04d8f6f76f | 0 | zeroturnaround/sql-formatter,zeroturnaround/sql-formatter,zeroturnaround/sql-formatter | import dedent from 'dedent-js';
import { NewlineMode } from '../../src/types';
/**
* Tests support for all newline options
* @param {string} language
* @param {Function} format
*/
export default function supportsNewlineOptions(language, format) {
it('throws error when newline is negative number', () => {
expect(() => {
format('SELECT *', { newline: -1 });
}).toThrowErrorMatchingInlineSnapshot(`"newline config must be a positive number."`);
});
it('throws error when newline is zero', () => {
expect(() => {
format('SELECT *', { newline: 0 });
}).toThrowErrorMatchingInlineSnapshot(`"newline config must be a positive number."`);
});
it('throws error when lineWidth negative number', () => {
expect(() => {
format('SELECT *', { newline: NewlineMode.lineWidth, lineWidth: -2 });
}).toThrowErrorMatchingInlineSnapshot(
`"lineWidth config must be positive number. Received -2 instead."`
);
});
it('throws error when lineWidth is zero', () => {
expect(() => {
format('SELECT *', { newline: NewlineMode.lineWidth, lineWidth: 0 });
}).toThrowErrorMatchingInlineSnapshot(
`"lineWidth config must be positive number. Received 0 instead."`
);
});
describe('newline: always', () => {
it('always splits to multiple lines, even when just a single clause', () => {
const result = format('SELECT foo, bar FROM qux;', {
newline: NewlineMode.always,
});
expect(result).toBe(dedent`
SELECT
foo,
bar
FROM
qux;
`);
});
});
describe('newline: never', () => {
it('never splits to multiple lines, regardless of count', () => {
const result = format('SELECT foo, bar, baz, qux FROM corge;', {
newline: NewlineMode.never,
});
expect(result).toBe(dedent`
SELECT foo, bar, baz, qux
FROM corge;
`);
});
});
describe('newline: number', () => {
it('splits to multiple lines when more clauses than than the specified number', () => {
const result = format('SELECT foo, bar, baz, qux FROM corge;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT
foo,
bar,
baz,
qux
FROM corge;
`);
});
it('does not split to multiple lines when the same number of clauses as specified number', () => {
const result = format('SELECT foo, bar, baz FROM corge;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT foo, bar, baz
FROM corge;
`);
});
it('does not split to multiple lines when less clauses than than the specified number', () => {
const result = format('SELECT foo, bar FROM corge;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT foo, bar
FROM corge;
`);
});
it('regardless of count, splits up long clauses (exceeding default lineWidth 50)', () => {
const result = format(
'SELECT customers.phone_number AS phone, customers.address AS addr FROM customers;',
{
newline: 3,
}
);
expect(result).toBe(dedent`
SELECT
customers.phone_number AS phone,
customers.address AS addr
FROM customers;
`);
});
it('does not smaller nr of clauses when their line width is exactly 50', () => {
const result = format('SELECT customer.phone phone, customer.addr AS addr FROM customers;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT customer.phone phone, customer.addr AS addr
FROM customers;
`);
});
it('splits up even short clauses when lineWidth is small', () => {
const result = format('SELECT foo, bar FROM customers GROUP BY foo, bar;', {
newline: 3,
lineWidth: 10,
});
expect(result).toBe(dedent`
SELECT
foo,
bar
FROM
customers
GROUP BY
foo,
bar;
`);
});
it('ignores commas inside parenthesis when counting clauses', () => {
const result = format('SELECT foo, some_function(a, b, c) AS bar FROM table1;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT foo, some_function(a, b, c) AS bar
FROM table1;
`);
});
});
describe('newline: lineWidth', () => {
it('splits to multiple lines when single line would exceed specified lineWidth', () => {
const result = format(
'SELECT first_field, second_field FROM some_excessively_long_table_name;',
{
newline: NewlineMode.lineWidth,
lineWidth: 20,
}
);
expect(result).toBe(dedent`
SELECT
first_field,
second_field
FROM
some_excessively_long_table_name;
`);
});
});
}
| test/features/newline.js | import dedent from 'dedent-js';
import { NewlineMode } from '../../src/types';
/**
* Tests support for all newline options
* @param {string} language
* @param {Function} format
*/
export default function supportsNewlineOptions(language, format) {
it('throws error when newline is negative number', () => {
expect(() => {
format('SELECT *', { newline: -1 });
}).toThrowErrorMatchingInlineSnapshot(`"newline config must be a positive number."`);
});
it('throws error when newline is zero', () => {
expect(() => {
format('SELECT *', { newline: 0 });
}).toThrowErrorMatchingInlineSnapshot(`"newline config must be a positive number."`);
});
it('throws error when lineWidth negative number', () => {
expect(() => {
format('SELECT *', { newline: NewlineMode.lineWidth, lineWidth: -2 });
}).toThrowErrorMatchingInlineSnapshot(
`"lineWidth config must be positive number. Received -2 instead."`
);
});
it('throws error when lineWidth is zero', () => {
expect(() => {
format('SELECT *', { newline: NewlineMode.lineWidth, lineWidth: 0 });
}).toThrowErrorMatchingInlineSnapshot(
`"lineWidth config must be positive number. Received 0 instead."`
);
});
describe('newline: always', () => {
it('always splits to multiple lines, even when just a single clause', () => {
const result = format('SELECT foo, bar FROM qux;', {
newline: NewlineMode.always,
});
expect(result).toBe(dedent`
SELECT
foo,
bar
FROM
qux;
`);
});
});
describe('newline: never', () => {
it('never splits to multiple lines, regardless of count', () => {
const result = format('SELECT foo, bar, baz, qux FROM corge;', {
newline: NewlineMode.never,
});
expect(result).toBe(dedent`
SELECT foo, bar, baz, qux
FROM corge;
`);
});
});
describe('newline: number', () => {
it('splits to multiple lines when more clauses than than the specified number', () => {
const result = format('SELECT foo, bar, baz, qux FROM corge;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT
foo,
bar,
baz,
qux
FROM corge;
`);
});
it('does not split to multiple lines when the same number of clauses as specified number', () => {
const result = format('SELECT foo, bar, baz FROM corge;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT foo, bar, baz
FROM corge;
`);
});
it('does not split to multiple lines when less clauses than than the specified number', () => {
const result = format('SELECT foo, bar FROM corge;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT foo, bar
FROM corge;
`);
});
it('regardless of count, splits up long clauses (exceeding default lineWidth 50)', () => {
const result = format(
'SELECT customers.phone_number AS phone, customers.address AS addr FROM customers;',
{
newline: 3,
}
);
expect(result).toBe(dedent`
SELECT
customers.phone_number AS phone,
customers.address AS addr
FROM customers;
`);
});
it('does not smaller nr of clauses when their line width is exactly 50', () => {
const result = format('SELECT customer.phone phone, customer.addr AS addr FROM customers;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT customer.phone phone, customer.addr AS addr
FROM customers;
`);
});
it('splits up even short clauses when lineWidth is small', () => {
const result = format('SELECT foo, bar FROM customers GROUP BY foo, bar;', {
newline: 3,
lineWidth: 10,
});
expect(result).toBe(dedent`
SELECT
foo,
bar
FROM
customers
GROUP BY
foo,
bar;
`);
});
it('ignores commas inside parenthesis when counting clauses', () => {
const result = format('SELECT foo, (SELECT a, b, c FROM table2) AS bar FROM table1;', {
newline: 3,
});
expect(result).toBe(dedent`
SELECT foo, (
SELECT a, b, c
FROM table2
) AS bar
FROM table1;
`);
});
});
describe('newline: lineWidth', () => {
it('splits to multiple lines when single line would exceed specified lineWidth', () => {
const result = format(
'SELECT first_field, second_field FROM some_excessively_long_table_name;',
{
newline: NewlineMode.lineWidth,
lineWidth: 20,
}
);
expect(result).toBe(dedent`
SELECT
first_field,
second_field
FROM
some_excessively_long_table_name;
`);
});
});
}
| Simplify test for comma-counting in parethesis
| test/features/newline.js | Simplify test for comma-counting in parethesis | <ide><path>est/features/newline.js
<ide> });
<ide>
<ide> it('ignores commas inside parenthesis when counting clauses', () => {
<del> const result = format('SELECT foo, (SELECT a, b, c FROM table2) AS bar FROM table1;', {
<add> const result = format('SELECT foo, some_function(a, b, c) AS bar FROM table1;', {
<ide> newline: 3,
<ide> });
<ide> expect(result).toBe(dedent`
<del> SELECT foo, (
<del> SELECT a, b, c
<del> FROM table2
<del> ) AS bar
<add> SELECT foo, some_function(a, b, c) AS bar
<ide> FROM table1;
<ide> `);
<ide> }); |
|
Java | apache-2.0 | afa93ff0f75e792414c1011493a4173aaed6d1ae | 0 | DBCG/cqf-ruler,DBCG/cql_measure_processor,DBCG/cql_measure_processor,DBCG/cqf-ruler,DBCG/cqf-ruler | package org.opencds.cqf.r4.providers;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import ca.uhn.fhir.jpa.dao.IFhirResourceDao;
import ca.uhn.fhir.rest.annotation.*;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.*;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.opencds.cqf.common.evaluation.EvaluationProviderFactory;
import org.opencds.cqf.common.providers.LibraryResolutionProvider;
import org.opencds.cqf.cql.engine.data.DataProvider;
import org.opencds.cqf.cql.engine.execution.LibraryLoader;
import org.opencds.cqf.library.r4.NarrativeProvider;
import org.opencds.cqf.measure.r4.CqfMeasure;
import org.opencds.cqf.r4.evaluation.MeasureEvaluation;
import org.opencds.cqf.r4.evaluation.MeasureEvaluationSeed;
import org.opencds.cqf.r4.helpers.LibraryHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.jpa.dao.DaoRegistry;
import ca.uhn.fhir.jpa.dao.IFhirSystemDao;
import ca.uhn.fhir.jpa.rp.r4.MeasureResourceProvider;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
public class MeasureOperationsProvider {
private NarrativeProvider narrativeProvider;
private HQMFProvider hqmfProvider;
private DataRequirementsProvider dataRequirementsProvider;
private LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider;
private MeasureResourceProvider measureResourceProvider;
private DaoRegistry registry;
private EvaluationProviderFactory factory;
private static final Logger logger = LoggerFactory.getLogger(MeasureOperationsProvider.class);
public MeasureOperationsProvider(DaoRegistry registry, EvaluationProviderFactory factory,
NarrativeProvider narrativeProvider, HQMFProvider hqmfProvider,
LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider,
MeasureResourceProvider measureResourceProvider) {
this.registry = registry;
this.factory = factory;
this.libraryResolutionProvider = libraryResolutionProvider;
this.narrativeProvider = narrativeProvider;
this.hqmfProvider = hqmfProvider;
this.dataRequirementsProvider = new DataRequirementsProvider();
this.measureResourceProvider = measureResourceProvider;
}
@Operation(name = "$hqmf", idempotent = true, type = Measure.class)
public Parameters hqmf(@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
String hqmf = this.generateHQMF(theResource);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(hqmf));
return p;
}
@Operation(name = "$refresh-generated-content", type = Measure.class)
public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails,
@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
theResource.getRelatedArtifact().removeIf(
relatedArtifact -> relatedArtifact.getType().equals(RelatedArtifact.RelatedArtifactType.DEPENDSON));
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource,
this.libraryResolutionProvider);
// Ensure All Related Artifacts for all referenced Libraries
if (!cqfMeasure.getRelatedArtifact().isEmpty()) {
for (RelatedArtifact relatedArtifact : cqfMeasure.getRelatedArtifact()) {
boolean artifactExists = false;
// logger.info("Related Artifact: " + relatedArtifact.getUrl());
for (RelatedArtifact resourceArtifact : theResource.getRelatedArtifact()) {
if (resourceArtifact.equalsDeep(relatedArtifact)) {
// logger.info("Equals deep true");
artifactExists = true;
break;
}
}
if (!artifactExists) {
theResource.addRelatedArtifact(relatedArtifact.copy());
}
}
}
try {
Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
theResource.setText(n.copy());
} catch (Exception e) {
logger.info("Error generating narrative", e);
}
return this.measureResourceProvider.update(theRequest, theResource, theId,
theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
}
@Operation(name = "$get-narrative", idempotent = true, type = Measure.class)
public Parameters getNarrative(@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource,
this.libraryResolutionProvider);
Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(n.getDivAsString()));
return p;
}
private String generateHQMF(Measure theResource) {
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource,
this.libraryResolutionProvider);
return this.hqmfProvider.generateHQMF(cqfMeasure);
}
/*
*
* NOTE that the source, user, and pass parameters are not standard parameters
* for the FHIR $evaluate-measure operation
*
*/
@Operation(name = "$evaluate-measure", idempotent = true, type = Measure.class)
public MeasureReport evaluateMeasure(@IdParam IdType theId,
@OperationParam(name = "periodStart") String periodStart,
@OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "measure") String measureRef,
@OperationParam(name = "reportType") String reportType, @OperationParam(name = "patient") String patientRef,
@OperationParam(name = "productLine") String productLine,
@OperationParam(name = "practitioner") String practitionerRef,
@OperationParam(name = "lastReceivedOn") String lastReceivedOn,
@OperationParam(name = "source") String source, @OperationParam(name = "user") String user,
@OperationParam(name = "pass") String pass) throws InternalErrorException, FHIRException {
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader,
this.libraryResolutionProvider);
Measure measure = this.measureResourceProvider.getDao().read(theId);
if (measure == null) {
throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
}
seed.setup(measure, periodStart, periodEnd, productLine, source, user, pass);
// resolve report type
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry,
seed.getMeasurementPeriod());
if (reportType != null) {
switch (reportType) {
case "patient":
return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
case "patient-list":
return evaluator.evaluateSubjectListMeasure(seed.getMeasure(), seed.getContext(), practitionerRef);
case "population":
return evaluator.evaluatePopulationMeasure(seed.getMeasure(), seed.getContext());
default:
throw new IllegalArgumentException("Invalid report type: " + reportType);
}
}
// default report type is patient
MeasureReport report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
if (productLine != null) {
Extension ext = new Extension();
ext.setUrl("http://hl7.org/fhir/us/cqframework/cqfmeasures/StructureDefinition/cqfm-productLine");
ext.setValue(new StringType(productLine));
report.addExtension(ext);
}
return report;
}
// @Operation(name = "$evaluate-measure-with-source", idempotent = true)
// public MeasureReport evaluateMeasure(@IdParam IdType theId,
// @OperationParam(name = "sourceData", min = 1, max = 1, type = Bundle.class)
// Bundle sourceData,
// @OperationParam(name = "periodStart", min = 1, max = 1) String periodStart,
// @OperationParam(name = "periodEnd", min = 1, max = 1) String periodEnd) {
// if (periodStart == null || periodEnd == null) {
// throw new IllegalArgumentException("periodStart and periodEnd are required
// for measure evaluation");
// }
// LibraryLoader libraryLoader =
// LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
// MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory,
// libraryLoader, this.libraryResourceProvider);
// Measure measure = this.getDao().read(theId);
// if (measure == null) {
// throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
// }
// seed.setup(measure, periodStart, periodEnd, null, null, null, null);
// BundleDataProviderStu3 bundleProvider = new
// BundleDataProviderStu3(sourceData);
// bundleProvider.setTerminologyProvider(provider.getTerminologyProvider());
// seed.getContext().registerDataProvider("http://hl7.org/fhir",
// bundleProvider);
// MeasureEvaluation evaluator = new MeasureEvaluation(bundleProvider,
// seed.getMeasurementPeriod());
// return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(),
// "");
// }
@Operation(name = "$care-gaps", idempotent = true, type = Measure.class)
public Parameters careGapsReport(@OperationParam(name = "periodStart") String periodStart,
@OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "subject") String subject,
@OperationParam(name = "topic") String topic,@OperationParam(name = "practitioner") String practitioner,
@OperationParam(name = "measure") String measure, @OperationParam(name="status")String status,
@OperationParam(name = "organization") String organization){
//TODO: status - optional if null all gaps - if closed-gap code only those gaps that are closed if open-gap code only those that are open
//TODO: topic should allow many and be a union of them
//TODO: "The Server needs to make sure that practitioner is authorized to get the gaps in care report for and know what measures the practitioner are eligible or qualified."
Parameters returnParams = new Parameters();
if(careGapParameterValidation(periodStart, periodEnd, subject, topic, practitioner, measure, status, organization)) {
if(subject.startsWith("Patient/")){
returnParams.addParameter(new Parameters.ParametersParameterComponent()
.setName("return")
.setResource(patientCareGap(periodStart, periodEnd, subject, topic, measure, status)));
return returnParams;
}else if(subject.startsWith("Group/")) {
returnParams.setId((status==null?"all-gaps": status) + "-" + subject.replace("/","_") + "-report");
(getPatientListFromGroup(subject))
.forEach(groupSubject ->{
Bundle patientGapBundle = patientCareGap(periodStart, periodEnd, groupSubject, topic, measure, status);
if(null != patientGapBundle){
returnParams.addParameter(new Parameters.ParametersParameterComponent()
.setName("return")
.setResource(patientGapBundle));
}
});
}
return returnParams;
}
if (practitioner == null || practitioner.equals("")) {
return new Parameters().addParameter(
new Parameters.ParametersParameterComponent()
.setName("Gaps in Care Report - " + subject)
.setResource(patientCareGap(periodStart, periodEnd, subject, topic, measure,status)));
}
return returnParams;
}
private List<String> getPatientListFromGroup(String subjectGroupRef){
List<String> patientList = new ArrayList<>();
DataProvider dataProvider = this.factory.createDataProvider("FHIR", "4");
Iterable<Object> groupRetrieve = dataProvider.retrieve("Group", "id", subjectGroupRef, "Group", null, null, null,
null, null, null, null, null);
Group group;
Iterator<Object> objIterator = groupRetrieve.iterator();
if (objIterator.hasNext()) {
while(objIterator.hasNext()) {
group = (Group) objIterator.next();
if (group.getIdElement().getIdPart().equalsIgnoreCase(subjectGroupRef.substring(subjectGroupRef.lastIndexOf("/") + 1)) ) {
group.getMember().forEach(member -> patientList.add(member.getEntity().getReference()));
}
}
}
return patientList;
}
private Boolean careGapParameterValidation(String periodStart, String periodEnd, String subject, String topic,
String practitioner, String measure, String status, String organization){
if(periodStart == null || periodStart.equals("") ||
periodEnd == null || periodEnd.equals("")){
throw new IllegalArgumentException("periodStart and periodEnd are required.");
}
//TODO - remove this - covered in check of subject/practitioner/organization - left in for now 'cause we need a subject to develop
if (subject == null || subject.equals("")) {
throw new IllegalArgumentException("Subject is required.");
}
if(null != subject) {
if (!subject.startsWith("Patient/") && !subject.startsWith("Group/")) {
throw new IllegalArgumentException("Subject must follow the format of either 'Patient/ID' OR 'Group/ID'.");
}
}
if(null != status && (!status.equalsIgnoreCase("open-gap") && !status.equalsIgnoreCase("closed-gap"))){
throw new IllegalArgumentException("If status is present, it must be either 'open-gap' or 'closed-gap'.");
}
if(null != practitioner && null == organization){
throw new IllegalArgumentException("If a practitioner is specified then an organization must also be specified.");
}
if(null == subject && null == practitioner && null == organization){
throw new IllegalArgumentException("periodStart AND periodEnd AND (subject OR organization OR (practitioner AND organization)) MUST be provided");
}
return true;
}
private Bundle patientCareGap(String periodStart, String periodEnd, String subject, String topic, String measure, String status) {
//TODO: this is an org hack. Need to figure out what the right thing is.
IFhirResourceDao<Organization> orgDao = this.registry.getResourceDao(Organization.class);
List<IBaseResource> org = orgDao.search(new SearchParameterMap()).getResources(0, 1);
SearchParameterMap theParams = new SearchParameterMap();
// if (theId != null) {
// var measureParam = new StringParam(theId.getIdPart());
// theParams.add("_id", measureParam);
// }
if (topic != null && !topic.equals("")) {
TokenParam topicParam = new TokenParam(topic);
theParams.add("topic", topicParam);
}
List<IBaseResource> measures = getMeasureList(theParams, measure);
Bundle careGapReport = new Bundle();
careGapReport.setType(Bundle.BundleType.DOCUMENT);
careGapReport.setTimestamp(new Date());
Composition composition = new Composition();
composition.setStatus(Composition.CompositionStatus.FINAL)
.setSubject(new Reference(subject.startsWith("Patient/") ? subject : "Patient/" + subject))
.setTitle("Care Gap Report for " + subject)
.setDate(new Date())
.setType(new CodeableConcept()
.addCoding(new Coding()
.setCode("gaps-doc")
.setSystem("http://hl7.org/fhir/us/davinci-deqm/CodeSystem/gaps-doc-type")
.setDisplay("Gaps in Care Report")));
List<MeasureReport> reports = new ArrayList<>();
List<DetectedIssue> detectedIssues = new ArrayList<DetectedIssue>();
MeasureReport report = null;
for (IBaseResource resource : measures) {
Measure measureResource = (Measure) resource;
Composition.SectionComponent section = new Composition.SectionComponent();
if (measureResource.hasTitle()) {
section.setTitle(measureResource.getTitle());
}
// TODO - this is configured for patient-level evaluation only
report = evaluateMeasure(measureResource.getIdElement(), periodStart, periodEnd, null, "patient", subject, null,
null, null, null, null, null);
report.setId(UUID.randomUUID().toString());
report.setDate(new Date());
report.setImprovementNotation(measureResource.getImprovementNotation());
//TODO: this is an org hack && requires an Organization to be in the ruler
if (org != null && org.size() > 0) {
report.setReporter(new Reference("Organization/" + org.get(0).getIdElement().getIdPart()));
}
report.setMeta(new Meta().addProfile("http://hl7.org/fhir/us/davinci-deqm/StructureDefinition/indv-measurereport-deqm"));
section.setFocus(new Reference("MeasureReport/" + report.getId()));
//TODO: DetectedIssue
//section.addEntry(new Reference("MeasureReport/" + report.getId()));
if (report.hasGroup() && measureResource.hasScoring()) {
int numerator = 0;
int denominator = 0;
for (MeasureReport.MeasureReportGroupComponent group : report.getGroup()) {
if (group.hasPopulation()) {
for (MeasureReport.MeasureReportGroupPopulationComponent population : group.getPopulation()) {
// TODO - currently configured for measures with only 1 numerator and 1
// denominator
if (population.hasCode()) {
if (population.getCode().hasCoding()) {
for (Coding coding : population.getCode().getCoding()) {
if (coding.hasCode()) {
if (coding.getCode().equals("numerator") && population.hasCount()) {
numerator = population.getCount();
} else if (coding.getCode().equals("denominator")
&& population.hasCount()) {
denominator = population.getCount();
}
}
}
}
}
}
}
}
//TODO: implement this per the spec
//Holding off on implementiation using Measure Score pending guidance re consideration for programs that don't perform the calculation (they just use numer/denom)
double proportion = 0.0;
if (measureResource.getScoring().hasCoding() && denominator != 0) {
for (Coding coding : measureResource.getScoring().getCoding()) {
if (coding.hasCode() && coding.getCode().equals("proportion")) {
if (denominator != 0.0 ) {
proportion = numerator / denominator;
}
}
}
}
// TODO - this is super hacky ... change once improvementNotation is specified
// as a code
String improvementNotation = measureResource.getImprovementNotation().getCodingFirstRep().getCode().toLowerCase();
if (((improvementNotation.equals("increase")) && (proportion < 1.0))
|| ((improvementNotation.equals("decrease")) && (proportion > 0.0))) {
if (status != null && status.equalsIgnoreCase("closed-gap")) {
continue;
}
DetectedIssue detectedIssue = new DetectedIssue();
detectedIssue.setId(UUID.randomUUID().toString());
detectedIssue.setStatus(DetectedIssue.DetectedIssueStatus.FINAL);
detectedIssue.setPatient(new Reference(subject.startsWith("Patient/") ? subject : "Patient/" + subject));
detectedIssue.getEvidence().add(new DetectedIssue.DetectedIssueEvidenceComponent().addDetail(new Reference("MeasureReport/" + report.getId())));
CodeableConcept code = new CodeableConcept()
.addCoding(new Coding()
.setSystem("http://hl7.org/fhir/us/davinci-deqm/CodeSystem/detectedissue-category")
.setCode("care-gap")
.setDisplay("Gap in Care Detected"));
detectedIssue.setCode(code);
section.addEntry(
new Reference("DetectedIssue/" + detectedIssue.getIdElement().getIdPart()));
detectedIssues.add(detectedIssue);
}else {
if (status != null && status.equalsIgnoreCase("open-gap")) {
continue;
}
section.setText(new Narrative()
.setStatus(Narrative.NarrativeStatus.GENERATED)
.setDiv(new XhtmlNode().setValue("<div xmlns=\"http://www.w3.org/1999/xhtml\"><p>No detected issues.</p></div>")));
}
composition.addSection(section);
reports.add(report);
// TODO - add other types of improvement notation cases
}
}
Parameters parameters = new Parameters();
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(composition));
for (MeasureReport rep : reports) {
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(rep));
if (report.hasContained()) {
for (Resource contained : report.getContained()) {
if (contained instanceof Bundle) {
addEvaluatedResourcesToParameters((Bundle) contained, parameters);
if(null != parameters && !parameters.isEmpty()) {
List <Reference> evaluatedResource = new ArrayList<>();
parameters.getParameter().forEach(parameter -> {
Reference newEvaluatedResourceItem = new Reference();
newEvaluatedResourceItem.setReference(parameter.getResource().getId());
List<Extension> evalResourceExt = new ArrayList<>();
evalResourceExt.add(new Extension("http://hl7.org/fhir/us/davinci-deqm/StructureDefinition/extension-populationReference",
new CodeableConcept()
.addCoding(new Coding("http://teminology.hl7.org/CodeSystem/measure-population", "initial-population", "initial-population"))));
newEvaluatedResourceItem.setExtension(evalResourceExt);
evaluatedResource.add(newEvaluatedResourceItem);
});
report.setEvaluatedResource(evaluatedResource);
}
}
}
}
}
for (DetectedIssue detectedIssue : detectedIssues) {
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(detectedIssue));
}
if(careGapReport.getEntry().isEmpty()){
return null;
}
return careGapReport;
}
private List<IBaseResource> getMeasureList(SearchParameterMap theParams, String measure){
List<IBaseResource> finalMeasureList = new ArrayList<>();
for(String theId: measure.split(",")){
if (theId.equals("")) {
continue;
}
Measure measureResource = this.measureResourceProvider.getDao().read(new IdType(theId.trim()));
if (measureResource != null) {
finalMeasureList.add(measureResource);
}
}
return finalMeasureList;
}
@Operation(name = "$collect-data", idempotent = true, type = Measure.class)
public Parameters collectData(@IdParam IdType theId, @OperationParam(name = "periodStart") String periodStart,
@OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "patient") String patientRef,
@OperationParam(name = "practitioner") String practitionerRef,
@OperationParam(name = "lastReceivedOn") String lastReceivedOn) throws FHIRException {
// TODO: Spec says that the periods are not required, but I am not sure what to
// do when they aren't supplied so I made them required
MeasureReport report = evaluateMeasure(theId, periodStart, periodEnd, null, null, patientRef, null,
practitionerRef, lastReceivedOn, null, null, null);
report.setGroup(null);
Parameters parameters = new Parameters();
parameters.addParameter(
new Parameters.ParametersParameterComponent().setName("measurereport").setResource(report));
if (report.hasContained()) {
for (Resource contained : report.getContained()) {
if (contained instanceof Bundle) {
addEvaluatedResourcesToParameters((Bundle) contained, parameters);
}
}
}
// TODO: need a way to resolve referenced resources within the evaluated
// resources
// Should be able to use _include search with * wildcard, but HAPI doesn't
// support that
return parameters;
}
private void addEvaluatedResourcesToParameters(Bundle contained, Parameters parameters) {
Map<String, Resource> resourceMap = new HashMap<>();
if (contained.hasEntry()) {
for (Bundle.BundleEntryComponent entry : contained.getEntry()) {
if (entry.hasResource() && !(entry.getResource() instanceof ListResource)) {
if (!resourceMap.containsKey(entry.getResource().getIdElement().getValue())) {
parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
.setResource(entry.getResource()));
resourceMap.put(entry.getResource().getIdElement().getValue(), entry.getResource());
resolveReferences(entry.getResource(), parameters, resourceMap);
}
}
}
}
}
private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap) {
List<IBase> values;
for (BaseRuntimeChildDefinition child : this.measureResourceProvider.getContext()
.getResourceDefinition(resource).getChildren()) {
values = child.getAccessor().getValues(resource);
if (values == null || values.isEmpty()) {
continue;
}
else if (values.get(0) instanceof Reference
&& ((Reference) values.get(0)).getReferenceElement().hasResourceType()
&& ((Reference) values.get(0)).getReferenceElement().hasIdPart()) {
Resource fetchedResource = (Resource) registry
.getResourceDao(((Reference) values.get(0)).getReferenceElement().getResourceType())
.read(new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart()));
if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue())) {
parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
.setResource(fetchedResource));
resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource);
}
}
}
}
// TODO - this needs a lot of work
@Operation(name = "$data-requirements", idempotent = true, type = Measure.class)
public org.hl7.fhir.r4.model.Library dataRequirements(@IdParam IdType theId,
@OperationParam(name = "startPeriod") String startPeriod,
@OperationParam(name = "endPeriod") String endPeriod) throws InternalErrorException, FHIRException {
Measure measure = this.measureResourceProvider.getDao().read(theId);
return this.dataRequirementsProvider.getDataRequirements(measure, this.libraryResolutionProvider);
}
@SuppressWarnings("unchecked")
@Operation(name = "$submit-data", idempotent = true, type = Measure.class)
public Resource submitData(RequestDetails details, @IdParam IdType theId,
@OperationParam(name = "measurereport", min = 1, max = 1, type = MeasureReport.class) MeasureReport report,
@OperationParam(name = "resource") List<IAnyResource> resources) {
Bundle transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
/*
* TODO - resource validation using $data-requirements operation (params are the
* provided id and the measurement period from the MeasureReport)
*
* TODO - profile validation ... not sure how that would work ... (get
* StructureDefinition from URL or must it be stored in Ruler?)
*/
transactionBundle.addEntry(createTransactionEntry(report));
for (IAnyResource resource : resources) {
Resource res = (Resource) resource;
if (res instanceof Bundle) {
for (Bundle.BundleEntryComponent entry : createTransactionBundle((Bundle) res).getEntry()) {
transactionBundle.addEntry(entry);
}
} else {
// Build transaction bundle
transactionBundle.addEntry(createTransactionEntry(res));
}
}
return (Resource) ((IFhirSystemDao<Bundle,?>)this.registry.getSystemDao()).transaction(details, transactionBundle);
}
private Bundle createTransactionBundle(Bundle bundle) {
Bundle transactionBundle;
if (bundle != null) {
if (bundle.hasType() && bundle.getType() == Bundle.BundleType.TRANSACTION) {
transactionBundle = bundle;
} else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
if (bundle.hasEntry()) {
for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
if (entry.hasResource()) {
transactionBundle.addEntry(createTransactionEntry(entry.getResource()));
}
}
}
}
} else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION).setEntry(new ArrayList<>());
}
return transactionBundle;
}
private Bundle.BundleEntryComponent createTransactionEntry(Resource resource) {
Bundle.BundleEntryComponent transactionEntry = new Bundle.BundleEntryComponent().setResource(resource);
if (resource.hasId()) {
transactionEntry.setRequest(
new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.PUT).setUrl(resource.getId()));
} else {
transactionEntry.setRequest(new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.POST)
.setUrl(resource.fhirType()));
}
return transactionEntry;
}
}
| r4/src/main/java/org/opencds/cqf/r4/providers/MeasureOperationsProvider.java | package org.opencds.cqf.r4.providers;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import ca.uhn.fhir.jpa.dao.IFhirResourceDao;
import ca.uhn.fhir.rest.annotation.*;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.*;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.opencds.cqf.common.evaluation.EvaluationProviderFactory;
import org.opencds.cqf.common.providers.LibraryResolutionProvider;
import org.opencds.cqf.cql.engine.data.DataProvider;
import org.opencds.cqf.cql.engine.execution.LibraryLoader;
import org.opencds.cqf.library.r4.NarrativeProvider;
import org.opencds.cqf.measure.r4.CqfMeasure;
import org.opencds.cqf.r4.evaluation.MeasureEvaluation;
import org.opencds.cqf.r4.evaluation.MeasureEvaluationSeed;
import org.opencds.cqf.r4.helpers.LibraryHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.jpa.dao.DaoRegistry;
import ca.uhn.fhir.jpa.dao.IFhirSystemDao;
import ca.uhn.fhir.jpa.rp.r4.MeasureResourceProvider;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
public class MeasureOperationsProvider {
private NarrativeProvider narrativeProvider;
private HQMFProvider hqmfProvider;
private DataRequirementsProvider dataRequirementsProvider;
private LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider;
private MeasureResourceProvider measureResourceProvider;
private DaoRegistry registry;
private EvaluationProviderFactory factory;
private static final Logger logger = LoggerFactory.getLogger(MeasureOperationsProvider.class);
public MeasureOperationsProvider(DaoRegistry registry, EvaluationProviderFactory factory,
NarrativeProvider narrativeProvider, HQMFProvider hqmfProvider,
LibraryResolutionProvider<org.hl7.fhir.r4.model.Library> libraryResolutionProvider,
MeasureResourceProvider measureResourceProvider) {
this.registry = registry;
this.factory = factory;
this.libraryResolutionProvider = libraryResolutionProvider;
this.narrativeProvider = narrativeProvider;
this.hqmfProvider = hqmfProvider;
this.dataRequirementsProvider = new DataRequirementsProvider();
this.measureResourceProvider = measureResourceProvider;
}
@Operation(name = "$hqmf", idempotent = true, type = Measure.class)
public Parameters hqmf(@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
String hqmf = this.generateHQMF(theResource);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(hqmf));
return p;
}
@Operation(name = "$refresh-generated-content", type = Measure.class)
public MethodOutcome refreshGeneratedContent(HttpServletRequest theRequest, RequestDetails theRequestDetails,
@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
theResource.getRelatedArtifact().removeIf(
relatedArtifact -> relatedArtifact.getType().equals(RelatedArtifact.RelatedArtifactType.DEPENDSON));
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource,
this.libraryResolutionProvider);
// Ensure All Related Artifacts for all referenced Libraries
if (!cqfMeasure.getRelatedArtifact().isEmpty()) {
for (RelatedArtifact relatedArtifact : cqfMeasure.getRelatedArtifact()) {
boolean artifactExists = false;
// logger.info("Related Artifact: " + relatedArtifact.getUrl());
for (RelatedArtifact resourceArtifact : theResource.getRelatedArtifact()) {
if (resourceArtifact.equalsDeep(relatedArtifact)) {
// logger.info("Equals deep true");
artifactExists = true;
break;
}
}
if (!artifactExists) {
theResource.addRelatedArtifact(relatedArtifact.copy());
}
}
}
try {
Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
theResource.setText(n.copy());
} catch (Exception e) {
logger.info("Error generating narrative", e);
}
return this.measureResourceProvider.update(theRequest, theResource, theId,
theRequestDetails.getConditionalUrl(RestOperationTypeEnum.UPDATE), theRequestDetails);
}
@Operation(name = "$get-narrative", idempotent = true, type = Measure.class)
public Parameters getNarrative(@IdParam IdType theId) {
Measure theResource = this.measureResourceProvider.getDao().read(theId);
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource,
this.libraryResolutionProvider);
Narrative n = this.narrativeProvider.getNarrative(this.measureResourceProvider.getContext(), cqfMeasure);
Parameters p = new Parameters();
p.addParameter().setValue(new StringType(n.getDivAsString()));
return p;
}
private String generateHQMF(Measure theResource) {
CqfMeasure cqfMeasure = this.dataRequirementsProvider.createCqfMeasure(theResource,
this.libraryResolutionProvider);
return this.hqmfProvider.generateHQMF(cqfMeasure);
}
/*
*
* NOTE that the source, user, and pass parameters are not standard parameters
* for the FHIR $evaluate-measure operation
*
*/
@Operation(name = "$evaluate-measure", idempotent = true, type = Measure.class)
public MeasureReport evaluateMeasure(@IdParam IdType theId,
@OperationParam(name = "periodStart") String periodStart,
@OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "measure") String measureRef,
@OperationParam(name = "reportType") String reportType, @OperationParam(name = "patient") String patientRef,
@OperationParam(name = "productLine") String productLine,
@OperationParam(name = "practitioner") String practitionerRef,
@OperationParam(name = "lastReceivedOn") String lastReceivedOn,
@OperationParam(name = "source") String source, @OperationParam(name = "user") String user,
@OperationParam(name = "pass") String pass) throws InternalErrorException, FHIRException {
LibraryLoader libraryLoader = LibraryHelper.createLibraryLoader(this.libraryResolutionProvider);
MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory, libraryLoader,
this.libraryResolutionProvider);
Measure measure = this.measureResourceProvider.getDao().read(theId);
if (measure == null) {
throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
}
seed.setup(measure, periodStart, periodEnd, productLine, source, user, pass);
// resolve report type
MeasureEvaluation evaluator = new MeasureEvaluation(seed.getDataProvider(), this.registry,
seed.getMeasurementPeriod());
if (reportType != null) {
switch (reportType) {
case "patient":
return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
case "patient-list":
return evaluator.evaluateSubjectListMeasure(seed.getMeasure(), seed.getContext(), practitionerRef);
case "population":
return evaluator.evaluatePopulationMeasure(seed.getMeasure(), seed.getContext());
default:
throw new IllegalArgumentException("Invalid report type: " + reportType);
}
}
// default report type is patient
MeasureReport report = evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(), patientRef);
if (productLine != null) {
Extension ext = new Extension();
ext.setUrl("http://hl7.org/fhir/us/cqframework/cqfmeasures/StructureDefinition/cqfm-productLine");
ext.setValue(new StringType(productLine));
report.addExtension(ext);
}
return report;
}
// @Operation(name = "$evaluate-measure-with-source", idempotent = true)
// public MeasureReport evaluateMeasure(@IdParam IdType theId,
// @OperationParam(name = "sourceData", min = 1, max = 1, type = Bundle.class)
// Bundle sourceData,
// @OperationParam(name = "periodStart", min = 1, max = 1) String periodStart,
// @OperationParam(name = "periodEnd", min = 1, max = 1) String periodEnd) {
// if (periodStart == null || periodEnd == null) {
// throw new IllegalArgumentException("periodStart and periodEnd are required
// for measure evaluation");
// }
// LibraryLoader libraryLoader =
// LibraryHelper.createLibraryLoader(this.libraryResourceProvider);
// MeasureEvaluationSeed seed = new MeasureEvaluationSeed(this.factory,
// libraryLoader, this.libraryResourceProvider);
// Measure measure = this.getDao().read(theId);
// if (measure == null) {
// throw new RuntimeException("Could not find Measure/" + theId.getIdPart());
// }
// seed.setup(measure, periodStart, periodEnd, null, null, null, null);
// BundleDataProviderStu3 bundleProvider = new
// BundleDataProviderStu3(sourceData);
// bundleProvider.setTerminologyProvider(provider.getTerminologyProvider());
// seed.getContext().registerDataProvider("http://hl7.org/fhir",
// bundleProvider);
// MeasureEvaluation evaluator = new MeasureEvaluation(bundleProvider,
// seed.getMeasurementPeriod());
// return evaluator.evaluatePatientMeasure(seed.getMeasure(), seed.getContext(),
// "");
// }
@Operation(name = "$care-gaps", idempotent = true, type = Measure.class)
public Parameters careGapsReport(@OperationParam(name = "periodStart") String periodStart,
@OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "subject") String subject,
@OperationParam(name = "topic") String topic,@OperationParam(name = "practitioner") String practitioner,
@OperationParam(name = "measure") String measure, @OperationParam(name="status")String status,
@OperationParam(name = "organization") String organization){
//TODO: status - optional if null all gaps - if closed-gap code only those gaps that are closed if open-gap code only those that are open
//TODO: topic should allow many and be a union of them
//TODO: "The Server needs to make sure that practitioner is authorized to get the gaps in care report for and know what measures the practitioner are eligible or qualified."
Parameters returnParams = new Parameters();
if(careGapParameterValidation(periodStart, periodEnd, subject, topic, practitioner, measure, status, organization)) {
if(subject.startsWith("Patient/")){
returnParams.addParameter(new Parameters.ParametersParameterComponent()
.setName("result")
.setResource(patientCareGap(periodStart, periodEnd, subject, topic, measure, status)));
return returnParams;
}else if(subject.startsWith("Group/")) {
returnParams.setId((status==null?"all-gaps": status) + "-" + subject.replace("/","_") + "-report");
(getPatientListFromGroup(subject))
.forEach(groupSubject ->{
Bundle patientGapBundle = patientCareGap(periodStart, periodEnd, groupSubject, topic, measure, status);
if(null != patientGapBundle){
returnParams.addParameter(new Parameters.ParametersParameterComponent()
.setName("result")
.setResource(patientGapBundle));
}
});
}
return returnParams;
}
if (practitioner == null || practitioner.equals("")) {
return new Parameters().addParameter(
new Parameters.ParametersParameterComponent()
.setName("Gaps in Care Report - " + subject)
.setResource(patientCareGap(periodStart, periodEnd, subject, topic, measure,status)));
}
return returnParams;
}
private List<String> getPatientListFromGroup(String subjectGroupRef){
List<String> patientList = new ArrayList<>();
DataProvider dataProvider = this.factory.createDataProvider("FHIR", "4");
Iterable<Object> groupRetrieve = dataProvider.retrieve("Group", "id", subjectGroupRef, "Group", null, null, null,
null, null, null, null, null);
Group group;
Iterator<Object> objIterator = groupRetrieve.iterator();
if (objIterator.hasNext()) {
while(objIterator.hasNext()) {
group = (Group) objIterator.next();
if (group.getIdElement().getIdPart().equalsIgnoreCase(subjectGroupRef.substring(subjectGroupRef.lastIndexOf("/") + 1)) ) {
group.getMember().forEach(member -> patientList.add(member.getEntity().getReference()));
}
}
}
return patientList;
}
private Boolean careGapParameterValidation(String periodStart, String periodEnd, String subject, String topic,
String practitioner, String measure, String status, String organization){
if(periodStart == null || periodStart.equals("") ||
periodEnd == null || periodEnd.equals("")){
throw new IllegalArgumentException("periodStart and periodEnd are required.");
}
//TODO - remove this - covered in check of subject/practitioner/organization - left in for now 'cause we need a subject to develop
if (subject == null || subject.equals("")) {
throw new IllegalArgumentException("Subject is required.");
}
if(null != subject) {
if (!subject.startsWith("Patient/") && !subject.startsWith("Group/")) {
throw new IllegalArgumentException("Subject must follow the format of either 'Patient/ID' OR 'Group/ID'.");
}
}
if(null != status && (!status.equalsIgnoreCase("open-gap") && !status.equalsIgnoreCase("closed-gap"))){
throw new IllegalArgumentException("If status is present, it must be either 'open-gap' or 'closed-gap'.");
}
if(null != practitioner && null == organization){
throw new IllegalArgumentException("If a practitioner is specified then an organization must also be specified.");
}
if(null == subject && null == practitioner && null == organization){
throw new IllegalArgumentException("periodStart AND periodEnd AND (subject OR organization OR (practitioner AND organization)) MUST be provided");
}
return true;
}
private Bundle patientCareGap(String periodStart, String periodEnd, String subject, String topic, String measure, String status) {
//TODO: this is an org hack. Need to figure out what the right thing is.
IFhirResourceDao<Organization> orgDao = this.registry.getResourceDao(Organization.class);
List<IBaseResource> org = orgDao.search(new SearchParameterMap()).getResources(0, 1);
SearchParameterMap theParams = new SearchParameterMap();
// if (theId != null) {
// var measureParam = new StringParam(theId.getIdPart());
// theParams.add("_id", measureParam);
// }
if (topic != null && !topic.equals("")) {
TokenParam topicParam = new TokenParam(topic);
theParams.add("topic", topicParam);
}
List<IBaseResource> measures = getMeasureList(theParams, measure);
Bundle careGapReport = new Bundle();
careGapReport.setType(Bundle.BundleType.DOCUMENT);
careGapReport.setTimestamp(new Date());
Composition composition = new Composition();
composition.setStatus(Composition.CompositionStatus.FINAL)
.setSubject(new Reference(subject.startsWith("Patient/") ? subject : "Patient/" + subject))
.setTitle("Care Gap Report for " + subject)
.setDate(new Date())
.setType(new CodeableConcept()
.addCoding(new Coding()
.setCode("gaps-doc")
.setSystem("http://hl7.org/fhir/us/davinci-deqm/CodeSystem/gaps-doc-type")
.setDisplay("Gaps in Care Report")));
List<MeasureReport> reports = new ArrayList<>();
List<DetectedIssue> detectedIssues = new ArrayList<DetectedIssue>();
MeasureReport report = null;
for (IBaseResource resource : measures) {
Measure measureResource = (Measure) resource;
Composition.SectionComponent section = new Composition.SectionComponent();
if (measureResource.hasTitle()) {
section.setTitle(measureResource.getTitle());
}
// TODO - this is configured for patient-level evaluation only
report = evaluateMeasure(measureResource.getIdElement(), periodStart, periodEnd, null, "patient", subject, null,
null, null, null, null, null);
report.setId(UUID.randomUUID().toString());
report.setDate(new Date());
report.setImprovementNotation(measureResource.getImprovementNotation());
//TODO: this is an org hack && requires an Organization to be in the ruler
if (org != null && org.size() > 0) {
report.setReporter(new Reference("Organization/" + org.get(0).getIdElement().getIdPart()));
}
report.setMeta(new Meta().addProfile("http://hl7.org/fhir/us/davinci-deqm/StructureDefinition/indv-measurereport-deqm"));
section.setFocus(new Reference("MeasureReport/" + report.getId()));
//TODO: DetectedIssue
//section.addEntry(new Reference("MeasureReport/" + report.getId()));
if (report.hasGroup() && measureResource.hasScoring()) {
int numerator = 0;
int denominator = 0;
for (MeasureReport.MeasureReportGroupComponent group : report.getGroup()) {
if (group.hasPopulation()) {
for (MeasureReport.MeasureReportGroupPopulationComponent population : group.getPopulation()) {
// TODO - currently configured for measures with only 1 numerator and 1
// denominator
if (population.hasCode()) {
if (population.getCode().hasCoding()) {
for (Coding coding : population.getCode().getCoding()) {
if (coding.hasCode()) {
if (coding.getCode().equals("numerator") && population.hasCount()) {
numerator = population.getCount();
} else if (coding.getCode().equals("denominator")
&& population.hasCount()) {
denominator = population.getCount();
}
}
}
}
}
}
}
}
//TODO: implement this per the spec
//Holding off on implementiation using Measure Score pending guidance re consideration for programs that don't perform the calculation (they just use numer/denom)
double proportion = 0.0;
if (measureResource.getScoring().hasCoding() && denominator != 0) {
for (Coding coding : measureResource.getScoring().getCoding()) {
if (coding.hasCode() && coding.getCode().equals("proportion")) {
if (denominator != 0.0 ) {
proportion = numerator / denominator;
}
}
}
}
// TODO - this is super hacky ... change once improvementNotation is specified
// as a code
String improvementNotation = measureResource.getImprovementNotation().getCodingFirstRep().getCode().toLowerCase();
if (((improvementNotation.equals("increase")) && (proportion < 1.0))
|| ((improvementNotation.equals("decrease")) && (proportion > 0.0))) {
if (status != null && status.equalsIgnoreCase("closed-gap")) {
continue;
}
DetectedIssue detectedIssue = new DetectedIssue();
detectedIssue.setId(UUID.randomUUID().toString());
detectedIssue.setStatus(DetectedIssue.DetectedIssueStatus.FINAL);
detectedIssue.setPatient(new Reference(subject.startsWith("Patient/") ? subject : "Patient/" + subject));
detectedIssue.getEvidence().add(new DetectedIssue.DetectedIssueEvidenceComponent().addDetail(new Reference("MeasureReport/" + report.getId())));
CodeableConcept code = new CodeableConcept()
.addCoding(new Coding()
.setSystem("http://hl7.org/fhir/us/davinci-deqm/CodeSystem/detectedissue-category")
.setCode("care-gap")
.setDisplay("Gap in Care Detected"));
detectedIssue.setCode(code);
section.addEntry(
new Reference("DetectedIssue/" + detectedIssue.getIdElement().getIdPart()));
detectedIssues.add(detectedIssue);
}else {
if (status != null && status.equalsIgnoreCase("open-gap")) {
continue;
}
section.setText(new Narrative()
.setStatus(Narrative.NarrativeStatus.GENERATED)
.setDiv(new XhtmlNode().setValue("<div xmlns=\"http://www.w3.org/1999/xhtml\"><p>No detected issues.</p></div>")));
}
composition.addSection(section);
reports.add(report);
// TODO - add other types of improvement notation cases
}
}
Parameters parameters = new Parameters();
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(composition));
for (MeasureReport rep : reports) {
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(rep));
if (report.hasContained()) {
for (Resource contained : report.getContained()) {
if (contained instanceof Bundle) {
addEvaluatedResourcesToParameters((Bundle) contained, parameters);
if(null != parameters && !parameters.isEmpty()) {
List <Reference> evaluatedResource = new ArrayList<>();
parameters.getParameter().forEach(parameter -> {
Reference newEvaluatedResourceItem = new Reference();
newEvaluatedResourceItem.setReference(parameter.getResource().getId());
List<Extension> evalResourceExt = new ArrayList<>();
evalResourceExt.add(new Extension("http://hl7.org/fhir/us/davinci-deqm/StructureDefinition/extension-populationReference",
new CodeableConcept()
.addCoding(new Coding("http://teminology.hl7.org/CodeSystem/measure-population", "initial-population", "initial-population"))));
newEvaluatedResourceItem.setExtension(evalResourceExt);
evaluatedResource.add(newEvaluatedResourceItem);
});
report.setEvaluatedResource(evaluatedResource);
}
}
}
}
}
for (DetectedIssue detectedIssue : detectedIssues) {
careGapReport.addEntry(new Bundle.BundleEntryComponent().setResource(detectedIssue));
}
if(careGapReport.getEntry().isEmpty()){
return null;
}
return careGapReport;
}
private List<IBaseResource> getMeasureList(SearchParameterMap theParams, String measure){
List<IBaseResource> finalMeasureList = new ArrayList<>();
for(String theId: measure.split(",")){
if (theId.equals("")) {
continue;
}
Measure measureResource = this.measureResourceProvider.getDao().read(new IdType(theId.trim()));
if (measureResource != null) {
finalMeasureList.add(measureResource);
}
}
return finalMeasureList;
}
@Operation(name = "$collect-data", idempotent = true, type = Measure.class)
public Parameters collectData(@IdParam IdType theId, @OperationParam(name = "periodStart") String periodStart,
@OperationParam(name = "periodEnd") String periodEnd, @OperationParam(name = "patient") String patientRef,
@OperationParam(name = "practitioner") String practitionerRef,
@OperationParam(name = "lastReceivedOn") String lastReceivedOn) throws FHIRException {
// TODO: Spec says that the periods are not required, but I am not sure what to
// do when they aren't supplied so I made them required
MeasureReport report = evaluateMeasure(theId, periodStart, periodEnd, null, null, patientRef, null,
practitionerRef, lastReceivedOn, null, null, null);
report.setGroup(null);
Parameters parameters = new Parameters();
parameters.addParameter(
new Parameters.ParametersParameterComponent().setName("measurereport").setResource(report));
if (report.hasContained()) {
for (Resource contained : report.getContained()) {
if (contained instanceof Bundle) {
addEvaluatedResourcesToParameters((Bundle) contained, parameters);
}
}
}
// TODO: need a way to resolve referenced resources within the evaluated
// resources
// Should be able to use _include search with * wildcard, but HAPI doesn't
// support that
return parameters;
}
private void addEvaluatedResourcesToParameters(Bundle contained, Parameters parameters) {
Map<String, Resource> resourceMap = new HashMap<>();
if (contained.hasEntry()) {
for (Bundle.BundleEntryComponent entry : contained.getEntry()) {
if (entry.hasResource() && !(entry.getResource() instanceof ListResource)) {
if (!resourceMap.containsKey(entry.getResource().getIdElement().getValue())) {
parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
.setResource(entry.getResource()));
resourceMap.put(entry.getResource().getIdElement().getValue(), entry.getResource());
resolveReferences(entry.getResource(), parameters, resourceMap);
}
}
}
}
}
private void resolveReferences(Resource resource, Parameters parameters, Map<String, Resource> resourceMap) {
List<IBase> values;
for (BaseRuntimeChildDefinition child : this.measureResourceProvider.getContext()
.getResourceDefinition(resource).getChildren()) {
values = child.getAccessor().getValues(resource);
if (values == null || values.isEmpty()) {
continue;
}
else if (values.get(0) instanceof Reference
&& ((Reference) values.get(0)).getReferenceElement().hasResourceType()
&& ((Reference) values.get(0)).getReferenceElement().hasIdPart()) {
Resource fetchedResource = (Resource) registry
.getResourceDao(((Reference) values.get(0)).getReferenceElement().getResourceType())
.read(new IdType(((Reference) values.get(0)).getReferenceElement().getIdPart()));
if (!resourceMap.containsKey(fetchedResource.getIdElement().getValue())) {
parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
.setResource(fetchedResource));
resourceMap.put(fetchedResource.getIdElement().getValue(), fetchedResource);
}
}
}
}
// TODO - this needs a lot of work
@Operation(name = "$data-requirements", idempotent = true, type = Measure.class)
public org.hl7.fhir.r4.model.Library dataRequirements(@IdParam IdType theId,
@OperationParam(name = "startPeriod") String startPeriod,
@OperationParam(name = "endPeriod") String endPeriod) throws InternalErrorException, FHIRException {
Measure measure = this.measureResourceProvider.getDao().read(theId);
return this.dataRequirementsProvider.getDataRequirements(measure, this.libraryResolutionProvider);
}
@SuppressWarnings("unchecked")
@Operation(name = "$submit-data", idempotent = true, type = Measure.class)
public Resource submitData(RequestDetails details, @IdParam IdType theId,
@OperationParam(name = "measurereport", min = 1, max = 1, type = MeasureReport.class) MeasureReport report,
@OperationParam(name = "resource") List<IAnyResource> resources) {
Bundle transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
/*
* TODO - resource validation using $data-requirements operation (params are the
* provided id and the measurement period from the MeasureReport)
*
* TODO - profile validation ... not sure how that would work ... (get
* StructureDefinition from URL or must it be stored in Ruler?)
*/
transactionBundle.addEntry(createTransactionEntry(report));
for (IAnyResource resource : resources) {
Resource res = (Resource) resource;
if (res instanceof Bundle) {
for (Bundle.BundleEntryComponent entry : createTransactionBundle((Bundle) res).getEntry()) {
transactionBundle.addEntry(entry);
}
} else {
// Build transaction bundle
transactionBundle.addEntry(createTransactionEntry(res));
}
}
return (Resource) ((IFhirSystemDao<Bundle,?>)this.registry.getSystemDao()).transaction(details, transactionBundle);
}
private Bundle createTransactionBundle(Bundle bundle) {
Bundle transactionBundle;
if (bundle != null) {
if (bundle.hasType() && bundle.getType() == Bundle.BundleType.TRANSACTION) {
transactionBundle = bundle;
} else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
if (bundle.hasEntry()) {
for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
if (entry.hasResource()) {
transactionBundle.addEntry(createTransactionEntry(entry.getResource()));
}
}
}
}
} else {
transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION).setEntry(new ArrayList<>());
}
return transactionBundle;
}
private Bundle.BundleEntryComponent createTransactionEntry(Resource resource) {
Bundle.BundleEntryComponent transactionEntry = new Bundle.BundleEntryComponent().setResource(resource);
if (resource.hasId()) {
transactionEntry.setRequest(
new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.PUT).setUrl(resource.getId()));
} else {
transactionEntry.setRequest(new Bundle.BundleEntryRequestComponent().setMethod(Bundle.HTTPVerb.POST)
.setUrl(resource.fhirType()));
}
return transactionEntry;
}
}
| Change parameter name to return
| r4/src/main/java/org/opencds/cqf/r4/providers/MeasureOperationsProvider.java | Change parameter name to return | <ide><path>4/src/main/java/org/opencds/cqf/r4/providers/MeasureOperationsProvider.java
<ide> if(careGapParameterValidation(periodStart, periodEnd, subject, topic, practitioner, measure, status, organization)) {
<ide> if(subject.startsWith("Patient/")){
<ide> returnParams.addParameter(new Parameters.ParametersParameterComponent()
<del> .setName("result")
<add> .setName("return")
<ide> .setResource(patientCareGap(periodStart, periodEnd, subject, topic, measure, status)));
<ide> return returnParams;
<ide> }else if(subject.startsWith("Group/")) {
<ide> Bundle patientGapBundle = patientCareGap(periodStart, periodEnd, groupSubject, topic, measure, status);
<ide> if(null != patientGapBundle){
<ide> returnParams.addParameter(new Parameters.ParametersParameterComponent()
<del> .setName("result")
<add> .setName("return")
<ide> .setResource(patientGapBundle));
<ide> }
<ide> }); |
|
Java | apache-2.0 | 16db68dddab2ebdd84c003c76c566ad0998bd546 | 0 | jjmrocha/couchdb-client | /*
a * CouchDB-client
* ==============
*
* Copyright (C) 2016-18 Joaquim Rocha <[email protected]>
*
* 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.
*/
package net.uiqui.couchdb.api;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import net.uiqui.couchdb.api.error.CouchException;
import net.uiqui.couchdb.api.error.DocNotFoundException;
import net.uiqui.couchdb.impl.Promise;
import net.uiqui.couchdb.impl.StreamSource;
import net.uiqui.couchdb.protocol.CouchAPI;
import net.uiqui.couchdb.protocol.DeleteDoc;
import net.uiqui.couchdb.protocol.impl.QueryResult;
import net.uiqui.couchdb.util.AsyncTask;
import net.uiqui.couchdb.util.CouchDBConstants;
public class DB {
private final CouchAPI api;
private final String dbName;
public DB(final CouchAPI api, final String dbName) {
this.dbName = dbName;
this.api = api;
}
public boolean contains(final String docId) throws CouchException {
return api.contains(dbName, docId);
}
public Stream<String> docIds() {
return docIds(null, null);
}
public Stream<String> docIds(final String startKey, final String endKey) {
return StreamSupport.stream(new StreamSource<String>() {
@Override
public Collection<String> fetchBatch(final long offset, final long size) throws Exception {
return docIds(startKey, endKey, offset, size);
}
}, false);
}
public Collection<String> docIds(final String startKey, final String endKey, final long skip, final long limit) throws CouchException {
return api.docIds(dbName, startKey, endKey, skip, limit);
}
public <T> T get(final String docId, final Class<T> type) throws CouchException {
return api.get(dbName, docId, type);
}
public void save(final Document doc) throws CouchException {
if (doc.getId() == null || doc.getRevision() == null) {
api.add(dbName, doc);
} else {
api.update(dbName, doc);
}
}
public void remove(final Document doc) throws CouchException {
remove(doc.getId(), doc.getRevision());
}
public void remove(final String docId, final String revision) throws CouchException {
api.remove(dbName, docId, revision);
}
public void remove(final String docId) throws CouchException {
final Document doc = get(docId, Document.class);
if (doc != null) {
remove(doc);
} else {
throw new DocNotFoundException(docId);
}
}
public ViewResult execute(final ViewRequest request) throws CouchException {
return api.execute(dbName, request);
}
public Promise<ViewResult> async(final ViewRequest request) {
return Promise.newPromise(() -> {
try {
return execute(request);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
public Stream<ViewResult.Row> stream(final ViewRequest request) {
return StreamSupport.stream(new StreamSource<ViewResult.Row>() {
@Override
public Collection<ViewResult.Row> fetchBatch(final long offset, final long size) throws Exception {
request.batch(offset, size);
final ViewResult result = execute(request);
return Arrays.asList(result.rows());
}
}, false);
}
public <T> Collection<T> execute(final QueryRequest request, final Class<T> type) throws CouchException {
final QueryResult queryResult = api.execute(dbName, request);
return queryResult.resultAsListOf(type);
}
public <T> Promise<Collection<T>> async(final QueryRequest request, final Class<T> type) {
return Promise.newPromise(() -> {
try {
return execute(request, type);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
public <T> Stream<T> stream(final QueryRequest request, final Class<T> type) {
return StreamSupport.stream(new StreamSource<T>() {
@Override
public Collection<T> fetchBatch(final long offset, final long size) throws Exception {
request.batch(offset, size);
return execute(request, type);
}
}, false);
}
public Promise<BulkResult[]> bulkSave(final Collection<Document> docs) {
final Document[] docArray = docs.toArray(new Document[docs.size()]);
return bulkSave(docArray);
}
public Promise<BulkResult[]> bulkSave(final Document[] docs) {
return Promise.newPromise(() -> {
try {
final BulkResult[] results = bulk(docs);
final List<BulkResult> output = new ArrayList<>();
for (int i = 0; i < docs.length; i++) {
final BulkResult result = results[i];
if (result.isSuccess()) {
final Document input = docs[i];
if (input.getId() != null) {
input.setId(result.id());
}
input.setRevision(result.rev());
} else {
output.add(result);
}
}
return output.toArray(new BulkResult[output.size()]);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
public Promise<BulkResult[]> bulkRemove(final Document[] docs) {
return Promise.newPromise(() -> {
final DeleteDoc[] deletDocs = DeleteDoc.from(docs);
try {
return bulkRemove(deletDocs);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
public Promise<BulkResult[]> bulkRemove(final Collection<Document> docs) {
return Promise.newPromise(() -> {
final DeleteDoc[] deletDocs = DeleteDoc.from(docs);
try {
return bulkRemove(deletDocs);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
private BulkResult[] bulkRemove(final DeleteDoc[] docs) throws CouchException {
final BulkResult[] results = bulk(docs);
final List<BulkResult> output = new ArrayList<>();
for (final BulkResult result : results) {
if (!result.isSuccess()) {
output.add(result);
}
}
return output.toArray(new BulkResult[output.size()]);
}
private BulkResult[] bulk(final Document[] docs) throws CouchException {
return AsyncTask.invoke(new RecursiveBulkTask(api, dbName, docs));
}
private static final class RecursiveBulkTask extends RecursiveTask<BulkResult[]> {
private final String dbName;
private final CouchAPI api;
private final Document[] docs;
public RecursiveBulkTask(final CouchAPI api, final String dbName, final Document[] docs) {
this.api = api;
this.dbName = dbName;
this.docs = docs;
}
@Override
public BulkResult[] compute() {
if (docs.length <= CouchDBConstants.BULK_REQUEST_SIZE) {
try {
return api.bulk(dbName, docs);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
}
final int headSize = CouchDBConstants.BULK_REQUEST_SIZE;
final int tailSize = docs.length - CouchDBConstants.BULK_REQUEST_SIZE;
final Document[] head = new Document[headSize];
final Document[] tail = new Document[tailSize];
System.arraycopy(docs, 0, head, 0, headSize);
System.arraycopy(docs, headSize, tail, 0, tailSize);
final RecursiveBulkTask firstBlock = new RecursiveBulkTask(api, dbName, head);
final RecursiveBulkTask remainingBlock = new RecursiveBulkTask(api, dbName, tail);
remainingBlock.fork();
final BulkResult[] results = new BulkResult[docs.length];
System.arraycopy(firstBlock.compute(), 0, results, 0, headSize);
System.arraycopy(remainingBlock.join(), 0, results, headSize, tailSize);
return results;
}
}
}
| src/main/java/net/uiqui/couchdb/api/DB.java | /*
a * CouchDB-client
* ==============
*
* Copyright (C) 2016-18 Joaquim Rocha <[email protected]>
*
* 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.
*/
package net.uiqui.couchdb.api;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import net.uiqui.couchdb.api.error.CouchException;
import net.uiqui.couchdb.api.error.DocNotFoundException;
import net.uiqui.couchdb.impl.Promise;
import net.uiqui.couchdb.impl.StreamSource;
import net.uiqui.couchdb.protocol.CouchAPI;
import net.uiqui.couchdb.protocol.DeleteDoc;
import net.uiqui.couchdb.protocol.impl.QueryResult;
import net.uiqui.couchdb.util.AsyncTask;
import net.uiqui.couchdb.util.CouchDBConstants;
public class DB {
private final CouchAPI api;
private final String dbName;
public DB(final CouchAPI api, final String dbName) {
this.dbName = dbName;
this.api = api;
}
public boolean contains(final String docId) throws CouchException {
return api.contains(dbName, docId);
}
public Stream<String> docIds() {
return docIds(null, null);
}
public Stream<String> docIds(final String startKey, final String endKey) {
return StreamSupport.stream(new StreamSource<String>() {
@Override
public Collection<String> fetchBatch(final long offset, final long size) throws Exception {
return docIds(startKey, endKey, offset, size);
}
}, false);
}
public Collection<String> docIds(final String startKey, final String endKey, final long skip, final long limit) throws CouchException {
return api.docIds(dbName, startKey, endKey, skip, limit);
}
public <T> T get(final String docId, final Class<T> type) throws CouchException {
return api.get(dbName, docId, type);
}
public void save(final Document doc) throws CouchException {
if (doc.getId() == null || doc.getRevision() == null) {
api.add(dbName, doc);
} else {
api.update(dbName, doc);
}
}
public void remove(final Document doc) throws CouchException {
remove(doc.getId(), doc.getRevision());
}
public void remove(final String docId, final String revision) throws CouchException {
api.remove(dbName, docId, revision);
}
public void remove(final String docId) throws CouchException {
final Document doc = get(docId, Document.class);
if (doc != null) {
remove(doc);
} else {
throw new DocNotFoundException(docId);
}
}
public ViewResult execute(final ViewRequest request) throws CouchException {
return api.execute(dbName, request);
}
public Promise<ViewResult> async(final ViewRequest request) {
return Promise.newPromise(() -> {
try {
return execute(request);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
public Stream<ViewResult.Row> stream(final ViewRequest request) {
return StreamSupport.stream(new StreamSource<ViewResult.Row>() {
@Override
public Collection<ViewResult.Row> fetchBatch(final long offset, final long size) throws Exception {
request.batch(offset, size);
final ViewResult result = execute(request);
return Arrays.asList(result.rows());
}
}, false);
}
public <T> Collection<T> execute(final QueryRequest request, final Class<T> type) throws CouchException {
final QueryResult queryResult = api.execute(dbName, request);
return queryResult.resultAsListOf(type);
}
public <T> Promise<Collection<T>> async(final QueryRequest request, final Class<T> type) {
return Promise.newPromise(() -> {
try {
return execute(request, type);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
public <T> Stream<T> stream(final QueryRequest request, final Class<T> type) {
return StreamSupport.stream(new StreamSource<T>() {
@Override
public Collection<T> fetchBatch(final long offset, final long size) throws Exception {
request.batch(offset, size);
return execute(request, type);
}
}, false);
}
public Promise<BulkResult[]> bulkSave(final Collection<Document> docs) {
final Document[] docArray = docs.toArray(new Document[docs.size()]);
return bulkSave(docArray);
}
public Promise<BulkResult[]> bulkSave(final Document[] docs) {
return Promise.newPromise(() -> {
try {
final BulkResult[] results = bulk(docs);
final List<BulkResult> output = new ArrayList<>();
for (int i = 0; i < docs.length; i++) {
final BulkResult result = results[i];
if (result.isSuccess()) {
final Document input = docs[i];
if (input.getId() != null) {
input.setId(result.id());
}
input.setRevision(result.rev());
} else {
output.add(result);
}
}
return output.toArray(new BulkResult[output.size()]);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
public Promise<BulkResult[]> bulkRemove(final Document[] docs) {
return Promise.newPromise(() -> {
final DeleteDoc[] deletDocs = DeleteDoc.from(docs);
try {
return bulkRemove(deletDocs);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
public Promise<BulkResult[]> bulkRemove(final Collection<Document> docs) {
return Promise.newPromise(() -> {
final DeleteDoc[] deletDocs = DeleteDoc.from(docs);
try {
return bulkRemove(deletDocs);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
});
}
private BulkResult[] bulkRemove(final DeleteDoc[] docs) throws CouchException {
final BulkResult[] results = bulk(docs);
final List<BulkResult> output = new ArrayList<>();
for (final BulkResult result : results) {
if (!result.isSuccess()) {
output.add(result);
}
}
return output.toArray(new BulkResult[output.size()]);
}
private BulkResult[] bulk(final Document[] docs) throws CouchException {
return AsyncTask.invoke(new RecursiveBulkTask(api, dbName, docs));
}
private static class RecursiveBulkTask extends RecursiveTask<BulkResult[]> {
private final String dbName;
private final CouchAPI api;
private final Document[] docs;
public RecursiveBulkTask(final CouchAPI api, final String dbName, final Document[] docs) {
this.api = api;
this.dbName = dbName;
this.docs = docs;
}
@Override
public BulkResult[] compute() {
if (CouchDBConstants.BULK_REQUEST_SIZE > docs.length) {
try {
return api.bulk(dbName, docs);
} catch (final CouchException ex) {
throw new CompletionException(ex);
}
}
final Document[] head = new Document[CouchDBConstants.BULK_REQUEST_SIZE];
final Document[] tail = new Document[docs.length - CouchDBConstants.BULK_REQUEST_SIZE];
System.arraycopy(docs, 0, head, head.length, 0);
System.arraycopy(docs, CouchDBConstants.BULK_REQUEST_SIZE, tail, tail.length, 0);
final RecursiveBulkTask firstBlock = new RecursiveBulkTask(api, dbName, head);
final RecursiveBulkTask remainingBlock = new RecursiveBulkTask(api, dbName, tail);
remainingBlock.fork();
final BulkResult[] results = new BulkResult[docs.length];
System.arraycopy(firstBlock.compute(), 0, results, head.length, 0);
System.arraycopy(remainingBlock.join(), 0, results, tail.length, CouchDBConstants.BULK_REQUEST_SIZE);
return results;
}
}
}
| Bulk recursiveTask | src/main/java/net/uiqui/couchdb/api/DB.java | Bulk recursiveTask | <ide><path>rc/main/java/net/uiqui/couchdb/api/DB.java
<ide> return AsyncTask.invoke(new RecursiveBulkTask(api, dbName, docs));
<ide> }
<ide>
<del> private static class RecursiveBulkTask extends RecursiveTask<BulkResult[]> {
<add> private static final class RecursiveBulkTask extends RecursiveTask<BulkResult[]> {
<ide> private final String dbName;
<ide> private final CouchAPI api;
<ide> private final Document[] docs;
<ide>
<ide> @Override
<ide> public BulkResult[] compute() {
<del> if (CouchDBConstants.BULK_REQUEST_SIZE > docs.length) {
<add> if (docs.length <= CouchDBConstants.BULK_REQUEST_SIZE) {
<ide> try {
<ide> return api.bulk(dbName, docs);
<ide> } catch (final CouchException ex) {
<ide> }
<ide> }
<ide>
<del> final Document[] head = new Document[CouchDBConstants.BULK_REQUEST_SIZE];
<del> final Document[] tail = new Document[docs.length - CouchDBConstants.BULK_REQUEST_SIZE];
<del>
<del> System.arraycopy(docs, 0, head, head.length, 0);
<del> System.arraycopy(docs, CouchDBConstants.BULK_REQUEST_SIZE, tail, tail.length, 0);
<add> final int headSize = CouchDBConstants.BULK_REQUEST_SIZE;
<add> final int tailSize = docs.length - CouchDBConstants.BULK_REQUEST_SIZE;
<add> final Document[] head = new Document[headSize];
<add> final Document[] tail = new Document[tailSize];
<add>
<add> System.arraycopy(docs, 0, head, 0, headSize);
<add> System.arraycopy(docs, headSize, tail, 0, tailSize);
<ide>
<ide> final RecursiveBulkTask firstBlock = new RecursiveBulkTask(api, dbName, head);
<ide> final RecursiveBulkTask remainingBlock = new RecursiveBulkTask(api, dbName, tail);
<ide> remainingBlock.fork();
<ide>
<ide> final BulkResult[] results = new BulkResult[docs.length];
<del> System.arraycopy(firstBlock.compute(), 0, results, head.length, 0);
<del> System.arraycopy(remainingBlock.join(), 0, results, tail.length, CouchDBConstants.BULK_REQUEST_SIZE);
<add> System.arraycopy(firstBlock.compute(), 0, results, 0, headSize);
<add> System.arraycopy(remainingBlock.join(), 0, results, headSize, tailSize);
<ide>
<ide> return results;
<ide> } |
|
Java | apache-2.0 | 269e4f97e620ec45ec6813b676c3694e4ca25945 | 0 | hawkular/hawkular-metrics,hawkular/hawkular-metrics,hawkular/hawkular-metrics,hawkular/hawkular-metrics | /*
* Copyright 2014-2019 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.
*/
package org.hawkular.metrics.schema;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.hawkular.metrics.scheduler.api.JobsManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.JdkSSLOptions;
import com.datastax.driver.core.SSLOptions;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;
/**
* @author jsanda
*/
public class Installer {
private static final Logger logger = LoggerFactory.getLogger(Installer.class);
private List<String> cassandraNodes;
private int cassandraConnectionMaxRetries;
private long cassandraConnectionMaxDelay;
private boolean useSSL;
private int cqlPort;
private String keyspace;
private boolean resetdb;
private int replicationFactor;
private long versionUpdateDelay;
private int versionUpdateMaxRetries;
private long waitRetry;
private int jobMaxRetries;
// Currently the installer is configured via system properties, and none of its fields are exposed as properties.
// If the need should arise, the fields can be exposed as properties with public getter/setter methods.
public Installer() {
cqlPort = Integer.getInteger("hawkular.metrics.cassandra.cql-port", 9042);
useSSL = Boolean.getBoolean("hawkular.metrics.cassandra.use-ssl");
String nodes = System.getProperty("hawkular.metrics.cassandra.nodes", "127.0.0.1");
cassandraNodes = new ArrayList<>();
Arrays.stream(nodes.split(",")).forEach(cassandraNodes::add);
cassandraConnectionMaxDelay = Long.getLong("hawkular.metrics.cassandra.connection.max-delay", 30) * 1000;
cassandraConnectionMaxRetries = Integer.getInteger("hawkular.metrics.cassandra.connection.max-retries", 5);
keyspace = System.getProperty("hawkular.metrics.cassandra.keyspace", "hawkular_metrics");
resetdb = Boolean.getBoolean("hawkular.metrics.cassandra.resetdb");
replicationFactor = Integer.getInteger("hawkular.metrics.cassandra.replication-factor", 1);
versionUpdateDelay = Long.getLong("hawkular.metrics.version-update.delay", 5) * 1000;
versionUpdateMaxRetries = Integer.getInteger("hawkular.metrics.version-update.max-retries", 10);
waitRetry = Long.getLong("hawkular.metrics.version-update.retry-delay", 10);
jobMaxRetries = Integer.getInteger("hawkular.metrics.job-max-retires", 20);
}
public void run() {
int retryCounter = 0;
while (retryCounter < jobMaxRetries) {
try {
this.install();
System.exit(0);
}
catch (InterruptedException e) {
logger.warn("Aborting installation");
System.exit(1);
} catch (Exception e) {
retryCounter++;
logger.error("Schema installer failed on retry " + retryCounter + " of " + jobMaxRetries +
", retry again.");
if (retryCounter >= jobMaxRetries) {
e.printStackTrace();
System.exit(1);
}
}
}
}
public void install() throws Exception {
logVersion();
logInstallerProperties();
Session session = initSession();
waitForAllNodesToBeUp(session);
SchemaService schemaService = new SchemaService(session, keyspace);
schemaService.run(resetdb, replicationFactor, false);
JobsManager jobsManager = new JobsManager(session);
jobsManager.installJobs();
schemaService.updateVersion(versionUpdateDelay, versionUpdateMaxRetries);
schemaService.updateSchemaVersionSession(versionUpdateDelay, versionUpdateMaxRetries);
logger.info("Finished installation");
}
private void logVersion() {
logger.info("Hawkular Metrics Schema Installer v{}", VersionUtil.getVersion());
}
private void logInstallerProperties() {
logger.info("Configured installer properties:\n" +
"\tcqlPort = " + cqlPort + "\n" +
"\tuseSSL = " + useSSL + "\n" +
"\tcassandraNodes = " + cassandraNodes + "\n" +
"\tcassandraConnectionMaxDelay = " + cassandraConnectionMaxDelay + "\n" +
"\tcassandraConnectionMaxRetries = " + cassandraConnectionMaxRetries + "\n" +
"\tkeyspace = " + keyspace + "\n" +
"\tresetdb = " + resetdb + "\n" +
"\treplicationFactor = " + replicationFactor + "\n" +
"\tversionUpdateDelay = " + versionUpdateDelay + "\n" +
"\tversionUpdateMaxRetries = " + versionUpdateMaxRetries);
}
private Session initSession() throws InterruptedException {
long retry = 5000;
while (true) {
try {
return createSession();
} catch (NoHostAvailableException e) {
logger.info("Cassandra may not be up yet. Retrying in {} ms", retry);
Thread.sleep(retry);
}
}
}
private Session createSession() {
Cluster.Builder clusterBuilder = new Cluster.Builder();
clusterBuilder.addContactPoints(cassandraNodes.toArray(new String[] {}));
if (useSSL) {
SSLOptions sslOptions = null;
try {
String[] defaultCipherSuites = {"TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"};
sslOptions = JdkSSLOptions.builder().withSSLContext(SSLContext.getDefault())
.withCipherSuites(defaultCipherSuites).build();
clusterBuilder.withSSL(sslOptions);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SSL support is required but is not available in the JVM.", e);
}
}
clusterBuilder.withoutJMXReporting();
Cluster cluster = clusterBuilder.build();
cluster.init();
Session createdSession = null;
try {
createdSession = cluster.connect("system");
return createdSession;
} finally {
if (createdSession == null) {
cluster.close();
}
}
}
private void waitForAllNodesToBeUp(Session session) {
boolean isReady = false;
int attempts = cassandraConnectionMaxRetries;
long delay = 2000;
while (!isReady && !Thread.currentThread().isInterrupted() && attempts-- >= 0) {
isReady = true;
for (Host host : session.getCluster().getMetadata().getAllHosts()) {
if (!host.isUp()) {
isReady = false;
logger.warn("Cassandra node {} may not be up yet. Waiting {} ms for node to come up", host, delay);
try {
Thread.sleep(delay);
delay = Math.min(delay * 2, cassandraConnectionMaxDelay);
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
break;
}
}
}
if (!isReady) {
throw new RuntimeException("It appears that not all nodes in the Cassandra cluster are up " +
"after " + attempts + " checks. Schema updates cannot proceed without all nodes being up.");
}
}
public static void main(String[] args) {
new Installer().run();
}
}
| core/schema-installer/src/main/java/org/hawkular/metrics/schema/Installer.java | /*
* Copyright 2014-2018 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.
*/
package org.hawkular.metrics.schema;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.hawkular.metrics.scheduler.api.JobsManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.JdkSSLOptions;
import com.datastax.driver.core.SSLOptions;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;
/**
* @author jsanda
*/
public class Installer {
private static final Logger logger = LoggerFactory.getLogger(Installer.class);
private List<String> cassandraNodes;
private int cassandraConnectionMaxRetries;
private long cassandraConnectionMaxDelay;
private boolean useSSL;
private int cqlPort;
private String keyspace;
private boolean resetdb;
private int replicationFactor;
private long versionUpdateDelay;
private int versionUpdateMaxRetries;
// Currently the installer is configured via system properties, and none of its fields are exposed as properties.
// If the need should arise, the fields can be exposed as properties with public getter/setter methods.
public Installer() {
cqlPort = Integer.getInteger("hawkular.metrics.cassandra.cql-port", 9042);
useSSL = Boolean.getBoolean("hawkular.metrics.cassandra.use-ssl");
String nodes = System.getProperty("hawkular.metrics.cassandra.nodes", "127.0.0.1");
cassandraNodes = new ArrayList<>();
Arrays.stream(nodes.split(",")).forEach(cassandraNodes::add);
cassandraConnectionMaxDelay = Long.getLong("hawkular.metrics.cassandra.connection.max-delay", 30) * 1000;
cassandraConnectionMaxRetries = Integer.getInteger("hawkular.metrics.cassandra.connection.max-retries", 5);
keyspace = System.getProperty("hawkular.metrics.cassandra.keyspace", "hawkular_metrics");
resetdb = Boolean.getBoolean("hawkular.metrics.cassandra.resetdb");
replicationFactor = Integer.getInteger("hawkular.metrics.cassandra.replication-factor", 1);
versionUpdateDelay = Long.getLong("hawkular.metrics.version-update.delay", 5) * 1000;
versionUpdateMaxRetries = Integer.getInteger("hawkular.metrics.version-update.max-retries", 10);
}
public void run() {
logVersion();
logInstallerProperties();
try (Session session = initSession()) {
waitForAllNodesToBeUp(session);
SchemaService schemaService = new SchemaService(session, keyspace);
schemaService.run(resetdb, replicationFactor, false);
JobsManager jobsManager = new JobsManager(session);
jobsManager.installJobs();
schemaService.updateVersion(versionUpdateDelay, versionUpdateMaxRetries);
schemaService.updateSchemaVersionSession(versionUpdateDelay, versionUpdateMaxRetries);
logger.info("Finished installation");
} catch (InterruptedException e) {
logger.warn("Aborting installation");
System.exit(1);
} catch (Exception e) {
logger.warn("Installation failed", e);
System.exit(1);
} finally {
System.exit(0);
}
}
private void logVersion() {
logger.info("Hawkular Metrics Schema Installer v{}", VersionUtil.getVersion());
}
private void logInstallerProperties() {
logger.info("Configured installer properties:\n" +
"\tcqlPort = " + cqlPort + "\n" +
"\tuseSSL = " + useSSL + "\n" +
"\tcassandraNodes = " + cassandraNodes + "\n" +
"\tcassandraConnectionMaxDelay = " + cassandraConnectionMaxDelay + "\n" +
"\tcassandraConnectionMaxRetries = " + cassandraConnectionMaxRetries + "\n" +
"\tkeyspace = " + keyspace + "\n" +
"\tresetdb = " + resetdb + "\n" +
"\treplicationFactor = " + replicationFactor + "\n" +
"\tversionUpdateDelay = " + versionUpdateDelay + "\n" +
"\tversionUpdateMaxRetries = " + versionUpdateMaxRetries);
}
private Session initSession() throws InterruptedException {
long retry = 5000;
while (true) {
try {
return createSession();
} catch (NoHostAvailableException e) {
logger.info("Cassandra may not be up yet. Retrying in {} ms", retry);
Thread.sleep(retry);
}
}
}
private Session createSession() {
Cluster.Builder clusterBuilder = new Cluster.Builder();
clusterBuilder.addContactPoints(cassandraNodes.toArray(new String[] {}));
if (useSSL) {
SSLOptions sslOptions = null;
try {
String[] defaultCipherSuites = {"TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"};
sslOptions = JdkSSLOptions.builder().withSSLContext(SSLContext.getDefault())
.withCipherSuites(defaultCipherSuites).build();
clusterBuilder.withSSL(sslOptions);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SSL support is required but is not available in the JVM.", e);
}
}
clusterBuilder.withoutJMXReporting();
Cluster cluster = clusterBuilder.build();
cluster.init();
Session createdSession = null;
try {
createdSession = cluster.connect("system");
return createdSession;
} finally {
if (createdSession == null) {
cluster.close();
}
}
}
private void waitForAllNodesToBeUp(Session session) {
boolean isReady = false;
int attempts = cassandraConnectionMaxRetries;
long delay = 2000;
while (!isReady && !Thread.currentThread().isInterrupted() && attempts-- >= 0) {
isReady = true;
for (Host host : session.getCluster().getMetadata().getAllHosts()) {
if (!host.isUp()) {
isReady = false;
logger.warn("Cassandra node {} may not be up yet. Waiting {} ms for node to come up", host, delay);
try {
Thread.sleep(delay);
delay = Math.min(delay * 2, cassandraConnectionMaxDelay);
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
break;
}
}
}
if (!isReady) {
throw new RuntimeException("It appears that not all nodes in the Cassandra cluster are up " +
"after " + attempts + " checks. Schema updates cannot proceed without all nodes being up.");
}
}
public static void main(String[] args) {
new Installer().run();
}
}
| BZ 1632852 Add retry logic that keep installer running until success.
| core/schema-installer/src/main/java/org/hawkular/metrics/schema/Installer.java | BZ 1632852 Add retry logic that keep installer running until success. | <ide><path>ore/schema-installer/src/main/java/org/hawkular/metrics/schema/Installer.java
<ide> /*
<del> * Copyright 2014-2018 Red Hat, Inc. and/or its affiliates
<add> * Copyright 2014-2019 Red Hat, Inc. and/or its affiliates
<ide> * and other contributors as indicated by the @author tags.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide>
<ide> private int versionUpdateMaxRetries;
<ide>
<add> private long waitRetry;
<add>
<add> private int jobMaxRetries;
<add>
<add>
<ide> // Currently the installer is configured via system properties, and none of its fields are exposed as properties.
<ide> // If the need should arise, the fields can be exposed as properties with public getter/setter methods.
<ide> public Installer() {
<ide> replicationFactor = Integer.getInteger("hawkular.metrics.cassandra.replication-factor", 1);
<ide> versionUpdateDelay = Long.getLong("hawkular.metrics.version-update.delay", 5) * 1000;
<ide> versionUpdateMaxRetries = Integer.getInteger("hawkular.metrics.version-update.max-retries", 10);
<add> waitRetry = Long.getLong("hawkular.metrics.version-update.retry-delay", 10);
<add> jobMaxRetries = Integer.getInteger("hawkular.metrics.job-max-retires", 20);
<add>
<ide> }
<ide>
<ide> public void run() {
<add> int retryCounter = 0;
<add> while (retryCounter < jobMaxRetries) {
<add> try {
<add> this.install();
<add> System.exit(0);
<add> }
<add> catch (InterruptedException e) {
<add> logger.warn("Aborting installation");
<add> System.exit(1);
<add> } catch (Exception e) {
<add> retryCounter++;
<add> logger.error("Schema installer failed on retry " + retryCounter + " of " + jobMaxRetries +
<add> ", retry again.");
<add> if (retryCounter >= jobMaxRetries) {
<add> e.printStackTrace();
<add> System.exit(1);
<add> }
<add> }
<add> }
<add> }
<add>
<add> public void install() throws Exception {
<ide> logVersion();
<ide> logInstallerProperties();
<ide>
<del> try (Session session = initSession()) {
<del> waitForAllNodesToBeUp(session);
<del>
<del> SchemaService schemaService = new SchemaService(session, keyspace);
<del> schemaService.run(resetdb, replicationFactor, false);
<del>
<del> JobsManager jobsManager = new JobsManager(session);
<del> jobsManager.installJobs();
<del>
<del> schemaService.updateVersion(versionUpdateDelay, versionUpdateMaxRetries);
<del> schemaService.updateSchemaVersionSession(versionUpdateDelay, versionUpdateMaxRetries);
<del>
<del> logger.info("Finished installation");
<del> } catch (InterruptedException e) {
<del> logger.warn("Aborting installation");
<del> System.exit(1);
<del> } catch (Exception e) {
<del> logger.warn("Installation failed", e);
<del> System.exit(1);
<del> } finally {
<del> System.exit(0);
<del> }
<add> Session session = initSession();
<add> waitForAllNodesToBeUp(session);
<add>
<add> SchemaService schemaService = new SchemaService(session, keyspace);
<add> schemaService.run(resetdb, replicationFactor, false);
<add>
<add> JobsManager jobsManager = new JobsManager(session);
<add> jobsManager.installJobs();
<add>
<add> schemaService.updateVersion(versionUpdateDelay, versionUpdateMaxRetries);
<add> schemaService.updateSchemaVersionSession(versionUpdateDelay, versionUpdateMaxRetries);
<add> logger.info("Finished installation");
<ide> }
<ide>
<ide> private void logVersion() { |
|
JavaScript | mit | b1dde46892f1cd924d92e57504c1b5452acb3395 | 0 | ai/autoprefixer-rails,ai/autoprefixer-rails,ai/autoprefixer-rails,ai/autoprefixer-rails | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.autoprefixer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(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 s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var unpack = require('caniuse-lite').feature;
var browsersSort = function browsersSort(a, b) {
a = a.split(' ');
b = b.split(' ');
if (a[0] > b[0]) {
return 1;
} else if (a[0] < b[0]) {
return -1;
} else {
return Math.sign(parseFloat(a[1]) - parseFloat(b[1]));
}
};
// Convert Can I Use data
function f(data, opts, callback) {
data = unpack(data);
if (!callback) {
var _ref = [opts, {}];
callback = _ref[0];
opts = _ref[1];
}
var match = opts.match || /\sx($|\s)/;
var need = [];
for (var browser in data.stats) {
var versions = data.stats[browser];
for (var version in versions) {
var support = versions[version];
if (support.match(match)) {
need.push(browser + ' ' + version);
}
}
}
callback(need.sort(browsersSort));
}
// Add data for all properties
var result = {};
var prefix = function prefix(names, data) {
for (var _iterator = names, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref2;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
}
var name = _ref2;
result[name] = Object.assign({}, data);
}
};
var add = function add(names, data) {
for (var _iterator2 = names, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref3;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref3 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref3 = _i2.value;
}
var name = _ref3;
result[name].browsers = result[name].browsers.concat(data.browsers).sort(browsersSort);
}
};
module.exports = result;
// Border Radius
f(require('caniuse-lite/data/features/border-radius.js'), function (browsers) {
return prefix(['border-radius', 'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'], {
mistakes: ['-khtml-', '-ms-', '-o-'],
feature: 'border-radius',
browsers: browsers
});
});
// Box Shadow
f(require('caniuse-lite/data/features/css-boxshadow.js'), function (browsers) {
return prefix(['box-shadow'], {
mistakes: ['-khtml-'],
feature: 'css-boxshadow',
browsers: browsers
});
});
// Animation
f(require('caniuse-lite/data/features/css-animation.js'), function (browsers) {
return prefix(['animation', 'animation-name', 'animation-duration', 'animation-delay', 'animation-direction', 'animation-fill-mode', 'animation-iteration-count', 'animation-play-state', 'animation-timing-function', '@keyframes'], {
mistakes: ['-khtml-', '-ms-'],
feature: 'css-animation',
browsers: browsers
});
});
// Transition
f(require('caniuse-lite/data/features/css-transitions.js'), function (browsers) {
return prefix(['transition', 'transition-property', 'transition-duration', 'transition-delay', 'transition-timing-function'], {
mistakes: ['-khtml-', '-ms-'],
browsers: browsers,
feature: 'css-transitions'
});
});
// Transform 2D
f(require('caniuse-lite/data/features/transforms2d.js'), function (browsers) {
return prefix(['transform', 'transform-origin'], {
feature: 'transforms2d',
browsers: browsers
});
});
// Transform 3D
var transforms3d = require('caniuse-lite/data/features/transforms3d.js');
f(transforms3d, function (browsers) {
prefix(['perspective', 'perspective-origin'], {
feature: 'transforms3d',
browsers: browsers
});
return prefix(['transform-style'], {
mistakes: ['-ms-', '-o-'],
browsers: browsers,
feature: 'transforms3d'
});
});
f(transforms3d, { match: /y\sx|y\s#2/ }, function (browsers) {
return prefix(['backface-visibility'], {
mistakes: ['-ms-', '-o-'],
feature: 'transforms3d',
browsers: browsers
});
});
// Gradients
var gradients = require('caniuse-lite/data/features/css-gradients.js');
f(gradients, { match: /y\sx/ }, function (browsers) {
return prefix(['linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
mistakes: ['-ms-'],
feature: 'css-gradients',
browsers: browsers
});
});
f(gradients, { match: /a\sx/ }, function (browsers) {
browsers = browsers.map(function (i) {
if (/op/.test(i)) {
return i;
} else {
return i + ' old';
}
});
return add(['linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient'], {
feature: 'css-gradients',
browsers: browsers
});
});
// Box sizing
f(require('caniuse-lite/data/features/css3-boxsizing.js'), function (browsers) {
return prefix(['box-sizing'], {
feature: 'css3-boxsizing',
browsers: browsers
});
});
// Filter Effects
f(require('caniuse-lite/data/features/css-filters.js'), function (browsers) {
return prefix(['filter'], {
feature: 'css-filters',
browsers: browsers
});
});
// filter() function
f(require('caniuse-lite/data/features/css-filter-function.js'), function (browsers) {
return prefix(['filter-function'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
feature: 'css-filter-function',
browsers: browsers
});
});
// Backdrop-filter
f(require('caniuse-lite/data/features/css-backdrop-filter.js'), function (browsers) {
return prefix(['backdrop-filter'], {
feature: 'css-backdrop-filter',
browsers: browsers
});
});
// element() function
f(require('caniuse-lite/data/features/css-element-function.js'), function (browsers) {
return prefix(['element'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
feature: 'css-element-function',
browsers: browsers
});
});
// Multicolumns
f(require('caniuse-lite/data/features/multicolumn.js'), function (browsers) {
prefix(['columns', 'column-width', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width'], {
feature: 'multicolumn',
browsers: browsers
});
prefix(['column-count', 'column-rule-style', 'column-span', 'column-fill', 'break-before', 'break-after', 'break-inside'], {
feature: 'multicolumn',
browsers: browsers
});
});
// User select
f(require('caniuse-lite/data/features/user-select-none.js'), function (browsers) {
return prefix(['user-select'], {
mistakes: ['-khtml-'],
feature: 'user-select-none',
browsers: browsers
});
});
// Flexible Box Layout
var flexbox = require('caniuse-lite/data/features/flexbox.js');
f(flexbox, { match: /a\sx/ }, function (browsers) {
browsers = browsers.map(function (i) {
if (/ie|firefox/.test(i)) {
return i;
} else {
return i + ' 2009';
}
});
prefix(['display-flex', 'inline-flex'], {
props: ['display'],
feature: 'flexbox',
browsers: browsers
});
prefix(['flex', 'flex-grow', 'flex-shrink', 'flex-basis'], {
feature: 'flexbox',
browsers: browsers
});
prefix(['flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content'], {
feature: 'flexbox',
browsers: browsers
});
});
f(flexbox, { match: /y\sx/ }, function (browsers) {
add(['display-flex', 'inline-flex'], {
feature: 'flexbox',
browsers: browsers
});
add(['flex', 'flex-grow', 'flex-shrink', 'flex-basis'], {
feature: 'flexbox',
browsers: browsers
});
add(['flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content'], {
feature: 'flexbox',
browsers: browsers
});
});
// calc() unit
f(require('caniuse-lite/data/features/calc.js'), function (browsers) {
return prefix(['calc'], {
props: ['*'],
feature: 'calc',
browsers: browsers
});
});
// Background options
f(require('caniuse-lite/data/features/background-img-opts.js'), function (browsers) {
return prefix(['background-clip', 'background-origin', 'background-size'], {
feature: 'background-img-opts',
browsers: browsers
});
});
// Font feature settings
f(require('caniuse-lite/data/features/font-feature.js'), function (browsers) {
return prefix(['font-feature-settings', 'font-variant-ligatures', 'font-language-override'], {
feature: 'font-feature',
browsers: browsers
});
});
// CSS font-kerning property
f(require('caniuse-lite/data/features/font-kerning.js'), function (browsers) {
return prefix(['font-kerning'], {
feature: 'font-kerning',
browsers: browsers
});
});
// Border image
f(require('caniuse-lite/data/features/border-image.js'), function (browsers) {
return prefix(['border-image'], {
feature: 'border-image',
browsers: browsers
});
});
// Selection selector
f(require('caniuse-lite/data/features/css-selection.js'), function (browsers) {
return prefix(['::selection'], {
selector: true,
feature: 'css-selection',
browsers: browsers
});
});
// Placeholder selector
f(require('caniuse-lite/data/features/css-placeholder.js'), function (browsers) {
browsers = browsers.map(function (i) {
var _i$split = i.split(' '),
name = _i$split[0],
version = _i$split[1];
if (name === 'firefox' && parseFloat(version) <= 18) {
return i + ' old';
} else {
return i;
}
});
prefix(['::placeholder'], {
selector: true,
feature: 'css-placeholder',
browsers: browsers
});
});
// Hyphenation
f(require('caniuse-lite/data/features/css-hyphens.js'), function (browsers) {
return prefix(['hyphens'], {
feature: 'css-hyphens',
browsers: browsers
});
});
// Fullscreen selector
var fullscreen = require('caniuse-lite/data/features/fullscreen.js');
f(fullscreen, function (browsers) {
return prefix([':fullscreen'], {
selector: true,
feature: 'fullscreen',
browsers: browsers
});
});
f(fullscreen, { match: /x(\s#2|$)/ }, function (browsers) {
return prefix(['::backdrop'], {
selector: true,
feature: 'fullscreen',
browsers: browsers
});
});
// Tab size
f(require('caniuse-lite/data/features/css3-tabsize.js'), function (browsers) {
return prefix(['tab-size'], {
feature: 'css3-tabsize',
browsers: browsers
});
});
// Intrinsic & extrinsic sizing
f(require('caniuse-lite/data/features/intrinsic-width.js'), function (browsers) {
return prefix(['max-content', 'min-content', 'fit-content', 'fill', 'fill-available', 'stretch'], {
props: ['width', 'min-width', 'max-width', 'height', 'min-height', 'max-height', 'inline-size', 'min-inline-size', 'max-inline-size', 'block-size', 'min-block-size', 'max-block-size', 'grid', 'grid-template', 'grid-template-rows', 'grid-template-columns', 'grid-auto-columns', 'grid-auto-rows'],
feature: 'intrinsic-width',
browsers: browsers
});
});
// Zoom cursors
f(require('caniuse-lite/data/features/css3-cursors-newer.js'), function (browsers) {
return prefix(['zoom-in', 'zoom-out'], {
props: ['cursor'],
feature: 'css3-cursors-newer',
browsers: browsers
});
});
// Grab cursors
f(require('caniuse-lite/data/features/css3-cursors-grab.js'), function (browsers) {
return prefix(['grab', 'grabbing'], {
props: ['cursor'],
feature: 'css3-cursors-grab',
browsers: browsers
});
});
// Sticky position
f(require('caniuse-lite/data/features/css-sticky.js'), function (browsers) {
return prefix(['sticky'], {
props: ['position'],
feature: 'css-sticky',
browsers: browsers
});
});
// Pointer Events
f(require('caniuse-lite/data/features/pointer.js'), function (browsers) {
return prefix(['touch-action'], {
feature: 'pointer',
browsers: browsers
});
});
// Text decoration
var decoration = require('caniuse-lite/data/features/text-decoration.js');
f(decoration, function (browsers) {
return prefix(['text-decoration-style', 'text-decoration-color', 'text-decoration-line', 'text-decoration'], {
feature: 'text-decoration',
browsers: browsers
});
});
f(decoration, { match: /x.*#[23]/ }, function (browsers) {
return prefix(['text-decoration-skip'], {
feature: 'text-decoration',
browsers: browsers
});
});
// Text Size Adjust
f(require('caniuse-lite/data/features/text-size-adjust.js'), function (browsers) {
return prefix(['text-size-adjust'], {
feature: 'text-size-adjust',
browsers: browsers
});
});
// CSS Masks
f(require('caniuse-lite/data/features/css-masks.js'), function (browsers) {
prefix(['mask-clip', 'mask-composite', 'mask-image', 'mask-origin', 'mask-repeat', 'mask-border-repeat', 'mask-border-source'], {
feature: 'css-masks',
browsers: browsers
});
prefix(['mask', 'mask-position', 'mask-size', 'mask-border', 'mask-border-outset', 'mask-border-width', 'mask-border-slice'], {
feature: 'css-masks',
browsers: browsers
});
});
// CSS clip-path property
f(require('caniuse-lite/data/features/css-clip-path.js'), function (browsers) {
return prefix(['clip-path'], {
feature: 'css-clip-path',
browsers: browsers
});
});
// Fragmented Borders and Backgrounds
f(require('caniuse-lite/data/features/css-boxdecorationbreak.js'), function (browsers) {
return prefix(['box-decoration-break'], {
feature: 'css-boxdecorationbreak',
browsers: browsers
});
});
// CSS3 object-fit/object-position
f(require('caniuse-lite/data/features/object-fit.js'), function (browsers) {
return prefix(['object-fit', 'object-position'], {
feature: 'object-fit',
browsers: browsers
});
});
// CSS Shapes
f(require('caniuse-lite/data/features/css-shapes.js'), function (browsers) {
return prefix(['shape-margin', 'shape-outside', 'shape-image-threshold'], {
feature: 'css-shapes',
browsers: browsers
});
});
// CSS3 text-overflow
f(require('caniuse-lite/data/features/text-overflow.js'), function (browsers) {
return prefix(['text-overflow'], {
feature: 'text-overflow',
browsers: browsers
});
});
// Viewport at-rule
f(require('caniuse-lite/data/features/css-deviceadaptation.js'), function (browsers) {
return prefix(['@viewport'], {
feature: 'css-deviceadaptation',
browsers: browsers
});
});
// Resolution Media Queries
var resolut = require('caniuse-lite/data/features/css-media-resolution.js');
f(resolut, { match: /( x($| )|a #3)/ }, function (browsers) {
return prefix(['@resolution'], {
feature: 'css-media-resolution',
browsers: browsers
});
});
// CSS text-align-last
f(require('caniuse-lite/data/features/css-text-align-last.js'), function (browsers) {
return prefix(['text-align-last'], {
feature: 'css-text-align-last',
browsers: browsers
});
});
// Crisp Edges Image Rendering Algorithm
var crispedges = require('caniuse-lite/data/features/css-crisp-edges.js');
f(crispedges, { match: /y x|a x #1/ }, function (browsers) {
return prefix(['pixelated'], {
props: ['image-rendering'],
feature: 'css-crisp-edges',
browsers: browsers
});
});
f(crispedges, { match: /a x #2/ }, function (browsers) {
return prefix(['image-rendering'], {
feature: 'css-crisp-edges',
browsers: browsers
});
});
// Logical Properties
var logicalProps = require('caniuse-lite/data/features/css-logical-props.js');
f(logicalProps, function (browsers) {
return prefix(['border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', 'padding-inline-start', 'padding-inline-end'], {
feature: 'css-logical-props',
browsers: browsers
});
});
f(logicalProps, { match: /x\s#2/ }, function (browsers) {
return prefix(['border-block-start', 'border-block-end', 'margin-block-start', 'margin-block-end', 'padding-block-start', 'padding-block-end'], {
feature: 'css-logical-props',
browsers: browsers
});
});
// CSS appearance
var appearance = require('caniuse-lite/data/features/css-appearance.js');
f(appearance, { match: /#2|x/ }, function (browsers) {
return prefix(['appearance'], {
feature: 'css-appearance',
browsers: browsers
});
});
// CSS Scroll snap points
f(require('caniuse-lite/data/features/css-snappoints.js'), function (browsers) {
return prefix(['scroll-snap-type', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scroll-snap-points-x', 'scroll-snap-points-y'], {
feature: 'css-snappoints',
browsers: browsers
});
});
// CSS Regions
f(require('caniuse-lite/data/features/css-regions.js'), function (browsers) {
return prefix(['flow-into', 'flow-from', 'region-fragment'], {
feature: 'css-regions',
browsers: browsers
});
});
// CSS image-set
f(require('caniuse-lite/data/features/css-image-set.js'), function (browsers) {
return prefix(['image-set'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
feature: 'css-image-set',
browsers: browsers
});
});
// Writing Mode
var writingMode = require('caniuse-lite/data/features/css-writing-mode.js');
f(writingMode, { match: /a|x/ }, function (browsers) {
return prefix(['writing-mode'], {
feature: 'css-writing-mode',
browsers: browsers
});
});
// Cross-Fade Function
f(require('caniuse-lite/data/features/css-cross-fade.js'), function (browsers) {
return prefix(['cross-fade'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
feature: 'css-cross-fade',
browsers: browsers
});
});
// Read Only selector
f(require('caniuse-lite/data/features/css-read-only-write.js'), function (browsers) {
return prefix([':read-only', ':read-write'], {
selector: true,
feature: 'css-read-only-write',
browsers: browsers
});
});
// Text Emphasize
f(require('caniuse-lite/data/features/text-emphasis.js'), function (browsers) {
return prefix(['text-emphasis', 'text-emphasis-position', 'text-emphasis-style', 'text-emphasis-color'], {
feature: 'text-emphasis',
browsers: browsers
});
});
// CSS Grid Layout
var grid = require('caniuse-lite/data/features/css-grid.js');
f(grid, function (browsers) {
prefix(['display-grid', 'inline-grid'], {
props: ['display'],
feature: 'css-grid',
browsers: browsers
});
prefix(['grid-template-columns', 'grid-template-rows', 'grid-row-start', 'grid-column-start', 'grid-row-end', 'grid-column-end', 'grid-row', 'grid-column'], {
feature: 'css-grid',
browsers: browsers
});
});
f(grid, { match: /a x/ }, function (browsers) {
return prefix(['grid-column-align', 'grid-row-align'], {
feature: 'css-grid',
browsers: browsers
});
});
// CSS text-spacing
f(require('caniuse-lite/data/features/css-text-spacing.js'), function (browsers) {
return prefix(['text-spacing'], {
feature: 'css-text-spacing',
browsers: browsers
});
});
// :any-link selector
f(require('caniuse-lite/data/features/css-any-link.js'), function (browsers) {
return prefix([':any-link'], {
selector: true,
feature: 'css-any-link',
browsers: browsers
});
});
// unicode-bidi
var bidi = require('caniuse-lite/data/features/css-unicode-bidi.js');
f(bidi, function (browsers) {
return prefix(['isolate'], {
props: ['unicode-bidi'],
feature: 'css-unicode-bidi',
browsers: browsers
});
});
f(bidi, { match: /y x|a x #2/ }, function (browsers) {
return prefix(['plaintext'], {
props: ['unicode-bidi'],
feature: 'css-unicode-bidi',
browsers: browsers
});
});
f(bidi, { match: /y x/ }, function (browsers) {
return prefix(['isolate-override'], {
props: ['unicode-bidi'],
feature: 'css-unicode-bidi',
browsers: browsers
});
});
},{"caniuse-lite":513,"caniuse-lite/data/features/background-img-opts.js":87,"caniuse-lite/data/features/border-image.js":95,"caniuse-lite/data/features/border-radius.js":96,"caniuse-lite/data/features/calc.js":99,"caniuse-lite/data/features/css-animation.js":120,"caniuse-lite/data/features/css-any-link.js":121,"caniuse-lite/data/features/css-appearance.js":122,"caniuse-lite/data/features/css-backdrop-filter.js":125,"caniuse-lite/data/features/css-boxdecorationbreak.js":128,"caniuse-lite/data/features/css-boxshadow.js":129,"caniuse-lite/data/features/css-clip-path.js":132,"caniuse-lite/data/features/css-crisp-edges.js":135,"caniuse-lite/data/features/css-cross-fade.js":136,"caniuse-lite/data/features/css-deviceadaptation.js":139,"caniuse-lite/data/features/css-element-function.js":142,"caniuse-lite/data/features/css-filter-function.js":145,"caniuse-lite/data/features/css-filters.js":146,"caniuse-lite/data/features/css-gradients.js":154,"caniuse-lite/data/features/css-grid.js":155,"caniuse-lite/data/features/css-hyphens.js":159,"caniuse-lite/data/features/css-image-set.js":161,"caniuse-lite/data/features/css-logical-props.js":168,"caniuse-lite/data/features/css-masks.js":170,"caniuse-lite/data/features/css-media-resolution.js":173,"caniuse-lite/data/features/css-placeholder.js":187,"caniuse-lite/data/features/css-read-only-write.js":188,"caniuse-lite/data/features/css-regions.js":191,"caniuse-lite/data/features/css-selection.js":200,"caniuse-lite/data/features/css-shapes.js":201,"caniuse-lite/data/features/css-snappoints.js":202,"caniuse-lite/data/features/css-sticky.js":203,"caniuse-lite/data/features/css-text-align-last.js":206,"caniuse-lite/data/features/css-text-spacing.js":210,"caniuse-lite/data/features/css-transitions.js":214,"caniuse-lite/data/features/css-unicode-bidi.js":215,"caniuse-lite/data/features/css-writing-mode.js":219,"caniuse-lite/data/features/css3-boxsizing.js":222,"caniuse-lite/data/features/css3-cursors-grab.js":224,"caniuse-lite/data/features/css3-cursors-newer.js":225,"caniuse-lite/data/features/css3-tabsize.js":227,"caniuse-lite/data/features/flexbox.js":267,"caniuse-lite/data/features/font-feature.js":270,"caniuse-lite/data/features/font-kerning.js":271,"caniuse-lite/data/features/fullscreen.js":282,"caniuse-lite/data/features/intrinsic-width.js":330,"caniuse-lite/data/features/multicolumn.js":367,"caniuse-lite/data/features/object-fit.js":376,"caniuse-lite/data/features/pointer.js":397,"caniuse-lite/data/features/text-decoration.js":459,"caniuse-lite/data/features/text-emphasis.js":460,"caniuse-lite/data/features/text-overflow.js":461,"caniuse-lite/data/features/text-size-adjust.js":462,"caniuse-lite/data/features/transforms2d.js":471,"caniuse-lite/data/features/transforms3d.js":472,"caniuse-lite/data/features/user-select-none.js":480}],2:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Prefixer = require('./prefixer');
var AtRule = function (_Prefixer) {
_inherits(AtRule, _Prefixer);
function AtRule() {
_classCallCheck(this, AtRule);
return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments));
}
/**
* Clone and add prefixes for at-rule
*/
AtRule.prototype.add = function add(rule, prefix) {
var prefixed = prefix + rule.name;
var already = rule.parent.some(function (i) {
return i.name === prefixed && i.params === rule.params;
});
if (already) {
return undefined;
}
var cloned = this.clone(rule, { name: prefixed });
return rule.parent.insertBefore(rule, cloned);
};
/**
* Clone node with prefixes
*/
AtRule.prototype.process = function process(node) {
var parent = this.parentPrefix(node);
for (var _iterator = this.prefixes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prefix = _ref;
if (!parent || parent === prefix) {
this.add(node, prefix);
}
}
};
return AtRule;
}(Prefixer);
module.exports = AtRule;
},{"./prefixer":53}],3:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var browserslist = require('browserslist');
var postcss = require('postcss');
var Browsers = require('./browsers');
var Prefixes = require('./prefixes');
function isPlainObject(obj) {
return Object.prototype.toString.apply(obj) === '[object Object]';
}
var cache = {};
function timeCapsule(result, prefixes) {
if (prefixes.browsers.selected.length === 0) {
return;
}
if (prefixes.add.selectors.length > 0) {
return;
}
if (Object.keys(prefixes.add).length > 2) {
return;
}
result.warn('Greetings, time traveller. ' + 'We are in the golden age of prefix-less CSS, ' + 'where Autoprefixer is no longer needed for your stylesheet.');
}
module.exports = postcss.plugin('autoprefixer', function () {
for (var _len = arguments.length, reqs = Array(_len), _key = 0; _key < _len; _key++) {
reqs[_key] = arguments[_key];
}
var options = void 0;
if (reqs.length === 1 && isPlainObject(reqs[0])) {
options = reqs[0];
reqs = undefined;
} else if (reqs.length === 0 || reqs.length === 1 && !reqs[0]) {
reqs = undefined;
} else if (reqs.length <= 2 && (reqs[0] instanceof Array || !reqs[0])) {
options = reqs[1];
reqs = reqs[0];
} else if (_typeof(reqs[reqs.length - 1]) === 'object') {
options = reqs.pop();
}
if (!options) {
options = {};
}
if (options.browser) {
throw new Error('Change `browser` option to `browsers` in Autoprefixer');
}
if (options.browsers) {
reqs = options.browsers;
}
if (typeof options.grid === 'undefined') {
options.grid = false;
}
var loadPrefixes = function loadPrefixes(opts) {
var data = module.exports.data;
var browsers = new Browsers(data.browsers, reqs, opts, options.stats);
var key = browsers.selected.join(', ') + JSON.stringify(options);
if (!cache[key]) {
cache[key] = new Prefixes(data.prefixes, browsers, options);
}
return cache[key];
};
var plugin = function plugin(css, result) {
var prefixes = loadPrefixes({
from: css.source && css.source.input.file,
env: options.env
});
timeCapsule(result, prefixes);
if (options.remove !== false) {
prefixes.processor.remove(css);
}
if (options.add !== false) {
prefixes.processor.add(css, result);
}
};
plugin.options = options;
plugin.info = function (opts) {
return require('./info')(loadPrefixes(opts));
};
return plugin;
});
/**
* Autoprefixer data
*/
module.exports.data = {
browsers: require('caniuse-lite').agents,
prefixes: require('../data/prefixes')
};
/**
* Autoprefixer default browsers
*/
module.exports.defaults = browserslist.defaults;
/**
* Inspect with default Autoprefixer
*/
module.exports.info = function () {
return module.exports().info();
};
},{"../data/prefixes":1,"./browsers":5,"./info":50,"./prefixes":54,"browserslist":65,"caniuse-lite":513,"postcss":541}],4:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var last = function last(array) {
return array[array.length - 1];
};
var brackets = {
/**
* Parse string to nodes tree
*/
parse: function parse(str) {
var current = [''];
var stack = [current];
for (var i = 0; i < str.length; i++) {
var sym = str[i];
if (sym === '(') {
current = [''];
last(stack).push(current);
stack.push(current);
} else if (sym === ')') {
stack.pop();
current = last(stack);
current.push('');
} else {
current[current.length - 1] += sym;
}
}
return stack[0];
},
/**
* Generate output string by nodes tree
*/
stringify: function stringify(ast) {
var result = '';
for (var _iterator = ast, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object') {
result += '(' + brackets.stringify(i) + ')';
} else {
result += i;
}
}
return result;
}
};
module.exports = brackets;
},{}],5:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var browserslist = require('browserslist');
var utils = require('./utils');
var Browsers = function () {
/**
* Return all prefixes for default browser data
*/
Browsers.prefixes = function prefixes() {
if (this.prefixesCache) {
return this.prefixesCache;
}
var data = require('caniuse-lite').agents;
this.prefixesCache = [];
for (var name in data) {
this.prefixesCache.push('-' + data[name].prefix + '-');
}
this.prefixesCache = utils.uniq(this.prefixesCache).sort(function (a, b) {
return b.length - a.length;
});
return this.prefixesCache;
};
/**
* Check is value contain any possibe prefix
*/
Browsers.withPrefix = function withPrefix(value) {
if (!this.prefixesRegexp) {
this.prefixesRegexp = new RegExp(this.prefixes().join('|'));
}
return this.prefixesRegexp.test(value);
};
function Browsers(data, requirements, options, stats) {
_classCallCheck(this, Browsers);
this.data = data;
this.options = options || {};
this.stats = stats;
this.selected = this.parse(requirements);
}
/**
* Return browsers selected by requirements
*/
Browsers.prototype.parse = function parse(requirements) {
return browserslist(requirements, {
stats: this.stats,
path: this.options.from,
env: this.options.env
});
};
/**
* Select major browsers versions by criteria
*/
Browsers.prototype.browsers = function browsers(criteria) {
var _this = this;
var selected = [];
var _loop = function _loop(browser) {
var data = _this.data[browser];
var versions = criteria(data).map(function (version) {
return browser + ' ' + version;
});
selected = selected.concat(versions);
};
for (var browser in this.data) {
_loop(browser);
}
return selected;
};
/**
* Return prefix for selected browser
*/
Browsers.prototype.prefix = function prefix(browser) {
var _browser$split = browser.split(' '),
name = _browser$split[0],
version = _browser$split[1];
var data = this.data[name];
var prefix = data.prefix_exceptions && data.prefix_exceptions[version];
if (!prefix) {
prefix = data.prefix;
}
return '-' + prefix + '-';
};
/**
* Is browser is selected by requirements
*/
Browsers.prototype.isSelected = function isSelected(browser) {
return this.selected.indexOf(browser) !== -1;
};
return Browsers;
}();
module.exports = Browsers;
},{"./utils":60,"browserslist":65,"caniuse-lite":513}],6:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Prefixer = require('./prefixer');
var Browsers = require('./browsers');
var utils = require('./utils');
var Declaration = function (_Prefixer) {
_inherits(Declaration, _Prefixer);
function Declaration() {
_classCallCheck(this, Declaration);
return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments));
}
/**
* Always true, because we already get prefixer by property name
*/
Declaration.prototype.check = function check() /* decl */{
return true;
};
/**
* Return prefixed version of property
*/
Declaration.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + prop;
};
/**
* Return unprefixed version of property
*/
Declaration.prototype.normalize = function normalize(prop) {
return prop;
};
/**
* Check `value`, that it contain other prefixes, rather than `prefix`
*/
Declaration.prototype.otherPrefixes = function otherPrefixes(value, prefix) {
for (var _iterator = Browsers.prefixes(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var other = _ref;
if (other === prefix) {
continue;
}
if (value.indexOf(other) !== -1) {
return true;
}
}
return false;
};
/**
* Set prefix to declaration
*/
Declaration.prototype.set = function set(decl, prefix) {
decl.prop = this.prefixed(decl.prop, prefix);
return decl;
};
/**
* Should we use visual cascade for prefixes
*/
Declaration.prototype.needCascade = function needCascade(decl) {
if (!decl._autoprefixerCascade) {
decl._autoprefixerCascade = this.all.options.cascade !== false && decl.raw('before').indexOf('\n') !== -1;
}
return decl._autoprefixerCascade;
};
/**
* Return maximum length of possible prefixed property
*/
Declaration.prototype.maxPrefixed = function maxPrefixed(prefixes, decl) {
if (decl._autoprefixerMax) {
return decl._autoprefixerMax;
}
var max = 0;
for (var _iterator2 = prefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var prefix = _ref2;
prefix = utils.removeNote(prefix);
if (prefix.length > max) {
max = prefix.length;
}
}
decl._autoprefixerMax = max;
return decl._autoprefixerMax;
};
/**
* Calculate indentation to create visual cascade
*/
Declaration.prototype.calcBefore = function calcBefore(prefixes, decl) {
var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
var max = this.maxPrefixed(prefixes, decl);
var diff = max - utils.removeNote(prefix).length;
var before = decl.raw('before');
before += Array(diff).fill(' ').join('');
return before;
};
/**
* Remove visual cascade
*/
Declaration.prototype.restoreBefore = function restoreBefore(decl) {
var lines = decl.raw('before').split('\n');
var min = lines[lines.length - 1];
this.all.group(decl).up(function (prefixed) {
var array = prefixed.raw('before').split('\n');
var last = array[array.length - 1];
if (last.length < min.length) {
min = last;
}
});
lines[lines.length - 1] = min;
decl.raws.before = lines.join('\n');
};
/**
* Clone and insert new declaration
*/
Declaration.prototype.insert = function insert(decl, prefix, prefixes) {
var cloned = this.set(this.clone(decl), prefix);
if (!cloned) return undefined;
var already = decl.parent.some(function (i) {
return i.prop === cloned.prop && i.value === cloned.value;
});
if (already) {
return undefined;
}
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
return decl.parent.insertBefore(decl, cloned);
};
/**
* Did this declaration has this prefix above
*/
Declaration.prototype.isAlready = function isAlready(decl, prefixed) {
var already = this.all.group(decl).up(function (i) {
return i.prop === prefixed;
});
if (!already) {
already = this.all.group(decl).down(function (i) {
return i.prop === prefixed;
});
}
return already;
};
/**
* Clone and add prefixes for declaration
*/
Declaration.prototype.add = function add(decl, prefix, prefixes) {
var prefixed = this.prefixed(decl.prop, prefix);
if (this.isAlready(decl, prefixed) || this.otherPrefixes(decl.value, prefix)) {
return undefined;
}
return this.insert(decl, prefix, prefixes);
};
/**
* Add spaces for visual cascade
*/
Declaration.prototype.process = function process(decl) {
if (this.needCascade(decl)) {
var prefixes = _Prefixer.prototype.process.call(this, decl);
if (prefixes && prefixes.length) {
this.restoreBefore(decl);
decl.raws.before = this.calcBefore(prefixes, decl);
}
} else {
_Prefixer.prototype.process.call(this, decl);
}
};
/**
* Return list of prefixed properties to clean old prefixes
*/
Declaration.prototype.old = function old(prop, prefix) {
return [this.prefixed(prop, prefix)];
};
return Declaration;
}(Prefixer);
module.exports = Declaration;
},{"./browsers":5,"./prefixer":53,"./utils":60}],7:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var AlignContent = function (_Declaration) {
_inherits(AlignContent, _Declaration);
function AlignContent() {
_classCallCheck(this, AlignContent);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2012 spec
*/
AlignContent.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2012) {
return prefix + 'flex-line-pack';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
AlignContent.prototype.normalize = function normalize() {
return 'align-content';
};
/**
* Change value for 2012 spec and ignore prefix for 2009
*/
AlignContent.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2012) {
decl.value = AlignContent.oldValues[decl.value] || decl.value;
return _Declaration.prototype.set.call(this, decl, prefix);
} else if (spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return AlignContent;
}(Declaration);
Object.defineProperty(AlignContent, 'names', {
enumerable: true,
writable: true,
value: ['align-content', 'flex-line-pack']
});
Object.defineProperty(AlignContent, 'oldValues', {
enumerable: true,
writable: true,
value: {
'flex-end': 'end',
'flex-start': 'start',
'space-between': 'justify',
'space-around': 'distribute'
}
});
module.exports = AlignContent;
},{"../declaration":6,"./flex-spec":26}],8:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var AlignItems = function (_Declaration) {
_inherits(AlignItems, _Declaration);
function AlignItems() {
_classCallCheck(this, AlignItems);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 and 2012 specs
*/
AlignItems.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-align';
} else if (spec === 2012) {
return prefix + 'flex-align';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
AlignItems.prototype.normalize = function normalize() {
return 'align-items';
};
/**
* Change value for 2009 and 2012 specs
*/
AlignItems.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009 || spec === 2012) {
decl.value = AlignItems.oldValues[decl.value] || decl.value;
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return AlignItems;
}(Declaration);
Object.defineProperty(AlignItems, 'names', {
enumerable: true,
writable: true,
value: ['align-items', 'flex-align', 'box-align']
});
Object.defineProperty(AlignItems, 'oldValues', {
enumerable: true,
writable: true,
value: {
'flex-end': 'end',
'flex-start': 'start'
}
});
module.exports = AlignItems;
},{"../declaration":6,"./flex-spec":26}],9:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var AlignSelf = function (_Declaration) {
_inherits(AlignSelf, _Declaration);
function AlignSelf() {
_classCallCheck(this, AlignSelf);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2012 specs
*/
AlignSelf.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2012) {
return prefix + 'flex-item-align';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
AlignSelf.prototype.normalize = function normalize() {
return 'align-self';
};
/**
* Change value for 2012 spec and ignore prefix for 2009
*/
AlignSelf.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2012) {
decl.value = AlignSelf.oldValues[decl.value] || decl.value;
return _Declaration.prototype.set.call(this, decl, prefix);
} else if (spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return AlignSelf;
}(Declaration);
Object.defineProperty(AlignSelf, 'names', {
enumerable: true,
writable: true,
value: ['align-self', 'flex-item-align']
});
Object.defineProperty(AlignSelf, 'oldValues', {
enumerable: true,
writable: true,
value: {
'flex-end': 'end',
'flex-start': 'start'
}
});
module.exports = AlignSelf;
},{"../declaration":6,"./flex-spec":26}],10:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var utils = require('../utils');
var Appearance = function (_Declaration) {
_inherits(Appearance, _Declaration);
function Appearance(name, prefixes, all) {
_classCallCheck(this, Appearance);
var _this = _possibleConstructorReturn(this, _Declaration.call(this, name, prefixes, all));
if (_this.prefixes) {
_this.prefixes = utils.uniq(_this.prefixes.map(function (i) {
if (i === '-ms-') {
return '-webkit-';
} else {
return i;
}
}));
}
return _this;
}
return Appearance;
}(Declaration);
Object.defineProperty(Appearance, 'names', {
enumerable: true,
writable: true,
value: ['appearance']
});
module.exports = Appearance;
},{"../declaration":6,"../utils":60}],11:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BackgroundSize = function (_Declaration) {
_inherits(BackgroundSize, _Declaration);
function BackgroundSize() {
_classCallCheck(this, BackgroundSize);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Duplication parameter for -webkit- browsers
*/
BackgroundSize.prototype.set = function set(decl, prefix) {
var value = decl.value.toLowerCase();
if (prefix === '-webkit-' && value.indexOf(' ') === -1 && value !== 'contain' && value !== 'cover') {
decl.value = decl.value + ' ' + decl.value;
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return BackgroundSize;
}(Declaration);
Object.defineProperty(BackgroundSize, 'names', {
enumerable: true,
writable: true,
value: ['background-size']
});
module.exports = BackgroundSize;
},{"../declaration":6}],12:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BlockLogical = function (_Declaration) {
_inherits(BlockLogical, _Declaration);
function BlockLogical() {
_classCallCheck(this, BlockLogical);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Use old syntax for -moz- and -webkit-
*/
BlockLogical.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + (prop.indexOf('-start') !== -1 ? prop.replace('-block-start', '-before') : prop.replace('-block-end', '-after'));
};
/**
* Return property name by spec
*/
BlockLogical.prototype.normalize = function normalize(prop) {
if (prop.indexOf('-before') !== -1) {
return prop.replace('-before', '-block-start');
} else {
return prop.replace('-after', '-block-end');
}
};
return BlockLogical;
}(Declaration);
Object.defineProperty(BlockLogical, 'names', {
enumerable: true,
writable: true,
value: ['border-block-start', 'border-block-end', 'margin-block-start', 'margin-block-end', 'padding-block-start', 'padding-block-end', 'border-before', 'border-after', 'margin-before', 'margin-after', 'padding-before', 'padding-after']
});
module.exports = BlockLogical;
},{"../declaration":6}],13:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BorderImage = function (_Declaration) {
_inherits(BorderImage, _Declaration);
function BorderImage() {
_classCallCheck(this, BorderImage);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Remove fill parameter for prefixed declarations
*/
BorderImage.prototype.set = function set(decl, prefix) {
decl.value = decl.value.replace(/\s+fill(\s)/, '$1');
return _Declaration.prototype.set.call(this, decl, prefix);
};
return BorderImage;
}(Declaration);
Object.defineProperty(BorderImage, 'names', {
enumerable: true,
writable: true,
value: ['border-image']
});
module.exports = BorderImage;
},{"../declaration":6}],14:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BorderRadius = function (_Declaration) {
_inherits(BorderRadius, _Declaration);
function BorderRadius() {
_classCallCheck(this, BorderRadius);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change syntax, when add Mozilla prefix
*/
BorderRadius.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-moz-') {
return prefix + (BorderRadius.toMozilla[prop] || prop);
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return unprefixed version of property
*/
BorderRadius.prototype.normalize = function normalize(prop) {
return BorderRadius.toNormal[prop] || prop;
};
return BorderRadius;
}(Declaration);
Object.defineProperty(BorderRadius, 'names', {
enumerable: true,
writable: true,
value: ['border-radius']
});
Object.defineProperty(BorderRadius, 'toMozilla', {
enumerable: true,
writable: true,
value: {}
});
Object.defineProperty(BorderRadius, 'toNormal', {
enumerable: true,
writable: true,
value: {}
});
var _arr = ['top', 'bottom'];
for (var _i = 0; _i < _arr.length; _i++) {
var ver = _arr[_i];var _arr2 = ['left', 'right'];
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var hor = _arr2[_i2];
var normal = 'border-' + ver + '-' + hor + '-radius';
var mozilla = 'border-radius-' + ver + hor;
BorderRadius.names.push(normal);
BorderRadius.names.push(mozilla);
BorderRadius.toMozilla[normal] = mozilla;
BorderRadius.toNormal[mozilla] = normal;
}
}
module.exports = BorderRadius;
},{"../declaration":6}],15:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BreakProps = function (_Declaration) {
_inherits(BreakProps, _Declaration);
function BreakProps() {
_classCallCheck(this, BreakProps);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change name for -webkit- and -moz- prefix
*/
BreakProps.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-webkit-') {
return '-webkit-column-' + prop;
} else if (prefix === '-moz-') {
return 'page-' + prop;
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
BreakProps.prototype.normalize = function normalize(prop) {
if (prop.indexOf('inside') !== -1) {
return 'break-inside';
} else if (prop.indexOf('before') !== -1) {
return 'break-before';
} else if (prop.indexOf('after') !== -1) {
return 'break-after';
}
return undefined;
};
/**
* Change prefixed value for avoid-column and avoid-page
*/
BreakProps.prototype.set = function set(decl, prefix) {
var v = decl.value;
if (decl.prop === 'break-inside' && v === 'avoid-column' || v === 'avoid-page') {
decl.value = 'avoid';
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
/**
* Don’t prefix some values
*/
BreakProps.prototype.insert = function insert(decl, prefix, prefixes) {
if (decl.prop !== 'break-inside') {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
} else if (decl.value === 'avoid-region') {
return undefined;
} else if (decl.value === 'avoid-page' && prefix === '-webkit-') {
return undefined;
} else {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
}
};
return BreakProps;
}(Declaration);
Object.defineProperty(BreakProps, 'names', {
enumerable: true,
writable: true,
value: ['break-inside', 'page-break-inside', 'column-break-inside', 'break-before', 'page-break-before', 'column-break-before', 'break-after', 'page-break-after', 'column-break-after']
});
module.exports = BreakProps;
},{"../declaration":6}],16:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Value = require('../value');
var list = require('postcss/lib/list');
var CrossFade = function (_Value) {
_inherits(CrossFade, _Value);
function CrossFade() {
_classCallCheck(this, CrossFade);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
CrossFade.prototype.replace = function replace(string, prefix) {
var _this2 = this;
return list.space(string).map(function (value) {
if (value.slice(0, +_this2.name.length + 1) !== _this2.name + '(') {
return value;
}
var close = value.lastIndexOf(')');
var after = value.slice(close + 1);
var args = value.slice(_this2.name.length + 1, close);
if (prefix === '-webkit-') {
var match = args.match(/\d*.?\d+%?/);
if (match) {
args = args.slice(match[0].length).trim();
args += ', ' + match[0];
} else {
args += ', 0.5';
}
}
return prefix + _this2.name + '(' + args + ')' + after;
}).join(' ');
};
return CrossFade;
}(Value);
Object.defineProperty(CrossFade, 'names', {
enumerable: true,
writable: true,
value: ['cross-fade']
});
module.exports = CrossFade;
},{"../value":61,"postcss/lib/list":536}],17:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var OldValue = require('../old-value');
var Value = require('../value');
var DisplayFlex = function (_Value) {
_inherits(DisplayFlex, _Value);
function DisplayFlex(name, prefixes) {
_classCallCheck(this, DisplayFlex);
var _this = _possibleConstructorReturn(this, _Value.call(this, name, prefixes));
if (name === 'display-flex') {
_this.name = 'flex';
}
return _this;
}
/**
* Faster check for flex value
*/
DisplayFlex.prototype.check = function check(decl) {
return decl.prop === 'display' && decl.value === this.name;
};
/**
* Return value by spec
*/
DisplayFlex.prototype.prefixed = function prefixed(prefix) {
var spec = void 0,
value = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
if (this.name === 'flex') {
value = 'box';
} else {
value = 'inline-box';
}
} else if (spec === 2012) {
if (this.name === 'flex') {
value = 'flexbox';
} else {
value = 'inline-flexbox';
}
} else if (spec === 'final') {
value = this.name;
}
return prefix + value;
};
/**
* Add prefix to value depend on flebox spec version
*/
DisplayFlex.prototype.replace = function replace(string, prefix) {
return this.prefixed(prefix);
};
/**
* Change value for old specs
*/
DisplayFlex.prototype.old = function old(prefix) {
var prefixed = this.prefixed(prefix);
if (prefixed) {
return new OldValue(this.name, prefixed);
}
return undefined;
};
return DisplayFlex;
}(Value);
Object.defineProperty(DisplayFlex, 'names', {
enumerable: true,
writable: true,
value: ['display-flex', 'inline-flex']
});
module.exports = DisplayFlex;
},{"../old-value":52,"../value":61,"./flex-spec":26}],18:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Value = require('../value');
var DisplayGrid = function (_Value) {
_inherits(DisplayGrid, _Value);
function DisplayGrid(name, prefixes) {
_classCallCheck(this, DisplayGrid);
var _this = _possibleConstructorReturn(this, _Value.call(this, name, prefixes));
if (name === 'display-grid') {
_this.name = 'grid';
}
return _this;
}
/**
* Faster check for flex value
*/
DisplayGrid.prototype.check = function check(decl) {
return decl.prop === 'display' && decl.value === this.name;
};
return DisplayGrid;
}(Value);
Object.defineProperty(DisplayGrid, 'names', {
enumerable: true,
writable: true,
value: ['display-grid', 'inline-grid']
});
module.exports = DisplayGrid;
},{"../value":61}],19:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
var utils = require('../utils');
var OldFilterValue = function (_OldValue) {
_inherits(OldFilterValue, _OldValue);
function OldFilterValue() {
_classCallCheck(this, OldFilterValue);
return _possibleConstructorReturn(this, _OldValue.apply(this, arguments));
}
/**
* Clean -webkit-filter from properties list
*/
OldFilterValue.prototype.clean = function clean(decl) {
var _this2 = this;
decl.value = utils.editList(decl.value, function (props) {
if (props.every(function (i) {
return i.indexOf(_this2.unprefixed) !== 0;
})) {
return props;
}
return props.filter(function (i) {
return i.indexOf(_this2.prefixed) === -1;
});
});
};
return OldFilterValue;
}(OldValue);
var FilterValue = function (_Value) {
_inherits(FilterValue, _Value);
function FilterValue(name, prefixes) {
_classCallCheck(this, FilterValue);
var _this3 = _possibleConstructorReturn(this, _Value.call(this, name, prefixes));
if (name === 'filter-function') {
_this3.name = 'filter';
}
return _this3;
}
/**
* Use prefixed and unprefixed filter for WebKit
*/
FilterValue.prototype.replace = function replace(value, prefix) {
if (prefix === '-webkit-' && value.indexOf('filter(') === -1) {
if (value.indexOf('-webkit-filter') === -1) {
return _Value.prototype.replace.call(this, value, prefix) + ', ' + value;
} else {
return value;
}
} else {
return _Value.prototype.replace.call(this, value, prefix);
}
};
/**
* Clean -webkit-filter
*/
FilterValue.prototype.old = function old(prefix) {
return new OldFilterValue(this.name, prefix + this.name);
};
return FilterValue;
}(Value);
Object.defineProperty(FilterValue, 'names', {
enumerable: true,
writable: true,
value: ['filter', 'filter-function']
});
module.exports = FilterValue;
},{"../old-value":52,"../utils":60,"../value":61}],20:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var Filter = function (_Declaration) {
_inherits(Filter, _Declaration);
function Filter() {
_classCallCheck(this, Filter);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Check is it Internet Explorer filter
*/
Filter.prototype.check = function check(decl) {
var v = decl.value;
return v.toLowerCase().indexOf('alpha(') === -1 && v.indexOf('DXImageTransform.Microsoft') === -1 && v.indexOf('data:image/svg+xml') === -1;
};
return Filter;
}(Declaration);
Object.defineProperty(Filter, 'names', {
enumerable: true,
writable: true,
value: ['filter']
});
module.exports = Filter;
},{"../declaration":6}],21:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexBasis = function (_Declaration) {
_inherits(FlexBasis, _Declaration);
function FlexBasis() {
_classCallCheck(this, FlexBasis);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
FlexBasis.prototype.normalize = function normalize() {
return 'flex-basis';
};
/**
* Return flex property for 2012 spec
*/
FlexBasis.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2012) {
return prefix + 'flex-preferred-size';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Ignore 2009 spec and use flex property for 2012
*/
FlexBasis.prototype.set = function set(decl, prefix) {
var spec = void 0;
var _flexSpec2 = flexSpec(prefix);
spec = _flexSpec2[0];
prefix = _flexSpec2[1];
if (spec === 2012 || spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return FlexBasis;
}(Declaration);
Object.defineProperty(FlexBasis, 'names', {
enumerable: true,
writable: true,
value: ['flex-basis', 'flex-preferred-size']
});
module.exports = FlexBasis;
},{"../declaration":6,"./flex-spec":26}],22:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexDirection = function (_Declaration) {
_inherits(FlexDirection, _Declaration);
function FlexDirection() {
_classCallCheck(this, FlexDirection);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
FlexDirection.prototype.normalize = function normalize() {
return 'flex-direction';
};
/**
* Use two properties for 2009 spec
*/
FlexDirection.prototype.insert = function insert(decl, prefix, prefixes) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec !== 2009) {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
} else {
var already = decl.parent.some(function (i) {
return i.prop === prefix + 'box-orient' || i.prop === prefix + 'box-direction';
});
if (already) {
return undefined;
}
var value = decl.value;
var orient = value.indexOf('row') !== -1 ? 'horizontal' : 'vertical';
var dir = value.indexOf('reverse') !== -1 ? 'reverse' : 'normal';
var cloned = this.clone(decl);
cloned.prop = prefix + 'box-orient';
cloned.value = orient;
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
decl.parent.insertBefore(decl, cloned);
cloned = this.clone(decl);
cloned.prop = prefix + 'box-direction';
cloned.value = dir;
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
return decl.parent.insertBefore(decl, cloned);
}
};
/**
* Clean two properties for 2009 spec
*/
FlexDirection.prototype.old = function old(prop, prefix) {
var spec = void 0;
var _flexSpec2 = flexSpec(prefix);
spec = _flexSpec2[0];
prefix = _flexSpec2[1];
if (spec === 2009) {
return [prefix + 'box-orient', prefix + 'box-direction'];
} else {
return _Declaration.prototype.old.call(this, prop, prefix);
}
};
return FlexDirection;
}(Declaration);
Object.defineProperty(FlexDirection, 'names', {
enumerable: true,
writable: true,
value: ['flex-direction', 'box-direction', 'box-orient']
});
module.exports = FlexDirection;
},{"../declaration":6,"./flex-spec":26}],23:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexFlow = function (_Declaration) {
_inherits(FlexFlow, _Declaration);
function FlexFlow() {
_classCallCheck(this, FlexFlow);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Use two properties for 2009 spec
*/
FlexFlow.prototype.insert = function insert(decl, prefix, prefixes) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec !== 2009) {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
} else {
var values = decl.value.split(/\s+/).filter(function (i) {
return i !== 'wrap' && i !== 'nowrap' && 'wrap-reverse';
});
if (values.length === 0) {
return undefined;
}
var already = decl.parent.some(function (i) {
return i.prop === prefix + 'box-orient' || i.prop === prefix + 'box-direction';
});
if (already) {
return undefined;
}
var value = values[0];
var orient = value.indexOf('row') !== -1 ? 'horizontal' : 'vertical';
var dir = value.indexOf('reverse') !== -1 ? 'reverse' : 'normal';
var cloned = this.clone(decl);
cloned.prop = prefix + 'box-orient';
cloned.value = orient;
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
decl.parent.insertBefore(decl, cloned);
cloned = this.clone(decl);
cloned.prop = prefix + 'box-direction';
cloned.value = dir;
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
return decl.parent.insertBefore(decl, cloned);
}
};
return FlexFlow;
}(Declaration);
Object.defineProperty(FlexFlow, 'names', {
enumerable: true,
writable: true,
value: ['flex-flow', 'box-direction', 'box-orient']
});
module.exports = FlexFlow;
},{"../declaration":6,"./flex-spec":26}],24:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var Flex = function (_Declaration) {
_inherits(Flex, _Declaration);
function Flex() {
_classCallCheck(this, Flex);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
Flex.prototype.normalize = function normalize() {
return 'flex';
};
/**
* Return flex property for 2009 and 2012 specs
*/
Flex.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-flex';
} else if (spec === 2012) {
return prefix + 'flex-positive';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
return Flex;
}(Declaration);
Object.defineProperty(Flex, 'names', {
enumerable: true,
writable: true,
value: ['flex-grow', 'flex-positive']
});
module.exports = Flex;
},{"../declaration":6,"./flex-spec":26}],25:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexShrink = function (_Declaration) {
_inherits(FlexShrink, _Declaration);
function FlexShrink() {
_classCallCheck(this, FlexShrink);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
FlexShrink.prototype.normalize = function normalize() {
return 'flex-shrink';
};
/**
* Return flex property for 2012 spec
*/
FlexShrink.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2012) {
return prefix + 'flex-negative';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Ignore 2009 spec and use flex property for 2012
*/
FlexShrink.prototype.set = function set(decl, prefix) {
var spec = void 0;
var _flexSpec2 = flexSpec(prefix);
spec = _flexSpec2[0];
prefix = _flexSpec2[1];
if (spec === 2012 || spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return FlexShrink;
}(Declaration);
Object.defineProperty(FlexShrink, 'names', {
enumerable: true,
writable: true,
value: ['flex-shrink', 'flex-negative']
});
module.exports = FlexShrink;
},{"../declaration":6,"./flex-spec":26}],26:[function(require,module,exports){
'use strict';
/**
* Return flexbox spec versions by prefix
*/
module.exports = function (prefix) {
var spec = void 0;
if (prefix === '-webkit- 2009' || prefix === '-moz-') {
spec = 2009;
} else if (prefix === '-ms-') {
spec = 2012;
} else if (prefix === '-webkit-') {
spec = 'final';
}
if (prefix === '-webkit- 2009') {
prefix = '-webkit-';
}
return [spec, prefix];
};
},{}],27:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
var FlexValues = function (_Value) {
_inherits(FlexValues, _Value);
function FlexValues() {
_classCallCheck(this, FlexValues);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
/**
* Return prefixed property name
*/
FlexValues.prototype.prefixed = function prefixed(prefix) {
return this.all.prefixed(this.name, prefix);
};
/**
* Change property name to prefixed property name
*/
FlexValues.prototype.replace = function replace(string, prefix) {
return string.replace(this.regexp(), '$1' + this.prefixed(prefix) + '$3');
};
/**
* Return function to fast prefixed property name
*/
FlexValues.prototype.old = function old(prefix) {
return new OldValue(this.name, this.prefixed(prefix));
};
return FlexValues;
}(Value);
Object.defineProperty(FlexValues, 'names', {
enumerable: true,
writable: true,
value: ['flex', 'flex-grow', 'flex-shrink', 'flex-basis']
});
module.exports = FlexValues;
},{"../old-value":52,"../value":61}],28:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexWrap = function (_Declaration) {
_inherits(FlexWrap, _Declaration);
function FlexWrap() {
_classCallCheck(this, FlexWrap);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Don't add prefix for 2009 spec
*/
FlexWrap.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec !== 2009) {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return FlexWrap;
}(Declaration);
Object.defineProperty(FlexWrap, 'names', {
enumerable: true,
writable: true,
value: ['flex-wrap']
});
module.exports = FlexWrap;
},{"../declaration":6,"./flex-spec":26}],29:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var list = require('postcss/lib/list');
var Flex = function (_Declaration) {
_inherits(Flex, _Declaration);
function Flex() {
_classCallCheck(this, Flex);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 spec
*/
Flex.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-flex';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
Flex.prototype.normalize = function normalize() {
return 'flex';
};
/**
* Spec 2009 supports only first argument
* Spec 2012 disallows unitless basis
*/
Flex.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009) {
decl.value = list.space(decl.value)[0];
decl.value = Flex.oldValues[decl.value] || decl.value;
return _Declaration.prototype.set.call(this, decl, prefix);
} else if (spec === 2012) {
var components = list.space(decl.value);
if (components.length === 3 && components[2] === '0') {
decl.value = components.slice(0, 2).concat('0px').join(' ');
}
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return Flex;
}(Declaration);
Object.defineProperty(Flex, 'names', {
enumerable: true,
writable: true,
value: ['flex', 'box-flex']
});
Object.defineProperty(Flex, 'oldValues', {
enumerable: true,
writable: true,
value: {
auto: '1',
none: '0'
}
});
module.exports = Flex;
},{"../declaration":6,"./flex-spec":26,"postcss/lib/list":536}],30:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Selector = require('../selector');
var Fullscreen = function (_Selector) {
_inherits(Fullscreen, _Selector);
function Fullscreen() {
_classCallCheck(this, Fullscreen);
return _possibleConstructorReturn(this, _Selector.apply(this, arguments));
}
/**
* Return different selectors depend on prefix
*/
Fullscreen.prototype.prefixed = function prefixed(prefix) {
if (prefix === '-webkit-') {
return ':-webkit-full-screen';
} else if (prefix === '-moz-') {
return ':-moz-full-screen';
} else {
return ':' + prefix + 'fullscreen';
}
};
return Fullscreen;
}(Selector);
Object.defineProperty(Fullscreen, 'names', {
enumerable: true,
writable: true,
value: [':fullscreen']
});
module.exports = Fullscreen;
},{"../selector":57}],31:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
var utils = require('../utils');
var parser = require('postcss-value-parser');
var range = require('normalize-range');
var isDirection = /top|left|right|bottom/gi;
var Gradient = function (_Value) {
_inherits(Gradient, _Value);
function Gradient() {
var _temp, _this, _ret;
_classCallCheck(this, Gradient);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Value.call.apply(_Value, [this].concat(args))), _this), Object.defineProperty(_this, 'directions', {
enumerable: true,
writable: true,
value: {
top: 'bottom',
left: 'right',
bottom: 'top',
right: 'left'
}
}), Object.defineProperty(_this, 'oldDirections', {
enumerable: true,
writable: true,
value: {
'top': 'left bottom, left top',
'left': 'right top, left top',
'bottom': 'left top, left bottom',
'right': 'left top, right top',
'top right': 'left bottom, right top',
'top left': 'right bottom, left top',
'right top': 'left bottom, right top',
'right bottom': 'left top, right bottom',
'bottom right': 'left top, right bottom',
'bottom left': 'right top, left bottom',
'left top': 'right bottom, left top',
'left bottom': 'right top, left bottom'
}
}), _temp), _possibleConstructorReturn(_this, _ret);
}
// Direction to replace
// Direction to replace
/**
* Change degrees for webkit prefix
*/
Gradient.prototype.replace = function replace(string, prefix) {
var ast = parser(string);
for (var _iterator = ast.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
if (node.type === 'function' && node.value === this.name) {
node.nodes = this.newDirection(node.nodes);
node.nodes = this.normalize(node.nodes);
if (prefix === '-webkit- old') {
var changes = this.oldWebkit(node);
if (!changes) {
return undefined;
}
} else {
node.nodes = this.convertDirection(node.nodes);
node.value = prefix + node.value;
}
}
}
return ast.toString();
};
/**
* Replace first token
*/
Gradient.prototype.replaceFirst = function replaceFirst(params) {
for (var _len2 = arguments.length, words = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
words[_key2 - 1] = arguments[_key2];
}
var prefix = words.map(function (i) {
if (i === ' ') {
return { type: 'space', value: i };
} else {
return { type: 'word', value: i };
}
});
return prefix.concat(params.slice(1));
};
/**
* Convert angle unit to deg
*/
Gradient.prototype.normalizeUnit = function normalizeUnit(str, full) {
var num = parseFloat(str);
var deg = num / full * 360;
return deg + 'deg';
};
/**
* Normalize angle
*/
Gradient.prototype.normalize = function normalize(nodes) {
if (!nodes[0]) {
return nodes;
}
if (/-?\d+(.\d+)?grad/.test(nodes[0].value)) {
nodes[0].value = this.normalizeUnit(nodes[0].value, 400);
} else if (/-?\d+(.\d+)?rad/.test(nodes[0].value)) {
nodes[0].value = this.normalizeUnit(nodes[0].value, 2 * Math.PI);
} else if (/-?\d+(.\d+)?turn/.test(nodes[0].value)) {
nodes[0].value = this.normalizeUnit(nodes[0].value, 1);
} else if (nodes[0].value.indexOf('deg') !== -1) {
var num = parseFloat(nodes[0].value);
num = range.wrap(0, 360, num);
nodes[0].value = num + 'deg';
}
if (nodes[0].value === '0deg') {
nodes = this.replaceFirst(nodes, 'to', ' ', 'top');
} else if (nodes[0].value === '90deg') {
nodes = this.replaceFirst(nodes, 'to', ' ', 'right');
} else if (nodes[0].value === '180deg') {
nodes = this.replaceFirst(nodes, 'to', ' ', 'bottom');
} else if (nodes[0].value === '270deg') {
nodes = this.replaceFirst(nodes, 'to', ' ', 'left');
}
return nodes;
};
/**
* Replace old direction to new
*/
Gradient.prototype.newDirection = function newDirection(params) {
if (params[0].value === 'to') {
return params;
}
if (!isDirection.test(params[0].value)) {
return params;
}
params.unshift({
type: 'word',
value: 'to'
}, {
type: 'space',
value: ' '
});
for (var i = 2; i < params.length; i++) {
if (params[i].type === 'div') {
break;
}
if (params[i].type === 'word') {
params[i].value = this.revertDirection(params[i].value);
}
}
return params;
};
/**
* Change new direction to old
*/
Gradient.prototype.convertDirection = function convertDirection(params) {
if (params.length > 0) {
if (params[0].value === 'to') {
this.fixDirection(params);
} else if (params[0].value.indexOf('deg') !== -1) {
this.fixAngle(params);
} else if (params[2].value === 'at') {
this.fixRadial(params);
}
}
return params;
};
/**
* Replace `to top left` to `bottom right`
*/
Gradient.prototype.fixDirection = function fixDirection(params) {
params.splice(0, 2);
for (var _iterator2 = params, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var param = _ref2;
if (param.type === 'div') {
break;
}
if (param.type === 'word') {
param.value = this.revertDirection(param.value);
}
}
};
/**
* Add 90 degrees
*/
Gradient.prototype.fixAngle = function fixAngle(params) {
var first = params[0].value;
first = parseFloat(first);
first = Math.abs(450 - first) % 360;
first = this.roundFloat(first, 3);
params[0].value = first + 'deg';
};
/**
* Fix radial direction syntax
*/
Gradient.prototype.fixRadial = function fixRadial(params) {
var first = params[0];
var second = [];
var i = void 0;
for (i = 4; i < params.length; i++) {
if (params[i].type === 'div') {
break;
} else {
second.push(params[i]);
}
}
params.splice.apply(params, [0, i].concat(second, [params[i + 2], first]));
};
Gradient.prototype.revertDirection = function revertDirection(word) {
return this.directions[word.toLowerCase()] || word;
};
/**
* Round float and save digits under dot
*/
Gradient.prototype.roundFloat = function roundFloat(float, digits) {
return parseFloat(float.toFixed(digits));
};
/**
* Convert to old webkit syntax
*/
Gradient.prototype.oldWebkit = function oldWebkit(node) {
var nodes = node.nodes;
var string = parser.stringify(node.nodes);
if (this.name !== 'linear-gradient') {
return false;
}
if (nodes[0] && nodes[0].value.indexOf('deg') !== -1) {
return false;
}
if (string.indexOf('px') !== -1) {
return false;
}
if (string.indexOf('-corner') !== -1) {
return false;
}
if (string.indexOf('-side') !== -1) {
return false;
}
var params = [[]];
for (var _iterator3 = nodes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var i = _ref3;
params[params.length - 1].push(i);
if (i.type === 'div' && i.value === ',') {
params.push([]);
}
}
this.oldDirection(params);
this.colorStops(params);
node.nodes = [];
for (var _iterator4 = params, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var param = _ref4;
node.nodes = node.nodes.concat(param);
}
node.nodes.unshift({ type: 'word', value: 'linear' }, this.cloneDiv(node.nodes));
node.value = '-webkit-gradient';
return true;
};
/**
* Change direction syntax to old webkit
*/
Gradient.prototype.oldDirection = function oldDirection(params) {
var div = this.cloneDiv(params[0]);
if (params[0][0].value !== 'to') {
return params.unshift([{ type: 'word', value: this.oldDirections.bottom }, div]);
} else {
var _words = [];
for (var _iterator5 = params[0].slice(2), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var node = _ref5;
if (node.type === 'word') {
_words.push(node.value.toLowerCase());
}
}
_words = _words.join(' ');
var old = this.oldDirections[_words] || _words;
params[0] = [{ type: 'word', value: old }, div];
return params[0];
}
};
/**
* Get div token from exists parameters
*/
Gradient.prototype.cloneDiv = function cloneDiv(params) {
for (var _iterator6 = params, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref6;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref6 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref6 = _i6.value;
}
var i = _ref6;
if (i.type === 'div' && i.value === ',') {
return i;
}
}
return { type: 'div', value: ',', after: ' ' };
};
/**
* Change colors syntax to old webkit
*/
Gradient.prototype.colorStops = function colorStops(params) {
var result = [];
for (var i = 0; i < params.length; i++) {
var pos = void 0;
var param = params[i];
var item = void 0;
if (i === 0) {
continue;
}
var color = parser.stringify(param[0]);
if (param[1] && param[1].type === 'word') {
pos = param[1].value;
} else if (param[2] && param[2].type === 'word') {
pos = param[2].value;
}
var stop = void 0;
if (i === 1 && (!pos || pos === '0%')) {
stop = 'from(' + color + ')';
} else if (i === params.length - 1 && (!pos || pos === '100%')) {
stop = 'to(' + color + ')';
} else if (pos) {
stop = 'color-stop(' + pos + ', ' + color + ')';
} else {
stop = 'color-stop(' + color + ')';
}
var div = param[param.length - 1];
params[i] = [{ type: 'word', value: stop }];
if (div.type === 'div' && div.value === ',') {
item = params[i].push(div);
}
result.push(item);
}
return result;
};
/**
* Remove old WebKit gradient too
*/
Gradient.prototype.old = function old(prefix) {
if (prefix === '-webkit-') {
var type = this.name === 'linear-gradient' ? 'linear' : 'radial';
var string = '-gradient';
var regexp = utils.regexp('-webkit-(' + type + '-gradient|gradient\\(\\s*' + type + ')', false);
return new OldValue(this.name, prefix + this.name, string, regexp);
} else {
return _Value.prototype.old.call(this, prefix);
}
};
/**
* Do not add non-webkit prefixes for list-style and object
*/
Gradient.prototype.add = function add(decl, prefix) {
var p = decl.prop;
if (p.indexOf('mask') !== -1) {
if (prefix === '-webkit-' || prefix === '-webkit- old') {
return _Value.prototype.add.call(this, decl, prefix);
}
} else if (p === 'list-style' || p === 'list-style-image' || p === 'content') {
if (prefix === '-webkit-' || prefix === '-webkit- old') {
return _Value.prototype.add.call(this, decl, prefix);
}
} else {
return _Value.prototype.add.call(this, decl, prefix);
}
return undefined;
};
return Gradient;
}(Value);
Object.defineProperty(Gradient, 'names', {
enumerable: true,
writable: true,
value: ['linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient']
});
module.exports = Gradient;
},{"../old-value":52,"../utils":60,"../value":61,"normalize-range":521,"postcss-value-parser":524}],32:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var GridColumnAlign = function (_Declaration) {
_inherits(GridColumnAlign, _Declaration);
function GridColumnAlign() {
_classCallCheck(this, GridColumnAlign);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not prefix flexbox values
*/
GridColumnAlign.prototype.check = function check(decl) {
return decl.value.indexOf('flex-') === -1 && decl.value !== 'baseline';
};
/**
* Change property name for IE
*/
GridColumnAlign.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + 'grid-column-align';
};
/**
* Change IE property back
*/
GridColumnAlign.prototype.normalize = function normalize() {
return 'justify-self';
};
return GridColumnAlign;
}(Declaration);
Object.defineProperty(GridColumnAlign, 'names', {
enumerable: true,
writable: true,
value: ['grid-column-align']
});
module.exports = GridColumnAlign;
},{"../declaration":6}],33:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var GridEnd = function (_Declaration) {
_inherits(GridEnd, _Declaration);
function GridEnd() {
_classCallCheck(this, GridEnd);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not add prefix for unsupported value in IE
*/
GridEnd.prototype.check = function check(decl) {
return decl.value.indexOf('span') !== -1;
};
/**
* Return a final spec property
*/
GridEnd.prototype.normalize = function normalize(prop) {
return prop.replace(/(-span|-end)/, '');
};
/**
* Change property name for IE
*/
GridEnd.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return prefix + prop.replace('-end', '-span');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Change repeating syntax for IE
*/
GridEnd.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-') {
decl.value = decl.value.replace(/span\s/i, '');
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return GridEnd;
}(Declaration);
Object.defineProperty(GridEnd, 'names', {
enumerable: true,
writable: true,
value: ['grid-row-end', 'grid-column-end', 'grid-row-span', 'grid-column-span']
});
module.exports = GridEnd;
},{"../declaration":6}],34:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var GridRowAlign = function (_Declaration) {
_inherits(GridRowAlign, _Declaration);
function GridRowAlign() {
_classCallCheck(this, GridRowAlign);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not prefix flexbox values
*/
GridRowAlign.prototype.check = function check(decl) {
return decl.value.indexOf('flex-') === -1 && decl.value !== 'baseline';
};
/**
* Change property name for IE
*/
GridRowAlign.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + 'grid-row-align';
};
/**
* Change IE property back
*/
GridRowAlign.prototype.normalize = function normalize() {
return 'align-self';
};
return GridRowAlign;
}(Declaration);
Object.defineProperty(GridRowAlign, 'names', {
enumerable: true,
writable: true,
value: ['grid-row-align']
});
module.exports = GridRowAlign;
},{"../declaration":6}],35:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var GridStart = function (_Declaration) {
_inherits(GridStart, _Declaration);
function GridStart() {
_classCallCheck(this, GridStart);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not add prefix for unsupported value in IE
*/
GridStart.prototype.check = function check(decl) {
return decl.value.indexOf('/') === -1 || decl.value.indexOf('span') !== -1;
};
/**
* Return a final spec property
*/
GridStart.prototype.normalize = function normalize(prop) {
return prop.replace('-start', '');
};
/**
* Change property name for IE
*/
GridStart.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return prefix + prop.replace('-start', '');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Split one value to two
*/
GridStart.prototype.insert = function insert(decl, prefix, prefixes) {
var parts = this.splitValue(decl, prefix);
if (parts.length === 2) {
decl.cloneBefore({
prop: '-ms-' + decl.prop + '-span',
value: parts[1]
});
}
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
};
/**
* Change value for combine property
*/
GridStart.prototype.set = function set(decl, prefix) {
var parts = this.splitValue(decl, prefix);
if (parts.length === 2) {
decl.value = parts[0];
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
/**
* If property contains start and end
*/
GridStart.prototype.splitValue = function splitValue(decl, prefix) {
if (prefix === '-ms-' && decl.prop.indexOf('-start') === -1) {
var parts = decl.value.split(/\s*\/\s*span\s+/);
if (parts.length === 2) {
return parts;
}
}
return false;
};
return GridStart;
}(Declaration);
Object.defineProperty(GridStart, 'names', {
enumerable: true,
writable: true,
value: ['grid-row-start', 'grid-column-start', 'grid-row', 'grid-column']
});
module.exports = GridStart;
},{"../declaration":6}],36:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var parser = require('postcss-value-parser');
var Declaration = require('../declaration');
var GridTemplate = function (_Declaration) {
_inherits(GridTemplate, _Declaration);
function GridTemplate() {
_classCallCheck(this, GridTemplate);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for IE
*/
GridTemplate.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return prefix + prop.replace('template-', '');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Change IE property back
*/
GridTemplate.prototype.normalize = function normalize(prop) {
return prop.replace(/^grid-(rows|columns)/, 'grid-template-$1');
};
/**
* Recursive part of changeRepeat
*/
GridTemplate.prototype.walkRepeat = function walkRepeat(node) {
var fixed = [];
for (var _iterator = node.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
if (i.nodes) {
this.walkRepeat(i);
}
fixed.push(i);
if (i.type === 'function' && i.value === 'repeat') {
var first = i.nodes.shift();
if (first) {
var count = first.value;
i.nodes.shift();
i.value = '';
fixed.push({ type: 'word', value: '[' + count + ']' });
}
}
}
node.nodes = fixed;
};
/**
* IE repeating syntax
*/
GridTemplate.prototype.changeRepeat = function changeRepeat(value) {
var ast = parser(value);
this.walkRepeat(ast);
return ast.toString();
};
/**
* Change repeating syntax for IE
*/
GridTemplate.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-' && decl.value.indexOf('repeat(') !== -1) {
decl.value = this.changeRepeat(decl.value);
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return GridTemplate;
}(Declaration);
Object.defineProperty(GridTemplate, 'names', {
enumerable: true,
writable: true,
value: ['grid-template-rows', 'grid-template-columns', 'grid-rows', 'grid-columns']
});
module.exports = GridTemplate;
},{"../declaration":6,"postcss-value-parser":524}],37:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var ImageRendering = function (_Declaration) {
_inherits(ImageRendering, _Declaration);
function ImageRendering() {
_classCallCheck(this, ImageRendering);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Add hack only for crisp-edges
*/
ImageRendering.prototype.check = function check(decl) {
return decl.value === 'pixelated';
};
/**
* Change property name for IE
*/
ImageRendering.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return '-ms-interpolation-mode';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Change property and value for IE
*/
ImageRendering.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-') {
decl.prop = '-ms-interpolation-mode';
decl.value = 'nearest-neighbor';
return decl;
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
/**
* Return property name by spec
*/
ImageRendering.prototype.normalize = function normalize() {
return 'image-rendering';
};
/**
* Warn on old value
*/
ImageRendering.prototype.process = function process(node, result) {
return _Declaration.prototype.process.call(this, node, result);
};
return ImageRendering;
}(Declaration);
Object.defineProperty(ImageRendering, 'names', {
enumerable: true,
writable: true,
value: ['image-rendering', 'interpolation-mode']
});
module.exports = ImageRendering;
},{"../declaration":6}],38:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Value = require('../value');
var ImageSet = function (_Value) {
_inherits(ImageSet, _Value);
function ImageSet() {
_classCallCheck(this, ImageSet);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
/**
* Use non-standard name for WebKit and Firefox
*/
ImageSet.prototype.replace = function replace(string, prefix) {
if (prefix === '-webkit-') {
return _Value.prototype.replace.call(this, string, prefix).replace(/("[^"]+"|'[^']+')(\s+\d+\w)/gi, 'url($1)$2');
} else {
return _Value.prototype.replace.call(this, string, prefix);
}
};
return ImageSet;
}(Value);
Object.defineProperty(ImageSet, 'names', {
enumerable: true,
writable: true,
value: ['image-set']
});
module.exports = ImageSet;
},{"../value":61}],39:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var InlineLogical = function (_Declaration) {
_inherits(InlineLogical, _Declaration);
function InlineLogical() {
_classCallCheck(this, InlineLogical);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Use old syntax for -moz- and -webkit-
*/
InlineLogical.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + prop.replace('-inline', '');
};
/**
* Return property name by spec
*/
InlineLogical.prototype.normalize = function normalize(prop) {
return prop.replace(/(margin|padding|border)-(start|end)/, '$1-inline-$2');
};
return InlineLogical;
}(Declaration);
Object.defineProperty(InlineLogical, 'names', {
enumerable: true,
writable: true,
value: ['border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', 'padding-inline-start', 'padding-inline-end', 'border-start', 'border-end', 'margin-start', 'margin-end', 'padding-start', 'padding-end']
});
module.exports = InlineLogical;
},{"../declaration":6}],40:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
function _regexp(name) {
return new RegExp('(^|[\\s,(])(' + name + '($|[\\s),]))', 'gi');
}
var Intrinsic = function (_Value) {
_inherits(Intrinsic, _Value);
function Intrinsic() {
_classCallCheck(this, Intrinsic);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
Intrinsic.prototype.regexp = function regexp() {
if (!this.regexpCache) this.regexpCache = _regexp(this.name);
return this.regexpCache;
};
Intrinsic.prototype.isStretch = function isStretch() {
return this.name === 'stretch' || this.name === 'fill' || this.name === 'fill-available';
};
Intrinsic.prototype.replace = function replace(string, prefix) {
if (prefix === '-moz-' && this.isStretch()) {
return string.replace(this.regexp(), '$1-moz-available$3');
} else if (prefix === '-webkit-' && this.isStretch()) {
return string.replace(this.regexp(), '$1-webkit-fill-available$3');
} else {
return _Value.prototype.replace.call(this, string, prefix);
}
};
Intrinsic.prototype.old = function old(prefix) {
var prefixed = prefix + this.name;
if (this.isStretch()) {
if (prefix === '-moz-') {
prefixed = '-moz-available';
} else if (prefix === '-webkit-') {
prefixed = '-webkit-fill-available';
}
}
return new OldValue(this.name, prefixed, prefixed, _regexp(prefixed));
};
Intrinsic.prototype.add = function add(decl, prefix) {
if (decl.prop.indexOf('grid') !== -1 && prefix !== '-webkit-') {
return undefined;
}
return _Value.prototype.add.call(this, decl, prefix);
};
return Intrinsic;
}(Value);
Object.defineProperty(Intrinsic, 'names', {
enumerable: true,
writable: true,
value: ['max-content', 'min-content', 'fit-content', 'fill', 'fill-available', 'stretch']
});
module.exports = Intrinsic;
},{"../old-value":52,"../value":61}],41:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var JustifyContent = function (_Declaration) {
_inherits(JustifyContent, _Declaration);
function JustifyContent() {
_classCallCheck(this, JustifyContent);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 and 2012 specs
*/
JustifyContent.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-pack';
} else if (spec === 2012) {
return prefix + 'flex-pack';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
JustifyContent.prototype.normalize = function normalize() {
return 'justify-content';
};
/**
* Change value for 2009 and 2012 specs
*/
JustifyContent.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009 || spec === 2012) {
var value = JustifyContent.oldValues[decl.value] || decl.value;
decl.value = value;
if (spec !== 2009 || value !== 'distribute') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
} else if (spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return JustifyContent;
}(Declaration);
Object.defineProperty(JustifyContent, 'names', {
enumerable: true,
writable: true,
value: ['justify-content', 'flex-pack', 'box-pack']
});
Object.defineProperty(JustifyContent, 'oldValues', {
enumerable: true,
writable: true,
value: {
'flex-end': 'end',
'flex-start': 'start',
'space-between': 'justify',
'space-around': 'distribute'
}
});
module.exports = JustifyContent;
},{"../declaration":6,"./flex-spec":26}],42:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var MaskBorder = function (_Declaration) {
_inherits(MaskBorder, _Declaration);
function MaskBorder() {
_classCallCheck(this, MaskBorder);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
MaskBorder.prototype.normalize = function normalize() {
return this.name.replace('box-image', 'border');
};
/**
* Return flex property for 2012 spec
*/
MaskBorder.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-webkit-') {
return _Declaration.prototype.prefixed.call(this, prop, prefix).replace('border', 'box-image');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
return MaskBorder;
}(Declaration);
Object.defineProperty(MaskBorder, 'names', {
enumerable: true,
writable: true,
value: ['mask-border', 'mask-border-source', 'mask-border-slice', 'mask-border-width', 'mask-border-outset', 'mask-border-repeat', 'mask-box-image', 'mask-box-image-source', 'mask-box-image-slice', 'mask-box-image-width', 'mask-box-image-outset', 'mask-box-image-repeat']
});
module.exports = MaskBorder;
},{"../declaration":6}],43:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var Order = function (_Declaration) {
_inherits(Order, _Declaration);
function Order() {
_classCallCheck(this, Order);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 and 2012 specs
*/
Order.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-ordinal-group';
} else if (spec === 2012) {
return prefix + 'flex-order';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
Order.prototype.normalize = function normalize() {
return 'order';
};
/**
* Fix value for 2009 spec
*/
Order.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009 && /\d/.test(decl.value)) {
decl.value = (parseInt(decl.value) + 1).toString();
return _Declaration.prototype.set.call(this, decl, prefix);
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
return Order;
}(Declaration);
Object.defineProperty(Order, 'names', {
enumerable: true,
writable: true,
value: ['order', 'flex-order', 'box-ordinal-group']
});
module.exports = Order;
},{"../declaration":6,"./flex-spec":26}],44:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
var Pixelated = function (_Value) {
_inherits(Pixelated, _Value);
function Pixelated() {
_classCallCheck(this, Pixelated);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
/**
* Use non-standard name for WebKit and Firefox
*/
Pixelated.prototype.replace = function replace(string, prefix) {
if (prefix === '-webkit-') {
return string.replace(this.regexp(), '$1-webkit-optimize-contrast');
} else if (prefix === '-moz-') {
return string.replace(this.regexp(), '$1-moz-crisp-edges');
} else {
return _Value.prototype.replace.call(this, string, prefix);
}
};
/**
* Different name for WebKit and Firefox
*/
Pixelated.prototype.old = function old(prefix) {
if (prefix === '-webkit-') {
return new OldValue(this.name, '-webkit-optimize-contrast');
} else if (prefix === '-moz-') {
return new OldValue(this.name, '-moz-crisp-edges');
} else {
return _Value.prototype.old.call(this, prefix);
}
};
return Pixelated;
}(Value);
Object.defineProperty(Pixelated, 'names', {
enumerable: true,
writable: true,
value: ['pixelated']
});
module.exports = Pixelated;
},{"../old-value":52,"../value":61}],45:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Selector = require('../selector');
var Placeholder = function (_Selector) {
_inherits(Placeholder, _Selector);
function Placeholder() {
_classCallCheck(this, Placeholder);
return _possibleConstructorReturn(this, _Selector.apply(this, arguments));
}
/**
* Add old mozilla to possible prefixes
*/
Placeholder.prototype.possible = function possible() {
return _Selector.prototype.possible.call(this).concat('-moz- old');
};
/**
* Return different selectors depend on prefix
*/
Placeholder.prototype.prefixed = function prefixed(prefix) {
if (prefix === '-webkit-') {
return '::-webkit-input-placeholder';
} else if (prefix === '-ms-') {
return ':-ms-input-placeholder';
} else if (prefix === '-moz- old') {
return ':-moz-placeholder';
} else {
return '::' + prefix + 'placeholder';
}
};
return Placeholder;
}(Selector);
Object.defineProperty(Placeholder, 'names', {
enumerable: true,
writable: true,
value: [':placeholder-shown', '::placeholder']
});
module.exports = Placeholder;
},{"../selector":57}],46:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BASIC = ['none', 'underline', 'overline', 'line-through', 'blink', 'inherit', 'initial', 'unset'];
var TextDecoration = function (_Declaration) {
_inherits(TextDecoration, _Declaration);
function TextDecoration() {
_classCallCheck(this, TextDecoration);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not add prefixes for basic values.
*/
TextDecoration.prototype.check = function check(decl) {
return decl.value.split(/\s+/).some(function (i) {
return BASIC.indexOf(i) === -1;
});
};
return TextDecoration;
}(Declaration);
Object.defineProperty(TextDecoration, 'names', {
enumerable: true,
writable: true,
value: ['text-decoration']
});
module.exports = TextDecoration;
},{"../declaration":6}],47:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var TextEmphasisPosition = function (_Declaration) {
_inherits(TextEmphasisPosition, _Declaration);
function TextEmphasisPosition() {
_classCallCheck(this, TextEmphasisPosition);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
TextEmphasisPosition.prototype.set = function set(decl, prefix) {
if (prefix === '-webkit-') {
decl.value = decl.value.replace(/\s*(right|left)\s*/i, '');
return _Declaration.prototype.set.call(this, decl, prefix);
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
return TextEmphasisPosition;
}(Declaration);
Object.defineProperty(TextEmphasisPosition, 'names', {
enumerable: true,
writable: true,
value: ['text-emphasis-position']
});
module.exports = TextEmphasisPosition;
},{"../declaration":6}],48:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var TransformDecl = function (_Declaration) {
_inherits(TransformDecl, _Declaration);
function TransformDecl() {
_classCallCheck(this, TransformDecl);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Recursively check all parents for @keyframes
*/
TransformDecl.prototype.keyframeParents = function keyframeParents(decl) {
var parent = decl.parent;
while (parent) {
if (parent.type === 'atrule' && parent.name === 'keyframes') {
return true;
}
var _parent = parent;
parent = _parent.parent;
}
return false;
};
/**
* Is transform caontain 3D commands
*/
TransformDecl.prototype.contain3d = function contain3d(decl) {
if (decl.prop === 'transform-origin') {
return false;
}
for (var _iterator = TransformDecl.functions3d, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var func = _ref;
if (decl.value.indexOf(func + '(') !== -1) {
return true;
}
}
return false;
};
/**
* Replace rotateZ to rotate for IE 9
*/
TransformDecl.prototype.set = function set(decl, prefix) {
decl = _Declaration.prototype.set.call(this, decl, prefix);
if (prefix === '-ms-') {
decl.value = decl.value.replace(/rotateZ/gi, 'rotate');
}
return decl;
};
/**
* Don't add prefix for IE in keyframes
*/
TransformDecl.prototype.insert = function insert(decl, prefix, prefixes) {
if (prefix === '-ms-') {
if (!this.contain3d(decl) && !this.keyframeParents(decl)) {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
}
} else if (prefix === '-o-') {
if (!this.contain3d(decl)) {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
}
} else {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
}
return undefined;
};
return TransformDecl;
}(Declaration);
Object.defineProperty(TransformDecl, 'names', {
enumerable: true,
writable: true,
value: ['transform', 'transform-origin']
});
Object.defineProperty(TransformDecl, 'functions3d', {
enumerable: true,
writable: true,
value: ['matrix3d', 'translate3d', 'translateZ', 'scale3d', 'scaleZ', 'rotate3d', 'rotateX', 'rotateY', 'perspective']
});
module.exports = TransformDecl;
},{"../declaration":6}],49:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var WritingMode = function (_Declaration) {
_inherits(WritingMode, _Declaration);
function WritingMode() {
_classCallCheck(this, WritingMode);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
WritingMode.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-') {
decl.value = WritingMode.msValues[decl.value] || decl.value;
return _Declaration.prototype.set.call(this, decl, prefix);
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
return WritingMode;
}(Declaration);
Object.defineProperty(WritingMode, 'names', {
enumerable: true,
writable: true,
value: ['writing-mode']
});
Object.defineProperty(WritingMode, 'msValues', {
enumerable: true,
writable: true,
value: {
'horizontal-tb': 'lr-tb',
'vertical-rl': 'tb-rl',
'vertical-lr': 'tb-lr'
}
});
module.exports = WritingMode;
},{"../declaration":6}],50:[function(require,module,exports){
'use strict';
var browserslist = require('browserslist');
function capitalize(str) {
return str.slice(0, 1).toUpperCase() + str.slice(1);
}
var names = {
ie: 'IE',
ie_mob: 'IE Mobile',
ios_saf: 'iOS',
op_mini: 'Opera Mini',
op_mob: 'Opera Mobile',
and_chr: 'Chrome for Android',
and_ff: 'Firefox for Android',
and_uc: 'UC for Android'
};
var prefix = function prefix(name, prefixes) {
var out = ' ' + name + ': ';
out += prefixes.map(function (i) {
return i.replace(/^-(.*)-$/g, '$1');
}).join(', ');
out += '\n';
return out;
};
module.exports = function (prefixes) {
if (prefixes.browsers.selected.length === 0) {
return 'No browsers selected';
}
var versions = {};
for (var _iterator = prefixes.browsers.selected, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var browser = _ref;
var _browser$split = browser.split(' '),
name = _browser$split[0],
version = _browser$split[1];
name = names[name] || capitalize(name);
if (versions[name]) {
versions[name].push(version);
} else {
versions[name] = [version];
}
}
var out = 'Browsers:\n';
for (var _browser in versions) {
var list = versions[_browser];
list = list.sort(function (a, b) {
return parseFloat(b) - parseFloat(a);
});
out += ' ' + _browser + ': ' + list.join(', ') + '\n';
}
var coverage = browserslist.coverage(prefixes.browsers.selected);
var round = Math.round(coverage * 100) / 100.0;
out += '\nThese browsers account for ' + round + '% of all users globally\n';
var atrules = '';
for (var name in prefixes.add) {
var data = prefixes.add[name];
if (name[0] === '@' && data.prefixes) {
atrules += prefix(name, data.prefixes);
}
}
if (atrules !== '') {
out += '\nAt-Rules:\n' + atrules;
}
var selectors = '';
for (var _iterator2 = prefixes.add.selectors, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var selector = _ref2;
if (selector.prefixes) {
selectors += prefix(selector.name, selector.prefixes);
}
}
if (selectors !== '') {
out += '\nSelectors:\n' + selectors;
}
var values = '';
var props = '';
for (var _name in prefixes.add) {
var _data = prefixes.add[_name];
if (_name[0] !== '@' && _data.prefixes) {
props += prefix(_name, _data.prefixes);
}
if (!_data.values) {
continue;
}
for (var _iterator3 = _data.values, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var value = _ref3;
var string = prefix(value.name, value.prefixes);
if (values.indexOf(string) === -1) {
values += string;
}
}
}
if (props !== '') {
out += '\nProperties:\n' + props;
}
if (values !== '') {
out += '\nValues:\n' + values;
}
if (atrules === '' && selectors === '' && props === '' && values === '') {
out += '\nAwesome! Your browsers don\'t require any vendor prefixes.' + '\nNow you can remove Autoprefixer from build steps.';
}
return out;
};
},{"browserslist":65}],51:[function(require,module,exports){
"use strict";
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var OldSelector = function () {
function OldSelector(selector, prefix) {
_classCallCheck(this, OldSelector);
this.prefix = prefix;
this.prefixed = selector.prefixed(this.prefix);
this.regexp = selector.regexp(this.prefix);
this.prefixeds = selector.possible().map(function (x) {
return [selector.prefixed(x), selector.regexp(x)];
});
this.unprefixed = selector.name;
this.nameRegexp = selector.regexp();
}
/**
* Is rule a hack without unprefixed version bottom
*/
OldSelector.prototype.isHack = function isHack(rule) {
var index = rule.parent.index(rule) + 1;
var rules = rule.parent.nodes;
while (index < rules.length) {
var before = rules[index].selector;
if (!before) {
return true;
}
if (before.indexOf(this.unprefixed) !== -1 && before.match(this.nameRegexp)) {
return false;
}
var some = false;
for (var _iterator = this.prefixeds, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref2;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
}
var _ref = _ref2;
var string = _ref[0];
var regexp = _ref[1];
if (before.indexOf(string) !== -1 && before.match(regexp)) {
some = true;
break;
}
}
if (!some) {
return true;
}
index += 1;
}
return true;
};
/**
* Does rule contain an unnecessary prefixed selector
*/
OldSelector.prototype.check = function check(rule) {
if (rule.selector.indexOf(this.prefixed) === -1) {
return false;
}
if (!rule.selector.match(this.regexp)) {
return false;
}
if (this.isHack(rule)) {
return false;
}
return true;
};
return OldSelector;
}();
module.exports = OldSelector;
},{}],52:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var utils = require('./utils');
var OldValue = function () {
function OldValue(unprefixed, prefixed, string, regexp) {
_classCallCheck(this, OldValue);
this.unprefixed = unprefixed;
this.prefixed = prefixed;
this.string = string || prefixed;
this.regexp = regexp || utils.regexp(prefixed);
}
/**
* Check, that value contain old value
*/
OldValue.prototype.check = function check(value) {
if (value.indexOf(this.string) !== -1) {
return !!value.match(this.regexp);
}
return false;
};
return OldValue;
}();
module.exports = OldValue;
},{"./utils":60}],53:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Browsers = require('./browsers');
var utils = require('./utils');
var vendor = require('postcss/lib/vendor');
/**
* Recursivly clone objects
*/
function _clone(obj, parent) {
var cloned = new obj.constructor();
for (var _iterator = Object.keys(obj || {}), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
var value = obj[i];
if (i === 'parent' && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
if (parent) {
cloned[i] = parent;
}
} else if (i === 'source') {
cloned[i] = value;
} else if (i === null) {
cloned[i] = value;
} else if (value instanceof Array) {
cloned[i] = value.map(function (x) {
return _clone(x, cloned);
});
} else if (i !== '_autoprefixerPrefix' && i !== '_autoprefixerValues') {
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) {
value = _clone(value, cloned);
}
cloned[i] = value;
}
}
return cloned;
}
var Prefixer = function () {
/**
* Add hack to selected names
*/
Prefixer.hack = function hack(klass) {
var _this = this;
if (!this.hacks) {
this.hacks = {};
}
return klass.names.map(function (name) {
_this.hacks[name] = klass;
return _this.hacks[name];
});
};
/**
* Load hacks for some names
*/
Prefixer.load = function load(name, prefixes, all) {
var Klass = this.hacks && this.hacks[name];
if (Klass) {
return new Klass(name, prefixes, all);
} else {
return new this(name, prefixes, all);
}
};
/**
* Clone node and clean autprefixer custom caches
*/
Prefixer.clone = function clone(node, overrides) {
var cloned = _clone(node);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
};
function Prefixer(name, prefixes, all) {
_classCallCheck(this, Prefixer);
this.name = name;
this.prefixes = prefixes;
this.all = all;
}
/**
* Find prefix in node parents
*/
Prefixer.prototype.parentPrefix = function parentPrefix(node) {
var prefix = void 0;
if (typeof node._autoprefixerPrefix !== 'undefined') {
prefix = node._autoprefixerPrefix;
} else if (node.type === 'decl' && node.prop[0] === '-') {
prefix = vendor.prefix(node.prop);
} else if (node.type === 'root') {
prefix = false;
} else if (node.type === 'rule' && node.selector.indexOf(':-') !== -1 && /:(-\w+-)/.test(node.selector)) {
prefix = node.selector.match(/:(-\w+-)/)[1];
} else if (node.type === 'atrule' && node.name[0] === '-') {
prefix = vendor.prefix(node.name);
} else {
prefix = this.parentPrefix(node.parent);
}
if (Browsers.prefixes().indexOf(prefix) === -1) {
prefix = false;
}
node._autoprefixerPrefix = prefix;
return node._autoprefixerPrefix;
};
/**
* Clone node with prefixes
*/
Prefixer.prototype.process = function process(node) {
if (!this.check(node)) {
return undefined;
}
var parent = this.parentPrefix(node);
var prefixes = this.prefixes.filter(function (prefix) {
return !parent || parent === utils.removeNote(prefix);
});
var added = [];
for (var _iterator2 = prefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var prefix = _ref2;
if (this.add(node, prefix, added.concat([prefix]))) {
added.push(prefix);
}
}
return added;
};
/**
* Shortcut for Prefixer.clone
*/
Prefixer.prototype.clone = function clone(node, overrides) {
return Prefixer.clone(node, overrides);
};
return Prefixer;
}();
module.exports = Prefixer;
},{"./browsers":5,"./utils":60,"postcss/lib/vendor":551}],54:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Declaration = require('./declaration');
var Resolution = require('./resolution');
var Transition = require('./transition');
var Processor = require('./processor');
var Supports = require('./supports');
var Browsers = require('./browsers');
var Selector = require('./selector');
var AtRule = require('./at-rule');
var Value = require('./value');
var utils = require('./utils');
var vendor = require('postcss/lib/vendor');
Selector.hack(require('./hacks/fullscreen'));
Selector.hack(require('./hacks/placeholder'));
Declaration.hack(require('./hacks/flex'));
Declaration.hack(require('./hacks/order'));
Declaration.hack(require('./hacks/filter'));
Declaration.hack(require('./hacks/grid-end'));
Declaration.hack(require('./hacks/flex-flow'));
Declaration.hack(require('./hacks/flex-grow'));
Declaration.hack(require('./hacks/flex-wrap'));
Declaration.hack(require('./hacks/grid-start'));
Declaration.hack(require('./hacks/align-self'));
Declaration.hack(require('./hacks/appearance'));
Declaration.hack(require('./hacks/flex-basis'));
Declaration.hack(require('./hacks/mask-border'));
Declaration.hack(require('./hacks/align-items'));
Declaration.hack(require('./hacks/flex-shrink'));
Declaration.hack(require('./hacks/break-props'));
Declaration.hack(require('./hacks/writing-mode'));
Declaration.hack(require('./hacks/border-image'));
Declaration.hack(require('./hacks/align-content'));
Declaration.hack(require('./hacks/border-radius'));
Declaration.hack(require('./hacks/block-logical'));
Declaration.hack(require('./hacks/grid-template'));
Declaration.hack(require('./hacks/inline-logical'));
Declaration.hack(require('./hacks/grid-row-align'));
Declaration.hack(require('./hacks/transform-decl'));
Declaration.hack(require('./hacks/flex-direction'));
Declaration.hack(require('./hacks/image-rendering'));
Declaration.hack(require('./hacks/text-decoration'));
Declaration.hack(require('./hacks/justify-content'));
Declaration.hack(require('./hacks/background-size'));
Declaration.hack(require('./hacks/grid-column-align'));
Declaration.hack(require('./hacks/text-emphasis-position'));
Value.hack(require('./hacks/gradient'));
Value.hack(require('./hacks/intrinsic'));
Value.hack(require('./hacks/pixelated'));
Value.hack(require('./hacks/image-set'));
Value.hack(require('./hacks/cross-fade'));
Value.hack(require('./hacks/flex-values'));
Value.hack(require('./hacks/display-flex'));
Value.hack(require('./hacks/display-grid'));
Value.hack(require('./hacks/filter-value'));
var declsCache = {};
var Prefixes = function () {
function Prefixes(data, browsers) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
_classCallCheck(this, Prefixes);
this.data = data;
this.browsers = browsers;
this.options = options;
var _preprocess = this.preprocess(this.select(this.data));
this.add = _preprocess[0];
this.remove = _preprocess[1];
this.transition = new Transition(this);
this.processor = new Processor(this);
}
/**
* Return clone instance to remove all prefixes
*/
Prefixes.prototype.cleaner = function cleaner() {
if (this.cleanerCache) {
return this.cleanerCache;
}
if (this.browsers.selected.length) {
var empty = new Browsers(this.browsers.data, []);
this.cleanerCache = new Prefixes(this.data, empty, this.options);
} else {
return this;
}
return this.cleanerCache;
};
/**
* Select prefixes from data, which is necessary for selected browsers
*/
Prefixes.prototype.select = function select(list) {
var _this = this;
var selected = { add: {}, remove: {} };
var _loop = function _loop(name) {
var data = list[name];
var add = data.browsers.map(function (i) {
var params = i.split(' ');
return {
browser: params[0] + ' ' + params[1],
note: params[2]
};
});
var notes = add.filter(function (i) {
return i.note;
}).map(function (i) {
return _this.browsers.prefix(i.browser) + ' ' + i.note;
});
notes = utils.uniq(notes);
add = add.filter(function (i) {
return _this.browsers.isSelected(i.browser);
}).map(function (i) {
var prefix = _this.browsers.prefix(i.browser);
if (i.note) {
return prefix + ' ' + i.note;
} else {
return prefix;
}
});
add = _this.sort(utils.uniq(add));
if (_this.options.flexbox === 'no-2009') {
add = add.filter(function (i) {
return i.indexOf('2009') === -1;
});
}
var all = data.browsers.map(function (i) {
return _this.browsers.prefix(i);
});
if (data.mistakes) {
all = all.concat(data.mistakes);
}
all = all.concat(notes);
all = utils.uniq(all);
if (add.length) {
selected.add[name] = add;
if (add.length < all.length) {
selected.remove[name] = all.filter(function (i) {
return add.indexOf(i) === -1;
});
}
} else {
selected.remove[name] = all;
}
};
for (var name in list) {
_loop(name);
}
return selected;
};
/**
* Sort vendor prefixes
*/
Prefixes.prototype.sort = function sort(prefixes) {
return prefixes.sort(function (a, b) {
var aLength = utils.removeNote(a).length;
var bLength = utils.removeNote(b).length;
if (aLength === bLength) {
return b.length - a.length;
} else {
return bLength - aLength;
}
});
};
/**
* Cache prefixes data to fast CSS processing
*/
Prefixes.prototype.preprocess = function preprocess(selected) {
var add = {
'selectors': [],
'@supports': new Supports(Prefixes, this)
};
for (var name in selected.add) {
var prefixes = selected.add[name];
if (name === '@keyframes' || name === '@viewport') {
add[name] = new AtRule(name, prefixes, this);
} else if (name === '@resolution') {
add[name] = new Resolution(name, prefixes, this);
} else if (this.data[name].selector) {
add.selectors.push(Selector.load(name, prefixes, this));
} else {
var props = this.data[name].props;
if (props) {
var value = Value.load(name, prefixes, this);
for (var _iterator = props, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prop = _ref;
if (!add[prop]) {
add[prop] = { values: [] };
}
add[prop].values.push(value);
}
} else {
var values = add[name] && add[name].values || [];
add[name] = Declaration.load(name, prefixes, this);
add[name].values = values;
}
}
}
var remove = { selectors: [] };
for (var _name in selected.remove) {
var _prefixes = selected.remove[_name];
if (this.data[_name].selector) {
var selector = Selector.load(_name, _prefixes);
for (var _iterator2 = _prefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var prefix = _ref2;
remove.selectors.push(selector.old(prefix));
}
} else if (_name === '@keyframes' || _name === '@viewport') {
for (var _iterator3 = _prefixes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var _prefix = _ref3;
var prefixed = '@' + _prefix + _name.slice(1);
remove[prefixed] = { remove: true };
}
} else if (_name === '@resolution') {
remove[_name] = new Resolution(_name, _prefixes, this);
} else {
var _props = this.data[_name].props;
if (_props) {
var _value = Value.load(_name, [], this);
for (var _iterator4 = _prefixes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var _prefix2 = _ref4;
var old = _value.old(_prefix2);
if (old) {
for (var _iterator5 = _props, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var _prop = _ref5;
if (!remove[_prop]) {
remove[_prop] = {};
}
if (!remove[_prop].values) {
remove[_prop].values = [];
}
remove[_prop].values.push(old);
}
}
}
} else {
for (var _iterator6 = _prefixes, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref6;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref6 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref6 = _i6.value;
}
var _prefix3 = _ref6;
var olds = this.decl(_name).old(_name, _prefix3);
if (_name === 'align-self') {
var a = add[_name] && add[_name].prefixes;
if (a) {
if (_prefix3 === '-webkit- 2009' && a.indexOf('-webkit-') !== -1) {
continue;
} else if (_prefix3 === '-webkit-' && a.indexOf('-webkit- 2009') !== -1) {
continue;
}
}
}
for (var _iterator7 = olds, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
var _ref7;
if (_isArray7) {
if (_i7 >= _iterator7.length) break;
_ref7 = _iterator7[_i7++];
} else {
_i7 = _iterator7.next();
if (_i7.done) break;
_ref7 = _i7.value;
}
var _prefixed = _ref7;
if (!remove[_prefixed]) {
remove[_prefixed] = {};
}
remove[_prefixed].remove = true;
}
}
}
}
}
return [add, remove];
};
/**
* Declaration loader with caching
*/
Prefixes.prototype.decl = function decl(prop) {
var decl = declsCache[prop];
if (decl) {
return decl;
} else {
declsCache[prop] = Declaration.load(prop);
return declsCache[prop];
}
};
/**
* Return unprefixed version of property
*/
Prefixes.prototype.unprefixed = function unprefixed(prop) {
var value = this.normalize(vendor.unprefixed(prop));
if (value === 'flex-direction') {
value = 'flex-flow';
}
return value;
};
/**
* Normalize prefix for remover
*/
Prefixes.prototype.normalize = function normalize(prop) {
return this.decl(prop).normalize(prop);
};
/**
* Return prefixed version of property
*/
Prefixes.prototype.prefixed = function prefixed(prop, prefix) {
prop = vendor.unprefixed(prop);
return this.decl(prop).prefixed(prop, prefix);
};
/**
* Return values, which must be prefixed in selected property
*/
Prefixes.prototype.values = function values(type, prop) {
var data = this[type];
var global = data['*'] && data['*'].values;
var values = data[prop] && data[prop].values;
if (global && values) {
return utils.uniq(global.concat(values));
} else {
return global || values || [];
}
};
/**
* Group declaration by unprefixed property to check them
*/
Prefixes.prototype.group = function group(decl) {
var _this2 = this;
var rule = decl.parent;
var index = rule.index(decl);
var length = rule.nodes.length;
var unprefixed = this.unprefixed(decl.prop);
var checker = function checker(step, callback) {
index += step;
while (index >= 0 && index < length) {
var other = rule.nodes[index];
if (other.type === 'decl') {
if (step === -1 && other.prop === unprefixed) {
if (!Browsers.withPrefix(other.value)) {
break;
}
}
if (_this2.unprefixed(other.prop) !== unprefixed) {
break;
} else if (callback(other) === true) {
return true;
}
if (step === +1 && other.prop === unprefixed) {
if (!Browsers.withPrefix(other.value)) {
break;
}
}
}
index += step;
}
return false;
};
return {
up: function up(callback) {
return checker(-1, callback);
},
down: function down(callback) {
return checker(+1, callback);
}
};
};
return Prefixes;
}();
module.exports = Prefixes;
},{"./at-rule":2,"./browsers":5,"./declaration":6,"./hacks/align-content":7,"./hacks/align-items":8,"./hacks/align-self":9,"./hacks/appearance":10,"./hacks/background-size":11,"./hacks/block-logical":12,"./hacks/border-image":13,"./hacks/border-radius":14,"./hacks/break-props":15,"./hacks/cross-fade":16,"./hacks/display-flex":17,"./hacks/display-grid":18,"./hacks/filter":20,"./hacks/filter-value":19,"./hacks/flex":29,"./hacks/flex-basis":21,"./hacks/flex-direction":22,"./hacks/flex-flow":23,"./hacks/flex-grow":24,"./hacks/flex-shrink":25,"./hacks/flex-values":27,"./hacks/flex-wrap":28,"./hacks/fullscreen":30,"./hacks/gradient":31,"./hacks/grid-column-align":32,"./hacks/grid-end":33,"./hacks/grid-row-align":34,"./hacks/grid-start":35,"./hacks/grid-template":36,"./hacks/image-rendering":37,"./hacks/image-set":38,"./hacks/inline-logical":39,"./hacks/intrinsic":40,"./hacks/justify-content":41,"./hacks/mask-border":42,"./hacks/order":43,"./hacks/pixelated":44,"./hacks/placeholder":45,"./hacks/text-decoration":46,"./hacks/text-emphasis-position":47,"./hacks/transform-decl":48,"./hacks/writing-mode":49,"./processor":55,"./resolution":56,"./selector":57,"./supports":58,"./transition":59,"./utils":60,"./value":61,"postcss/lib/vendor":551}],55:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Value = require('./value');
var OLD_DIRECTION = /(^|[^-])(linear|radial)-gradient\(\s*(top|left|right|bottom)/i;
var SIZES = ['width', 'height', 'min-width', 'max-width', 'min-height', 'max-height', 'inline-size', 'min-inline-size', 'max-inline-size', 'block-size', 'min-block-size', 'max-block-size'];
var Processor = function () {
function Processor(prefixes) {
_classCallCheck(this, Processor);
this.prefixes = prefixes;
}
/**
* Add necessary prefixes
*/
Processor.prototype.add = function add(css, result) {
var _this = this;
// At-rules
var resolution = this.prefixes.add['@resolution'];
var keyframes = this.prefixes.add['@keyframes'];
var viewport = this.prefixes.add['@viewport'];
var supports = this.prefixes.add['@supports'];
css.walkAtRules(function (rule) {
if (rule.name === 'keyframes') {
if (!_this.disabled(rule)) {
return keyframes && keyframes.process(rule);
}
} else if (rule.name === 'viewport') {
if (!_this.disabled(rule)) {
return viewport && viewport.process(rule);
}
} else if (rule.name === 'supports') {
if (_this.prefixes.options.supports !== false && !_this.disabled(rule)) {
return supports.process(rule);
}
} else if (rule.name === 'media' && rule.params.indexOf('-resolution') !== -1) {
if (!_this.disabled(rule)) {
return resolution && resolution.process(rule);
}
}
return undefined;
});
// Selectors
css.walkRules(function (rule) {
if (_this.disabled(rule)) return undefined;
return _this.prefixes.add.selectors.map(function (selector) {
return selector.process(rule, result);
});
});
css.walkDecls(function (decl) {
if (_this.disabledDecl(decl)) return undefined;
if (decl.prop === 'display' && decl.value === 'box') {
result.warn('You should write display: flex by final spec ' + 'instead of display: box', { node: decl });
return undefined;
}
if (decl.value.indexOf('linear-gradient') !== -1) {
if (OLD_DIRECTION.test(decl.value)) {
result.warn('Gradient has outdated direction syntax. ' + 'New syntax is like `to left` instead of `right`.', { node: decl });
}
}
if (decl.prop === 'text-emphasis-position') {
if (decl.value === 'under' || decl.value === 'over') {
result.warn('You should use 2 values for text-emphasis-position ' + 'For example, `under left` instead of just `under`.', { node: decl });
}
}
if (SIZES.indexOf(decl.prop) !== -1) {
if (decl.value.indexOf('fill-available') !== -1) {
result.warn('Replace fill-available to stretch, ' + 'because spec had been changed', { node: decl });
} else if (decl.value.indexOf('fill') !== -1) {
result.warn('Replace fill to stretch, ' + 'because spec had been changed', { node: decl });
}
}
if (_this.prefixes.options.flexbox !== false) {
if (decl.prop === 'grid-row-end' && decl.value.indexOf('span') === -1) {
result.warn('IE supports only grid-row-end with span. ' + 'You should add grid: false option to Autoprefixer ' + 'and use some JS grid polyfill for full spec support', { node: decl });
}
if (decl.prop === 'grid-row') {
if (decl.value.indexOf('/') !== -1 && decl.value.indexOf('span') === -1) {
result.warn('IE supports only grid-row with / and span. ' + 'You should add grid: false option ' + 'to Autoprefixer and use some JS grid polyfill ' + 'for full spec support', { node: decl });
}
}
}
var prefixer = void 0;
if (decl.prop === 'transition' || decl.prop === 'transition-property') {
// Transition
return _this.prefixes.transition.add(decl, result);
} else if (decl.prop === 'align-self') {
// align-self flexbox or grid
var display = _this.displayType(decl);
if (display !== 'grid' && _this.prefixes.options.flexbox !== false) {
prefixer = _this.prefixes.add['align-self'];
if (prefixer && prefixer.prefixes) {
prefixer.process(decl);
}
}
if (display !== 'flex' && _this.prefixes.options.grid !== false) {
prefixer = _this.prefixes.add['grid-row-align'];
if (prefixer && prefixer.prefixes) {
return prefixer.process(decl);
}
}
} else if (decl.prop === 'justify-self') {
// justify-self flexbox or grid
var _display = _this.displayType(decl);
if (_display !== 'flex' && _this.prefixes.options.grid !== false) {
prefixer = _this.prefixes.add['grid-column-align'];
if (prefixer && prefixer.prefixes) {
return prefixer.process(decl);
}
}
} else {
// Properties
prefixer = _this.prefixes.add[decl.prop];
if (prefixer && prefixer.prefixes) {
return prefixer.process(decl);
}
}
return undefined;
});
// Values
return css.walkDecls(function (decl) {
if (_this.disabledValue(decl)) return;
var unprefixed = _this.prefixes.unprefixed(decl.prop);
for (var _iterator = _this.prefixes.values('add', unprefixed), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var value = _ref;
value.process(decl, result);
}
Value.save(_this.prefixes, decl);
});
};
/**
* Remove unnecessary pefixes
*/
Processor.prototype.remove = function remove(css) {
var _this2 = this;
// At-rules
var resolution = this.prefixes.remove['@resolution'];
css.walkAtRules(function (rule, i) {
if (_this2.prefixes.remove['@' + rule.name]) {
if (!_this2.disabled(rule)) {
rule.parent.removeChild(i);
}
} else if (rule.name === 'media' && rule.params.indexOf('-resolution') !== -1 && resolution) {
resolution.clean(rule);
}
});
// Selectors
var _loop = function _loop(checker) {
css.walkRules(function (rule, i) {
if (checker.check(rule)) {
if (!_this2.disabled(rule)) {
rule.parent.removeChild(i);
}
}
});
};
for (var _iterator2 = this.prefixes.remove.selectors, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var checker = _ref2;
_loop(checker);
}
return css.walkDecls(function (decl, i) {
if (_this2.disabled(decl)) return;
var rule = decl.parent;
var unprefixed = _this2.prefixes.unprefixed(decl.prop);
// Transition
if (decl.prop === 'transition' || decl.prop === 'transition-property') {
_this2.prefixes.transition.remove(decl);
}
// Properties
if (_this2.prefixes.remove[decl.prop] && _this2.prefixes.remove[decl.prop].remove) {
var notHack = _this2.prefixes.group(decl).down(function (other) {
return _this2.prefixes.normalize(other.prop) === unprefixed;
});
if (unprefixed === 'flex-flow') {
notHack = true;
}
if (notHack && !_this2.withHackValue(decl)) {
if (decl.raw('before').indexOf('\n') > -1) {
_this2.reduceSpaces(decl);
}
rule.removeChild(i);
return;
}
}
// Values
for (var _iterator3 = _this2.prefixes.values('remove', unprefixed), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var checker = _ref3;
if (checker.check(decl.value)) {
unprefixed = checker.unprefixed;
var _notHack = _this2.prefixes.group(decl).down(function (other) {
return other.value.indexOf(unprefixed) !== -1;
});
if (_notHack) {
rule.removeChild(i);
return;
} else if (checker.clean) {
checker.clean(decl);
return;
}
}
}
});
};
/**
* Some rare old values, which is not in standard
*/
Processor.prototype.withHackValue = function withHackValue(decl) {
return decl.prop === '-webkit-background-clip' && decl.value === 'text';
};
/**
* Check for grid/flexbox options.
*/
Processor.prototype.disabledValue = function disabledValue(node) {
if (this.prefixes.options.grid === false && node.type === 'decl') {
if (node.prop === 'display' && node.value.indexOf('grid') !== -1) {
return true;
}
}
if (this.prefixes.options.flexbox === false && node.type === 'decl') {
if (node.prop === 'display' && node.value.indexOf('flex') !== -1) {
return true;
}
}
return this.disabled(node);
};
/**
* Check for grid/flexbox options.
*/
Processor.prototype.disabledDecl = function disabledDecl(node) {
if (this.prefixes.options.grid === false && node.type === 'decl') {
if (node.prop.indexOf('grid') !== -1 || node.prop === 'justify-items') {
return true;
}
}
if (this.prefixes.options.flexbox === false && node.type === 'decl') {
var other = ['order', 'justify-content', 'align-items', 'align-content'];
if (node.prop.indexOf('flex') !== -1 || other.indexOf(node.prop) !== -1) {
return true;
}
}
return this.disabled(node);
};
/**
* Check for control comment and global options
*/
Processor.prototype.disabled = function disabled(node) {
if (node._autoprefixerDisabled !== undefined) {
return node._autoprefixerDisabled;
} else if (node.nodes) {
var status = undefined;
node.each(function (i) {
if (i.type !== 'comment') {
return undefined;
}
if (/(!\s*)?autoprefixer:\s*off/i.test(i.text)) {
status = false;
return false;
} else if (/(!\s*)?autoprefixer:\s*on/i.test(i.text)) {
status = true;
return false;
}
return undefined;
});
var result = false;
if (status !== undefined) {
result = !status;
} else if (node.parent) {
result = this.disabled(node.parent);
}
node._autoprefixerDisabled = result;
return node._autoprefixerDisabled;
} else if (node.parent) {
node._autoprefixerDisabled = this.disabled(node.parent);
return node._autoprefixerDisabled;
} else {
// unknown state
return false;
}
};
/**
* Normalize spaces in cascade declaration group
*/
Processor.prototype.reduceSpaces = function reduceSpaces(decl) {
var stop = false;
this.prefixes.group(decl).up(function () {
stop = true;
return true;
});
if (stop) {
return;
}
var parts = decl.raw('before').split('\n');
var prevMin = parts[parts.length - 1].length;
var diff = false;
this.prefixes.group(decl).down(function (other) {
parts = other.raw('before').split('\n');
var last = parts.length - 1;
if (parts[last].length > prevMin) {
if (diff === false) {
diff = parts[last].length - prevMin;
}
parts[last] = parts[last].slice(0, -diff);
other.raws.before = parts.join('\n');
}
});
};
/**
* Is it flebox or grid rule
*/
Processor.prototype.displayType = function displayType(decl) {
for (var _iterator4 = decl.parent.nodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var i = _ref4;
if (i.prop === 'display') {
if (i.value.indexOf('flex') !== -1) {
return 'flex';
} else if (i.value.indexOf('grid') !== -1) {
return 'grid';
}
}
}
return false;
};
return Processor;
}();
module.exports = Processor;
},{"./value":61}],56:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Prefixer = require('./prefixer');
var utils = require('./utils');
var n2f = require('num2fraction');
var regexp = /(min|max)-resolution\s*:\s*\d*\.?\d+(dppx|dpi)/gi;
var split = /(min|max)-resolution(\s*:\s*)(\d*\.?\d+)(dppx|dpi)/i;
var Resolution = function (_Prefixer) {
_inherits(Resolution, _Prefixer);
function Resolution() {
_classCallCheck(this, Resolution);
return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments));
}
/**
* Return prefixed query name
*/
Resolution.prototype.prefixName = function prefixName(prefix, name) {
var newName = prefix === '-moz-' ? name + '--moz-device-pixel-ratio' : prefix + name + '-device-pixel-ratio';
return newName;
};
/**
* Return prefixed query
*/
Resolution.prototype.prefixQuery = function prefixQuery(prefix, name, colon, value, units) {
if (units === 'dpi') {
value = Number(value / 96);
}
if (prefix === '-o-') {
value = n2f(value);
}
return this.prefixName(prefix, name) + colon + value;
};
/**
* Remove prefixed queries
*/
Resolution.prototype.clean = function clean(rule) {
var _this2 = this;
if (!this.bad) {
this.bad = [];
for (var _iterator = this.prefixes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prefix = _ref;
this.bad.push(this.prefixName(prefix, 'min'));
this.bad.push(this.prefixName(prefix, 'max'));
}
}
rule.params = utils.editList(rule.params, function (queries) {
return queries.filter(function (query) {
return _this2.bad.every(function (i) {
return query.indexOf(i) === -1;
});
});
});
};
/**
* Add prefixed queries
*/
Resolution.prototype.process = function process(rule) {
var _this3 = this;
var parent = this.parentPrefix(rule);
var prefixes = parent ? [parent] : this.prefixes;
rule.params = utils.editList(rule.params, function (origin, prefixed) {
for (var _iterator2 = origin, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var query = _ref2;
if (query.indexOf('min-resolution') === -1 && query.indexOf('max-resolution') === -1) {
prefixed.push(query);
continue;
}
var _loop = function _loop(prefix) {
if (prefix === '-moz-' && rule.params.indexOf('dpi') !== -1) {
return 'continue';
} else {
var processed = query.replace(regexp, function (str) {
var parts = str.match(split);
return _this3.prefixQuery(prefix, parts[1], parts[2], parts[3], parts[4]);
});
prefixed.push(processed);
}
};
for (var _iterator3 = prefixes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var prefix = _ref3;
var _ret = _loop(prefix);
if (_ret === 'continue') continue;
}
prefixed.push(query);
}
return utils.uniq(prefixed);
});
};
return Resolution;
}(Prefixer);
module.exports = Resolution;
},{"./prefixer":53,"./utils":60,"num2fraction":522}],57:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldSelector = require('./old-selector');
var Prefixer = require('./prefixer');
var Browsers = require('./browsers');
var utils = require('./utils');
var Selector = function (_Prefixer) {
_inherits(Selector, _Prefixer);
function Selector(name, prefixes, all) {
_classCallCheck(this, Selector);
var _this = _possibleConstructorReturn(this, _Prefixer.call(this, name, prefixes, all));
_this.regexpCache = {};
return _this;
}
/**
* Is rule selectors need to be prefixed
*/
Selector.prototype.check = function check(rule) {
if (rule.selector.indexOf(this.name) !== -1) {
return !!rule.selector.match(this.regexp());
} else {
return false;
}
};
/**
* Return prefixed version of selector
*/
Selector.prototype.prefixed = function prefixed(prefix) {
return this.name.replace(/^([^\w]*)/, '$1' + prefix);
};
/**
* Lazy loadRegExp for name
*/
Selector.prototype.regexp = function regexp(prefix) {
if (this.regexpCache[prefix]) {
return this.regexpCache[prefix];
}
var name = prefix ? this.prefixed(prefix) : this.name;
this.regexpCache[prefix] = new RegExp('(^|[^:"\'=])' + utils.escapeRegexp(name), 'gi');
return this.regexpCache[prefix];
};
/**
* All possible prefixes
*/
Selector.prototype.possible = function possible() {
return Browsers.prefixes();
};
/**
* Return all possible selector prefixes
*/
Selector.prototype.prefixeds = function prefixeds(rule) {
if (rule._autoprefixerPrefixeds) {
return rule._autoprefixerPrefixeds;
}
var prefixeds = {};
for (var _iterator = this.possible(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prefix = _ref;
prefixeds[prefix] = this.replace(rule.selector, prefix);
}
rule._autoprefixerPrefixeds = prefixeds;
return rule._autoprefixerPrefixeds;
};
/**
* Is rule already prefixed before
*/
Selector.prototype.already = function already(rule, prefixeds, prefix) {
var index = rule.parent.index(rule) - 1;
while (index >= 0) {
var before = rule.parent.nodes[index];
if (before.type !== 'rule') {
return false;
}
var some = false;
for (var key in prefixeds) {
var prefixed = prefixeds[key];
if (before.selector === prefixed) {
if (prefix === key) {
return true;
} else {
some = true;
break;
}
}
}
if (!some) {
return false;
}
index -= 1;
}
return false;
};
/**
* Replace selectors by prefixed one
*/
Selector.prototype.replace = function replace(selector, prefix) {
return selector.replace(this.regexp(), '$1' + this.prefixed(prefix));
};
/**
* Clone and add prefixes for at-rule
*/
Selector.prototype.add = function add(rule, prefix) {
var prefixeds = this.prefixeds(rule);
if (this.already(rule, prefixeds, prefix)) {
return;
}
var cloned = this.clone(rule, { selector: prefixeds[prefix] });
rule.parent.insertBefore(rule, cloned);
};
/**
* Return function to fast find prefixed selector
*/
Selector.prototype.old = function old(prefix) {
return new OldSelector(this, prefix);
};
return Selector;
}(Prefixer);
module.exports = Selector;
},{"./browsers":5,"./old-selector":51,"./prefixer":53,"./utils":60}],58:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Browsers = require('./browsers');
var brackets = require('./brackets');
var Value = require('./value');
var utils = require('./utils');
var postcss = require('postcss');
var supported = [];
var data = require('caniuse-lite').feature(require('caniuse-lite/data/features/css-featurequeries.js'));
for (var browser in data.stats) {
var versions = data.stats[browser];
for (var version in versions) {
var support = versions[version];
if (/y/.test(support)) {
supported.push(browser + ' ' + version);
}
}
}
var Supports = function () {
function Supports(Prefixes, all) {
_classCallCheck(this, Supports);
this.Prefixes = Prefixes;
this.all = all;
}
/**
* Return prefixer only with @supports supported browsers
*/
Supports.prototype.prefixer = function prefixer() {
if (this.prefixerCache) {
return this.prefixerCache;
}
var filtered = this.all.browsers.selected.filter(function (i) {
return supported.indexOf(i) !== -1;
});
var browsers = new Browsers(this.all.browsers.data, filtered, this.all.options);
this.prefixerCache = new this.Prefixes(this.all.data, browsers, this.all.options);
return this.prefixerCache;
};
/**
* Parse string into declaration property and value
*/
Supports.prototype.parse = function parse(str) {
var _str$split = str.split(':'),
prop = _str$split[0],
value = _str$split[1];
if (!value) value = '';
return [prop.trim(), value.trim()];
};
/**
* Create virtual rule to process it by prefixer
*/
Supports.prototype.virtual = function virtual(str) {
var _parse = this.parse(str),
prop = _parse[0],
value = _parse[1];
var rule = postcss.parse('a{}').first;
rule.append({ prop: prop, value: value, raws: { before: '' } });
return rule;
};
/**
* Return array of Declaration with all necessary prefixes
*/
Supports.prototype.prefixed = function prefixed(str) {
var rule = this.virtual(str);
if (this.disabled(rule.first)) {
return rule.nodes;
}
var prefixer = this.prefixer().add[rule.first.prop];
prefixer && prefixer.process && prefixer.process(rule.first);
for (var _iterator = rule.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var decl = _ref;
for (var _iterator2 = this.prefixer().values('add', rule.first.prop), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var value = _ref2;
value.process(decl);
}
Value.save(this.all, decl);
}
return rule.nodes;
};
/**
* Return true if brackets node is "not" word
*/
Supports.prototype.isNot = function isNot(node) {
return typeof node === 'string' && /not\s*/i.test(node);
};
/**
* Return true if brackets node is "or" word
*/
Supports.prototype.isOr = function isOr(node) {
return typeof node === 'string' && /\s*or\s*/i.test(node);
};
/**
* Return true if brackets node is (prop: value)
*/
Supports.prototype.isProp = function isProp(node) {
return (typeof node === 'undefined' ? 'undefined' : _typeof(node)) === 'object' && node.length === 1 && typeof node[0] === 'string';
};
/**
* Return true if prefixed property has no unprefixed
*/
Supports.prototype.isHack = function isHack(all, unprefixed) {
var check = new RegExp('(\\(|\\s)' + utils.escapeRegexp(unprefixed) + ':');
return !check.test(all);
};
/**
* Return true if we need to remove node
*/
Supports.prototype.toRemove = function toRemove(str, all) {
var _parse2 = this.parse(str),
prop = _parse2[0],
value = _parse2[1];
var unprefixed = this.all.unprefixed(prop);
var cleaner = this.all.cleaner();
if (cleaner.remove[prop] && cleaner.remove[prop].remove && !this.isHack(all, unprefixed)) {
return true;
}
for (var _iterator3 = cleaner.values('remove', unprefixed), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var checker = _ref3;
if (checker.check(value)) {
return true;
}
}
return false;
};
/**
* Remove all unnecessary prefixes
*/
Supports.prototype.remove = function remove(nodes, all) {
var i = 0;
while (i < nodes.length) {
if (!this.isNot(nodes[i - 1]) && this.isProp(nodes[i]) && this.isOr(nodes[i + 1])) {
if (this.toRemove(nodes[i][0], all)) {
nodes.splice(i, 2);
} else {
i += 2;
}
} else {
if (_typeof(nodes[i]) === 'object') {
nodes[i] = this.remove(nodes[i], all);
}
i += 1;
}
}
return nodes;
};
/**
* Clean brackets with one child
*/
Supports.prototype.cleanBrackets = function cleanBrackets(nodes) {
var _this = this;
return nodes.map(function (i) {
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object') {
if (i.length === 1 && _typeof(i[0]) === 'object') {
return _this.cleanBrackets(i[0]);
} else {
return _this.cleanBrackets(i);
}
} else {
return i;
}
});
};
/**
* Add " or " between properties and convert it to brackets format
*/
Supports.prototype.convert = function convert(progress) {
var result = [''];
for (var _iterator4 = progress, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var i = _ref4;
result.push([i.prop + ': ' + i.value]);
result.push(' or ');
}
result[result.length - 1] = '';
return result;
};
/**
* Compress value functions into a string nodes
*/
Supports.prototype.normalize = function normalize(nodes) {
var _this2 = this;
if ((typeof nodes === 'undefined' ? 'undefined' : _typeof(nodes)) === 'object') {
nodes = nodes.filter(function (i) {
return i !== '';
});
if (typeof nodes[0] === 'string' && nodes[0].indexOf(':') !== -1) {
return [brackets.stringify(nodes)];
} else {
return nodes.map(function (i) {
return _this2.normalize(i);
});
}
} else {
return nodes;
}
};
/**
* Add prefixes
*/
Supports.prototype.add = function add(nodes, all) {
var _this3 = this;
return nodes.map(function (i) {
if (_this3.isProp(i)) {
var prefixed = _this3.prefixed(i[0]);
if (prefixed.length > 1) {
return _this3.convert(prefixed);
} else {
return i;
}
} else if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object') {
return _this3.add(i, all);
} else {
return i;
}
});
};
/**
* Add prefixed declaration
*/
Supports.prototype.process = function process(rule) {
var ast = brackets.parse(rule.params);
ast = this.normalize(ast);
ast = this.remove(ast, rule.params);
ast = this.add(ast, rule.params);
ast = this.cleanBrackets(ast);
rule.params = brackets.stringify(ast);
};
/**
* Check global options
*/
Supports.prototype.disabled = function disabled(node) {
if (this.all.options.grid === false) {
if (node.prop === 'display' && node.value.indexOf('grid') !== -1) {
return true;
}
if (node.prop.indexOf('grid') !== -1 || node.prop === 'justify-items') {
return true;
}
}
if (this.all.options.flexbox === false) {
if (node.prop === 'display' && node.value.indexOf('flex') !== -1) {
return true;
}
var other = ['order', 'justify-content', 'align-items', 'align-content'];
if (node.prop.indexOf('flex') !== -1 || other.indexOf(node.prop) !== -1) {
return true;
}
}
return false;
};
return Supports;
}();
module.exports = Supports;
},{"./brackets":4,"./browsers":5,"./utils":60,"./value":61,"caniuse-lite":513,"caniuse-lite/data/features/css-featurequeries.js":144,"postcss":541}],59:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var parser = require('postcss-value-parser');
var vendor = require('postcss/lib/vendor');
var list = require('postcss/lib/list');
var Transition = function () {
function Transition(prefixes) {
_classCallCheck(this, Transition);
Object.defineProperty(this, 'props', {
enumerable: true,
writable: true,
value: ['transition', 'transition-property']
});
this.prefixes = prefixes;
}
/**
* Process transition and add prefies for all necessary properties
*/
Transition.prototype.add = function add(decl, result) {
var _this = this;
var prefix = void 0,
prop = void 0;
var declPrefixes = this.prefixes.add[decl.prop] && this.prefixes.add[decl.prop].prefixes || [];
var params = this.parse(decl.value);
var names = params.map(function (i) {
return _this.findProp(i);
});
var added = [];
if (names.some(function (i) {
return i[0] === '-';
})) {
return;
}
for (var _iterator = params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var param = _ref;
prop = this.findProp(param);
if (prop[0] === '-') {
continue;
}
var prefixer = this.prefixes.add[prop];
if (!prefixer || !prefixer.prefixes) {
continue;
}
for (var _iterator3 = prefixer.prefixes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
prefix = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
prefix = _i3.value;
}
var prefixed = this.prefixes.prefixed(prop, prefix);
if (prefixed !== '-ms-transform' && names.indexOf(prefixed) === -1) {
if (!this.disabled(prop, prefix)) {
added.push(this.clone(prop, prefixed, param));
}
}
}
}
params = params.concat(added);
var value = this.stringify(params);
var webkitClean = this.stringify(this.cleanFromUnprefixed(params, '-webkit-'));
if (declPrefixes.indexOf('-webkit-') !== -1) {
this.cloneBefore(decl, '-webkit-' + decl.prop, webkitClean);
}
this.cloneBefore(decl, decl.prop, webkitClean);
if (declPrefixes.indexOf('-o-') !== -1) {
var operaClean = this.stringify(this.cleanFromUnprefixed(params, '-o-'));
this.cloneBefore(decl, '-o-' + decl.prop, operaClean);
}
for (var _iterator2 = declPrefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
prefix = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
prefix = _i2.value;
}
if (prefix !== '-webkit-' && prefix !== '-o-') {
var prefixValue = this.stringify(this.cleanOtherPrefixes(params, prefix));
this.cloneBefore(decl, prefix + decl.prop, prefixValue);
}
}
if (value !== decl.value && !this.already(decl, decl.prop, value)) {
this.checkForWarning(result, decl);
decl.cloneBefore();
decl.value = value;
}
};
/**
* Find property name
*/
Transition.prototype.findProp = function findProp(param) {
var prop = param[0].value;
if (/^\d/.test(prop)) {
for (var i = 0; i < param.length; i++) {
var token = param[i];
if (i !== 0 && token.type === 'word') {
return token.value;
}
}
}
return prop;
};
/**
* Does we aready have this declaration
*/
Transition.prototype.already = function already(decl, prop, value) {
return decl.parent.some(function (i) {
return i.prop === prop && i.value === value;
});
};
/**
* Add declaration if it is not exist
*/
Transition.prototype.cloneBefore = function cloneBefore(decl, prop, value) {
if (!this.already(decl, prop, value)) {
decl.cloneBefore({ prop: prop, value: value });
}
};
/**
* Show transition-property warning
*/
Transition.prototype.checkForWarning = function checkForWarning(result, decl) {
if (decl.prop === 'transition-property') {
decl.parent.each(function (i) {
if (i.type !== 'decl') {
return undefined;
}
if (i.prop.indexOf('transition-') !== 0) {
return undefined;
}
if (i.prop === 'transition-property') {
return undefined;
}
if (list.comma(i.value).length > 1) {
decl.warn(result, 'Replace transition-property to transition, ' + 'because Autoprefixer could not support ' + 'any cases of transition-property ' + 'and other transition-*');
}
return false;
});
}
};
/**
* Process transition and remove all unnecessary properties
*/
Transition.prototype.remove = function remove(decl) {
var _this2 = this;
var params = this.parse(decl.value);
params = params.filter(function (i) {
var prop = _this2.prefixes.remove[_this2.findProp(i)];
return !prop || !prop.remove;
});
var value = this.stringify(params);
if (decl.value === value) {
return;
}
if (params.length === 0) {
decl.remove();
return;
}
var double = decl.parent.some(function (i) {
return i.prop === decl.prop && i.value === value;
});
var smaller = decl.parent.some(function (i) {
return i !== decl && i.prop === decl.prop && i.value.length > value.length;
});
if (double || smaller) {
decl.remove();
} else {
decl.value = value;
}
};
/**
* Parse properties list to array
*/
Transition.prototype.parse = function parse(value) {
var ast = parser(value);
var result = [];
var param = [];
for (var _iterator4 = ast.nodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref2;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref2 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref2 = _i4.value;
}
var node = _ref2;
param.push(node);
if (node.type === 'div' && node.value === ',') {
result.push(param);
param = [];
}
}
result.push(param);
return result.filter(function (i) {
return i.length > 0;
});
};
/**
* Return properties string from array
*/
Transition.prototype.stringify = function stringify(params) {
if (params.length === 0) {
return '';
}
var nodes = [];
for (var _iterator5 = params, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref3;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref3 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref3 = _i5.value;
}
var param = _ref3;
if (param[param.length - 1].type !== 'div') {
param.push(this.div(params));
}
nodes = nodes.concat(param);
}
if (nodes[0].type === 'div') {
nodes = nodes.slice(1);
}
if (nodes[nodes.length - 1].type === 'div') {
nodes = nodes.slice(0, +-2 + 1 || undefined);
}
return parser.stringify({ nodes: nodes });
};
/**
* Return new param array with different name
*/
Transition.prototype.clone = function clone(origin, name, param) {
var result = [];
var changed = false;
for (var _iterator6 = param, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref4;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref4 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref4 = _i6.value;
}
var i = _ref4;
if (!changed && i.type === 'word' && i.value === origin) {
result.push({ type: 'word', value: name });
changed = true;
} else {
result.push(i);
}
}
return result;
};
/**
* Find or create seperator
*/
Transition.prototype.div = function div(params) {
for (var _iterator7 = params, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
var _ref5;
if (_isArray7) {
if (_i7 >= _iterator7.length) break;
_ref5 = _iterator7[_i7++];
} else {
_i7 = _iterator7.next();
if (_i7.done) break;
_ref5 = _i7.value;
}
var param = _ref5;
for (var _iterator8 = param, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) {
var _ref6;
if (_isArray8) {
if (_i8 >= _iterator8.length) break;
_ref6 = _iterator8[_i8++];
} else {
_i8 = _iterator8.next();
if (_i8.done) break;
_ref6 = _i8.value;
}
var node = _ref6;
if (node.type === 'div' && node.value === ',') {
return node;
}
}
}
return { type: 'div', value: ',', after: ' ' };
};
Transition.prototype.cleanOtherPrefixes = function cleanOtherPrefixes(params, prefix) {
var _this3 = this;
return params.filter(function (param) {
var current = vendor.prefix(_this3.findProp(param));
return current === '' || current === prefix;
});
};
/**
* Remove all non-webkit prefixes and unprefixed params if we have prefixed
*/
Transition.prototype.cleanFromUnprefixed = function cleanFromUnprefixed(params, prefix) {
var _this4 = this;
var remove = params.map(function (i) {
return _this4.findProp(i);
}).filter(function (i) {
return i.slice(0, prefix.length) === prefix;
}).map(function (i) {
return _this4.prefixes.unprefixed(i);
});
var result = [];
for (var _iterator9 = params, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) {
var _ref7;
if (_isArray9) {
if (_i9 >= _iterator9.length) break;
_ref7 = _iterator9[_i9++];
} else {
_i9 = _iterator9.next();
if (_i9.done) break;
_ref7 = _i9.value;
}
var param = _ref7;
var prop = this.findProp(param);
var p = vendor.prefix(prop);
if (remove.indexOf(prop) === -1 && (p === prefix || p === '')) {
result.push(param);
}
}
return result;
};
/**
* Check property for disabled by option
*/
Transition.prototype.disabled = function disabled(prop, prefix) {
var other = ['order', 'justify-content', 'align-self', 'align-content'];
if (prop.indexOf('flex') !== -1 || other.indexOf(prop) !== -1) {
if (this.prefixes.options.flexbox === false) {
return true;
} else if (this.prefixes.options.flexbox === 'no-2009') {
return prefix.indexOf('2009') !== -1;
}
}
return undefined;
};
return Transition;
}();
module.exports = Transition;
},{"postcss-value-parser":524,"postcss/lib/list":536,"postcss/lib/vendor":551}],60:[function(require,module,exports){
'use strict';
var list = require('postcss/lib/list');
module.exports = {
/**
* Throw special error, to tell beniary,
* that this error is from Autoprefixer.
*/
error: function error(text) {
var err = new Error(text);
err.autoprefixer = true;
throw err;
},
/**
* Return array, that doesn’t contain duplicates.
*/
uniq: function uniq(array) {
var filtered = [];
for (var _iterator = array, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
if (filtered.indexOf(i) === -1) {
filtered.push(i);
}
}
return filtered;
},
/**
* Return "-webkit-" on "-webkit- old"
*/
removeNote: function removeNote(string) {
if (string.indexOf(' ') === -1) {
return string;
} else {
return string.split(' ')[0];
}
},
/**
* Escape RegExp symbols
*/
escapeRegexp: function escapeRegexp(string) {
return string.replace(/[.?*+\^\$\[\]\\(){}|\-]/g, '\\$&');
},
/**
* Return regexp to check, that CSS string contain word
*/
regexp: function regexp(word) {
var escape = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (escape) {
word = this.escapeRegexp(word);
}
return new RegExp('(^|[\\s,(])(' + word + '($|[\\s(,]))', 'gi');
},
/**
* Change comma list
*/
editList: function editList(value, callback) {
var origin = list.comma(value);
var changed = callback(origin, []);
if (origin === changed) {
return value;
} else {
var join = value.match(/,\s*/);
join = join ? join[0] : ', ';
return changed.join(join);
}
}
};
},{"postcss/lib/list":536}],61:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Prefixer = require('./prefixer');
var OldValue = require('./old-value');
var utils = require('./utils');
var vendor = require('postcss/lib/vendor');
var Value = function (_Prefixer) {
_inherits(Value, _Prefixer);
function Value() {
_classCallCheck(this, Value);
return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments));
}
/**
* Clone decl for each prefixed values
*/
Value.save = function save(prefixes, decl) {
var _this2 = this;
var prop = decl.prop;
var result = [];
for (var prefix in decl._autoprefixerValues) {
var value = decl._autoprefixerValues[prefix];
if (value === decl.value) {
continue;
}
var item = void 0;
var propPrefix = vendor.prefix(prop);
if (propPrefix === prefix) {
item = decl.value = value;
} else if (propPrefix === '-pie-') {
continue;
} else {
(function () {
var prefixed = prefixes.prefixed(prop, prefix);
var rule = decl.parent;
if (rule.every(function (i) {
return i.prop !== prefixed;
})) {
var trimmed = value.replace(/\s+/, ' ');
var already = rule.some(function (i) {
return i.prop === decl.prop && i.value.replace(/\s+/, ' ') === trimmed;
});
if (!already) {
var cloned = _this2.clone(decl, { value: value });
item = decl.parent.insertBefore(decl, cloned);
}
}
})();
}
result.push(item);
}
return result;
};
/**
* Is declaration need to be prefixed
*/
Value.prototype.check = function check(decl) {
var value = decl.value;
if (value.indexOf(this.name) !== -1) {
return !!value.match(this.regexp());
} else {
return false;
}
};
/**
* Lazy regexp loading
*/
Value.prototype.regexp = function regexp() {
return this.regexpCache || (this.regexpCache = utils.regexp(this.name));
};
/**
* Add prefix to values in string
*/
Value.prototype.replace = function replace(string, prefix) {
return string.replace(this.regexp(), '$1' + prefix + '$2');
};
/**
* Get value with comments if it was not changed
*/
Value.prototype.value = function value(decl) {
if (decl.raws.value && decl.raws.value.value === decl.value) {
return decl.raws.value.raw;
} else {
return decl.value;
}
};
/**
* Save values with next prefixed token
*/
Value.prototype.add = function add(decl, prefix) {
if (!decl._autoprefixerValues) {
decl._autoprefixerValues = {};
}
var value = decl._autoprefixerValues[prefix] || this.value(decl);
value = this.replace(value, prefix);
if (value) {
decl._autoprefixerValues[prefix] = value;
}
};
/**
* Return function to fast find prefixed value
*/
Value.prototype.old = function old(prefix) {
return new OldValue(this.name, prefix + this.name);
};
return Value;
}(Prefixer);
module.exports = Value;
},{"./old-value":52,"./prefixer":53,"./utils":60,"postcss/lib/vendor":551}],62:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var colorConvert = require('color-convert');
var wrapAnsi16 = function wrapAnsi16(fn, offset) {
return function () {
var code = fn.apply(colorConvert, arguments);
return '\x1B[' + (code + offset) + 'm';
};
};
var wrapAnsi256 = function wrapAnsi256(fn, offset) {
return function () {
var code = fn.apply(colorConvert, arguments);
return '\x1B[' + (38 + offset) + ';5;' + code + 'm';
};
};
var wrapAnsi16m = function wrapAnsi16m(fn, offset) {
return function () {
var rgb = fn.apply(colorConvert, arguments);
return '\x1B[' + (38 + offset) + ';2;' + rgb[0] + ';' + rgb[1] + ';' + rgb[2] + 'm';
};
};
function assembleStyles() {
var styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
// Bright color
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
// Fix humans
styles.color.grey = styles.color.gray;
Object.keys(styles).forEach(function (groupName) {
var group = styles[groupName];
Object.keys(group).forEach(function (styleName) {
var style = group[styleName];
styles[styleName] = {
open: '\x1B[' + style[0] + 'm',
close: '\x1B[' + style[1] + 'm'
};
group[styleName] = styles[styleName];
});
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
});
var rgb2rgb = function rgb2rgb(r, g, b) {
return [r, g, b];
};
styles.color.close = '\x1B[39m';
styles.bgColor.close = '\x1B[49m';
styles.color.ansi = {};
styles.color.ansi256 = {};
styles.color.ansi16m = {
rgb: wrapAnsi16m(rgb2rgb, 0)
};
styles.bgColor.ansi = {};
styles.bgColor.ansi256 = {};
styles.bgColor.ansi16m = {
rgb: wrapAnsi16m(rgb2rgb, 10)
};
for (var _iterator = Object.keys(colorConvert), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var key = _ref;
if (_typeof(colorConvert[key]) !== 'object') {
continue;
}
var suite = colorConvert[key];
if ('ansi16' in suite) {
styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
}
if ('ansi256' in suite) {
styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
}
if ('rgb' in suite) {
styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
}
}
return styles;
}
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});
},{"color-convert":515}],63:[function(require,module,exports){
'use strict';
exports.byteLength = byteLength;
exports.toByteArray = toByteArray;
exports.fromByteArray = fromByteArray;
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
revLookup['-'.charCodeAt(0)] = 62;
revLookup['_'.charCodeAt(0)] = 63;
function placeHoldersCount(b64) {
var len = b64.length;
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4');
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
}
function byteLength(b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64);
}
function toByteArray(b64) {
var i, l, tmp, placeHolders, arr;
var len = b64.length;
placeHolders = placeHoldersCount(b64);
arr = new Arr(len * 3 / 4 - placeHolders);
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len;
var L = 0;
for (i = 0; i < l; i += 4) {
tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
arr[L++] = tmp >> 16 & 0xFF;
arr[L++] = tmp >> 8 & 0xFF;
arr[L++] = tmp & 0xFF;
}
if (placeHolders === 2) {
tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
arr[L++] = tmp & 0xFF;
} else if (placeHolders === 1) {
tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
arr[L++] = tmp >> 8 & 0xFF;
arr[L++] = tmp & 0xFF;
}
return arr;
}
function tripletToBase64(num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
output.push(tripletToBase64(tmp));
}
return output.join('');
}
function fromByteArray(uint8) {
var tmp;
var len = uint8.length;
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
var output = '';
var parts = [];
var maxChunkLength = 16383; // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
output += lookup[tmp >> 2];
output += lookup[tmp << 4 & 0x3F];
output += '==';
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
output += lookup[tmp >> 10];
output += lookup[tmp >> 4 & 0x3F];
output += lookup[tmp << 2 & 0x3F];
output += '=';
}
parts.push(output);
return parts.join('');
}
},{}],64:[function(require,module,exports){
"use strict";
},{}],65:[function(require,module,exports){
(function (process){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var path = require('path');
var e2c = require('electron-to-chromium/versions');
var fs = require('fs');
var caniuse = require('caniuse-lite').agents;
var region = require('caniuse-lite').region;
function normalize(versions) {
return versions.filter(function (version) {
return typeof version === 'string';
});
}
var FLOAT_RANGE = /^\d+(\.\d+)?(-\d+(\.\d+)?)*$/;
var IS_SECTION = /^\s*\[(.+)\]\s*$/;
function uniq(array) {
var filtered = [];
for (var i = 0; i < array.length; i++) {
if (filtered.indexOf(array[i]) === -1) filtered.push(array[i]);
}
return filtered;
}
function BrowserslistError(message) {
this.name = 'BrowserslistError';
this.message = message || '';
this.browserslist = true;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, BrowserslistError);
}
}
BrowserslistError.prototype = Error.prototype;
// Helpers
function error(name) {
throw new BrowserslistError(name);
}
function fillUsage(result, name, data) {
for (var i in data) {
result[name + ' ' + i] = data[i];
}
}
var cacheEnabled = !(process && process.env && process.env.BROWSERSLIST_DISABLE_CACHE);
var filenessCache = {};
var configCache = {};
function isFile(file) {
if (!fs.existsSync) {
return false;
}
if (file in filenessCache) {
return filenessCache[file];
}
var result = fs.existsSync(file) && fs.statSync(file).isFile();
if (cacheEnabled) {
filenessCache[file] = result;
}
return result;
}
function eachParent(file, callback) {
var loc = path.resolve(file);
do {
var result = callback(loc);
if (typeof result !== 'undefined') return result;
} while (loc !== (loc = path.dirname(loc)));
return undefined;
}
function getStat(opts) {
if (opts.stats) {
return opts.stats;
} else if (process.env.BROWSERSLIST_STATS) {
return process.env.BROWSERSLIST_STATS;
} else if (opts.path) {
return eachParent(opts.path, function (dir) {
var file = path.join(dir, 'browserslist-stats.json');
if (isFile(file)) {
return file;
}
});
}
}
function parsePackage(file) {
var config = JSON.parse(fs.readFileSync(file)).browserslist;
if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config.length) {
config = { defaults: config };
}
return config;
}
function pickEnv(config, opts) {
if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) !== 'object') return config;
var env;
if (typeof opts.env === 'string') {
env = opts.env;
} else if (typeof process.env.BROWSERSLIST_ENV === 'string') {
env = process.env.BROWSERSLIST_ENV;
} else if (typeof process.env.NODE_ENV === 'string') {
env = process.env.NODE_ENV;
} else {
env = 'development';
}
return config[env] || config.defaults;
}
function generateFilter(sign, version) {
version = parseFloat(version);
if (sign === '>') {
return function (v) {
return parseFloat(v) > version;
};
} else if (sign === '>=') {
return function (v) {
return parseFloat(v) >= version;
};
} else if (sign === '<') {
return function (v) {
return parseFloat(v) < version;
};
} else if (sign === '<=') {
return function (v) {
return parseFloat(v) <= version;
};
}
}
function compareStrings(a, b) {
if (a < b) return -1;
if (a > b) return +1;
return 0;
}
/**
* Return array of browsers by selection queries.
*
* @param {string[]} queries Browser queries.
* @param {object} opts Options.
* @param {string} [opts.path="."] Path to processed file.
* It will be used to find config files.
* @param {string} [opts.env="development"] Processing environment.
* It will be used to take right
* queries from config file.
* @param {string} [opts.config] Path to config file with queries.
* @param {object} [opts.stats] Custom browser usage statistics
* for "> 1% in my stats" query.
* @return {string[]} Array with browser names in Can I Use.
*
* @example
* browserslist('IE >= 10, IE 8') //=> ['ie 11', 'ie 10', 'ie 8']
*/
var browserslist = function browserslist(queries, opts) {
if (typeof opts === 'undefined') opts = {};
if (!opts.hasOwnProperty('path')) {
opts.path = path.resolve('.');
}
if (typeof queries === 'undefined' || queries === null) {
if (process.env.BROWSERSLIST) {
queries = process.env.BROWSERSLIST;
} else if (opts.config || process.env.BROWSERSLIST_CONFIG) {
var file = opts.config || process.env.BROWSERSLIST_CONFIG;
if (path.basename(file) === 'package.json') {
queries = pickEnv(parsePackage(file), opts);
} else {
queries = pickEnv(browserslist.readConfig(file), opts);
}
} else if (opts.path) {
queries = pickEnv(browserslist.findConfig(opts.path), opts);
}
}
if (typeof queries === 'undefined' || queries === null) {
queries = browserslist.defaults;
}
if (typeof queries === 'string') {
queries = queries.split(/,\s*/);
}
var context = {};
var stats = getStat(opts);
if (stats) {
if (typeof stats === 'string') {
try {
stats = JSON.parse(fs.readFileSync(stats));
} catch (e) {
error('Can\'t read ' + stats);
}
}
if ('dataByBrowser' in stats) {
stats = stats.dataByBrowser;
}
context.customUsage = {};
for (var browser in stats) {
fillUsage(context.customUsage, browser, stats[browser]);
}
}
var result = [];
queries.forEach(function (selection, index) {
if (selection.trim() === '') return;
var exclude = selection.indexOf('not ') === 0;
if (exclude) {
if (index === 0) {
error('Write any browsers query (for instance, `defaults`) ' + 'before `' + selection + '`');
}
selection = selection.slice(4);
}
for (var i in browserslist.queries) {
var type = browserslist.queries[i];
var match = selection.match(type.regexp);
if (match) {
var args = [context].concat(match.slice(1));
var array = type.select.apply(browserslist, args);
if (exclude) {
array = array.concat(array.map(function (j) {
return j.replace(/\s\d+/, ' 0');
}));
result = result.filter(function (j) {
return array.indexOf(j) === -1;
});
} else {
result = result.concat(array);
}
return;
}
}
error('Unknown browser query `' + selection + '`');
});
result = result.map(function (i) {
var parts = i.split(' ');
var name = parts[0];
var version = parts[1];
if (version === '0') {
return name + ' ' + browserslist.byName(name).versions[0];
} else {
return i;
}
}).sort(function (name1, name2) {
name1 = name1.split(' ');
name2 = name2.split(' ');
if (name1[0] === name2[0]) {
if (FLOAT_RANGE.test(name1[1]) && FLOAT_RANGE.test(name2[1])) {
return parseFloat(name2[1]) - parseFloat(name1[1]);
} else {
return compareStrings(name2[1], name1[1]);
}
} else {
return compareStrings(name1[0], name2[0]);
}
});
return uniq(result);
};
var normalizeVersion = function normalizeVersion(data, version) {
if (data.versions.indexOf(version) !== -1) {
return version;
} else if (browserslist.versionAliases[data.name][version]) {
return browserslist.versionAliases[data.name][version];
} else if (data.versions.length === 1) {
return data.versions[0];
}
};
var loadCountryStatistics = function loadCountryStatistics(country) {
if (!browserslist.usage[country]) {
var usage = {};
var data = region(require('caniuse-lite/data/regions/' + country + '.js'));
for (var i in data) {
fillUsage(usage, i, data[i]);
}
browserslist.usage[country] = usage;
}
};
// Will be filled by Can I Use data below
browserslist.data = {};
browserslist.usage = {
global: {},
custom: null
};
// Default browsers query
browserslist.defaults = ['> 1%', 'last 2 versions', 'Firefox ESR'];
// Browser names aliases
browserslist.aliases = {
fx: 'firefox',
ff: 'firefox',
ios: 'ios_saf',
explorer: 'ie',
blackberry: 'bb',
explorermobile: 'ie_mob',
operamini: 'op_mini',
operamobile: 'op_mob',
chromeandroid: 'and_chr',
firefoxandroid: 'and_ff',
ucandroid: 'and_uc',
qqandroid: 'and_qq'
};
// Aliases to work with joined versions like `ios_saf 7.0-7.1`
browserslist.versionAliases = {};
// Get browser data by alias or case insensitive name
browserslist.byName = function (name) {
name = name.toLowerCase();
name = browserslist.aliases[name] || name;
return browserslist.data[name];
};
// Get browser data by alias or case insensitive name and throw error
// on unknown browser
browserslist.checkName = function (name) {
var data = browserslist.byName(name);
if (!data) error('Unknown browser ' + name);
return data;
};
// Read and parse config
browserslist.readConfig = function (file) {
if (!isFile(file)) {
error('Can\'t read ' + file + ' config');
}
return browserslist.parseConfig(fs.readFileSync(file));
};
// Find config, read file and parse it
browserslist.findConfig = function (from) {
from = path.resolve(from);
var cacheKey = isFile(from) ? path.dirname(from) : from;
if (cacheKey in configCache) {
return configCache[cacheKey];
}
var resolved = eachParent(from, function (dir) {
var config = path.join(dir, 'browserslist');
var pkg = path.join(dir, 'package.json');
var rc = path.join(dir, '.browserslistrc');
var pkgBrowserslist;
if (isFile(pkg)) {
try {
pkgBrowserslist = parsePackage(pkg);
} catch (e) {
console.warn('[Browserslist] Could not parse ' + pkg + '. ' + 'Ignoring it.');
}
}
if (isFile(config) && pkgBrowserslist) {
error(dir + ' contains both browserslist ' + 'and package.json with browsers');
} else if (isFile(rc) && pkgBrowserslist) {
error(dir + ' contains both .browserslistrc ' + 'and package.json with browsers');
} else if (isFile(config) && isFile(rc)) {
error(dir + ' contains both .browserslistrc and browserslist');
} else if (isFile(config)) {
return browserslist.readConfig(config);
} else if (isFile(rc)) {
return browserslist.readConfig(rc);
} else if (pkgBrowserslist) {
return pkgBrowserslist;
}
});
if (cacheEnabled) {
configCache[cacheKey] = resolved;
}
return resolved;
};
/**
* Return browsers market coverage.
*
* @param {string[]} browsers Browsers names in Can I Use.
* @param {string} [country="global"] Which country statistics should be used.
*
* @return {number} Total market coverage for all selected browsers.
*
* @example
* browserslist.coverage(browserslist('> 1% in US'), 'US') //=> 83.1
*/
browserslist.coverage = function (browsers, country) {
if (country && country !== 'global') {
country = country.toUpperCase();
loadCountryStatistics(country);
} else {
country = 'global';
}
return browsers.reduce(function (all, i) {
var usage = browserslist.usage[country][i];
if (usage === undefined) {
usage = browserslist.usage[country][i.replace(/ [\d.]+$/, ' 0')];
}
return all + (usage || 0);
}, 0);
};
// Return array of queries from config content
browserslist.parseConfig = function (string) {
var result = { defaults: [] };
var section = 'defaults';
string.toString().replace(/#[^\n]*/g, '').split(/\n/).map(function (line) {
return line.trim();
}).filter(function (line) {
return line !== '';
}).forEach(function (line) {
if (IS_SECTION.test(line)) {
section = line.match(IS_SECTION)[1].trim();
result[section] = result[section] || [];
} else {
result[section].push(line);
}
});
return result;
};
// Clear internal caches
browserslist.clearCaches = function () {
filenessCache = {};
configCache = {};
};
browserslist.queries = {
lastVersions: {
regexp: /^last\s+(\d+)\s+versions?$/i,
select: function select(context, versions) {
var selected = [];
Object.keys(caniuse).forEach(function (name) {
var data = browserslist.byName(name);
if (!data) return;
var array = data.released.slice(-versions);
array = array.map(function (v) {
return data.name + ' ' + v;
});
selected = selected.concat(array);
});
return selected;
}
},
lastByBrowser: {
regexp: /^last\s+(\d+)\s+(\w+)\s+versions?$/i,
select: function select(context, versions, name) {
var data = browserslist.checkName(name);
return data.released.slice(-versions).map(function (v) {
return data.name + ' ' + v;
});
}
},
globalStatistics: {
regexp: /^(>=?)\s*(\d*\.?\d+)%$/,
select: function select(context, sign, popularity) {
popularity = parseFloat(popularity);
var result = [];
for (var version in browserslist.usage.global) {
if (sign === '>') {
if (browserslist.usage.global[version] > popularity) {
result.push(version);
}
} else if (browserslist.usage.global[version] >= popularity) {
result.push(version);
}
}
return result;
}
},
customStatistics: {
regexp: /^(>=?)\s*(\d*\.?\d+)%\s+in\s+my\s+stats$/,
select: function select(context, sign, popularity) {
popularity = parseFloat(popularity);
var result = [];
if (!context.customUsage) {
error('Custom usage statistics was not provided');
}
for (var version in context.customUsage) {
if (sign === '>') {
if (context.customUsage[version] > popularity) {
result.push(version);
}
} else if (context.customUsage[version] >= popularity) {
result.push(version);
}
}
return result;
}
},
countryStatistics: {
regexp: /^(>=?)\s*(\d*\.?\d+)%\s+in\s+(\w\w)$/,
select: function select(context, sign, popularity, country) {
popularity = parseFloat(popularity);
country = country.toUpperCase();
var result = [];
loadCountryStatistics(country);
var usage = browserslist.usage[country];
for (var version in usage) {
if (sign === '>') {
if (usage[version] > popularity) {
result.push(version);
}
} else if (usage[version] >= popularity) {
result.push(version);
}
}
return result;
}
},
electronRange: {
regexp: /^electron\s+([\d\.]+)\s*-\s*([\d\.]+)$/i,
select: function select(context, from, to) {
if (!e2c[from]) error('Unknown version ' + from + ' of electron');
if (!e2c[to]) error('Unknown version ' + to + ' of electron');
from = parseFloat(from);
to = parseFloat(to);
return Object.keys(e2c).filter(function (i) {
var parsed = parseFloat(i);
return parsed >= from && parsed <= to;
}).map(function (i) {
return 'chrome ' + e2c[i];
});
}
},
range: {
regexp: /^(\w+)\s+([\d\.]+)\s*-\s*([\d\.]+)$/i,
select: function select(context, name, from, to) {
var data = browserslist.checkName(name);
from = parseFloat(normalizeVersion(data, from) || from);
to = parseFloat(normalizeVersion(data, to) || to);
var filter = function filter(v) {
var parsed = parseFloat(v);
return parsed >= from && parsed <= to;
};
return data.released.filter(filter).map(function (v) {
return data.name + ' ' + v;
});
}
},
electronVersions: {
regexp: /^electron\s*(>=?|<=?)\s*([\d\.]+)$/i,
select: function select(context, sign, version) {
return Object.keys(e2c).filter(generateFilter(sign, version)).map(function (i) {
return 'chrome ' + e2c[i];
});
}
},
versions: {
regexp: /^(\w+)\s*(>=?|<=?)\s*([\d\.]+)$/,
select: function select(context, name, sign, version) {
var data = browserslist.checkName(name);
var alias = normalizeVersion(data, version);
if (alias) {
version = alias;
}
return data.released.filter(generateFilter(sign, version)).map(function (v) {
return data.name + ' ' + v;
});
}
},
esr: {
regexp: /^(firefox|ff|fx)\s+esr$/i,
select: function select() {
return ['firefox 52'];
}
},
opMini: {
regexp: /(operamini|op_mini)\s+all/i,
select: function select() {
return ['op_mini all'];
}
},
electron: {
regexp: /^electron\s+([\d\.]+)$/i,
select: function select(context, version) {
var chrome = e2c[version];
if (!chrome) error('Unknown version ' + version + ' of electron');
return ['chrome ' + chrome];
}
},
direct: {
regexp: /^(\w+)\s+(tp|[\d\.]+)$/i,
select: function select(context, name, version) {
if (/tp/i.test(version)) version = 'TP';
var data = browserslist.checkName(name);
var alias = normalizeVersion(data, version);
if (alias) {
version = alias;
} else {
if (version.indexOf('.') === -1) {
alias = version + '.0';
} else if (/\.0$/.test(version)) {
alias = version.replace(/\.0$/, '');
}
alias = normalizeVersion(data, alias);
if (alias) {
version = alias;
} else {
error('Unknown version ' + version + ' of ' + name);
}
}
return [data.name + ' ' + version];
}
},
defaults: {
regexp: /^defaults$/i,
select: function select() {
return browserslist(browserslist.defaults);
}
}
};
// Get and convert Can I Use data
(function () {
for (var name in caniuse) {
var browser = caniuse[name];
browserslist.data[name] = {
name: name,
versions: normalize(caniuse[name].versions),
released: normalize(caniuse[name].versions.slice(0, -3))
};
fillUsage(browserslist.usage.global, name, browser.usage_global);
browserslist.versionAliases[name] = {};
for (var i = 0; i < browser.versions.length; i++) {
var full = browser.versions[i];
if (!full) continue;
if (full.indexOf('-') !== -1) {
var interval = full.split('-');
for (var j = 0; j < interval.length; j++) {
browserslist.versionAliases[name][interval[j]] = full;
}
}
}
}
})();
module.exports = browserslist;
}).call(this,require('_process'))
},{"_process":557,"caniuse-lite":513,"electron-to-chromium/versions":518,"fs":64,"path":523}],66:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict';
var base64 = require('base64-js');
var ieee754 = require('ieee754');
exports.Buffer = Buffer;
exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50;
var K_MAX_LENGTH = 0x7fffffff;
exports.kMaxLength = K_MAX_LENGTH;
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') {
console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.');
}
function typedArraySupport() {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1);
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function foo() {
return 42;
} };
return arr.foo() === 42;
} catch (e) {
return false;
}
}
function createBuffer(length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length');
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length);
buf.__proto__ = Buffer.prototype;
return buf;
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer(arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error('If encoding is specified then the first argument must be a string');
}
return allocUnsafe(arg);
}
return from(arg, encodingOrOffset, length);
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
});
}
Buffer.poolSize = 8192; // not used by this implementation
function from(value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number');
}
if (value instanceof ArrayBuffer) {
return fromArrayBuffer(value, encodingOrOffset, length);
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset);
}
return fromObject(value);
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length);
};
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype;
Buffer.__proto__ = Uint8Array;
function assertSize(size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number');
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative');
}
}
function alloc(size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(size);
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
}
return createBuffer(size);
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding);
};
function allocUnsafe(size) {
assertSize(size);
return createBuffer(size < 0 ? 0 : checked(size) | 0);
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size);
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size);
};
function fromString(string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8';
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding');
}
var length = byteLength(string, encoding) | 0;
var buf = createBuffer(length);
var actual = buf.write(string, encoding);
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual);
}
return buf;
}
function fromArrayLike(array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0;
var buf = createBuffer(length);
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255;
}
return buf;
}
function fromArrayBuffer(array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds');
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds');
}
var buf;
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array);
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset);
} else {
buf = new Uint8Array(array, byteOffset, length);
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype;
return buf;
}
function fromObject(obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0;
var buf = createBuffer(len);
if (buf.length === 0) {
return buf;
}
obj.copy(buf, 0, 0, len);
return buf;
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0);
}
return fromArrayLike(obj);
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data);
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.');
}
function checked(length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes');
}
return length | 0;
}
function SlowBuffer(length) {
if (+length != length) {
// eslint-disable-line eqeqeq
length = 0;
}
return Buffer.alloc(+length);
}
Buffer.isBuffer = function isBuffer(b) {
return b != null && b._isBuffer === true;
};
Buffer.compare = function compare(a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers');
}
if (a === b) return 0;
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
Buffer.isEncoding = function isEncoding(encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true;
default:
return false;
}
};
Buffer.concat = function concat(list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
if (list.length === 0) {
return Buffer.alloc(0);
}
var i;
if (length === undefined) {
length = 0;
for (i = 0; i < list.length; ++i) {
length += list[i].length;
}
}
var buffer = Buffer.allocUnsafe(length);
var pos = 0;
for (i = 0; i < list.length; ++i) {
var buf = list[i];
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
buf.copy(buffer, pos);
pos += buf.length;
}
return buffer;
};
function byteLength(string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length;
}
if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
return string.byteLength;
}
if (typeof string !== 'string') {
string = '' + string;
}
var len = string.length;
if (len === 0) return 0;
// Use a for loop to avoid recursion
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len;
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length;
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2;
case 'hex':
return len >>> 1;
case 'base64':
return base64ToBytes(string).length;
default:
if (loweredCase) return utf8ToBytes(string).length; // assume utf8
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer.byteLength = byteLength;
function slowToString(encoding, start, end) {
var loweredCase = false;
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0;
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return '';
}
if (end === undefined || end > this.length) {
end = this.length;
}
if (end <= 0) {
return '';
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0;
start >>>= 0;
if (end <= start) {
return '';
}
if (!encoding) encoding = 'utf8';
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end);
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end);
case 'ascii':
return asciiSlice(this, start, end);
case 'latin1':
case 'binary':
return latin1Slice(this, start, end);
case 'base64':
return base64Slice(this, start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end);
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
encoding = (encoding + '').toLowerCase();
loweredCase = true;
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true;
function swap(b, n, m) {
var i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer.prototype.swap16 = function swap16() {
var len = this.length;
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits');
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1);
}
return this;
};
Buffer.prototype.swap32 = function swap32() {
var len = this.length;
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits');
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this;
};
Buffer.prototype.swap64 = function swap64() {
var len = this.length;
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits');
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this;
};
Buffer.prototype.toString = function toString() {
var length = this.length;
if (length === 0) return '';
if (arguments.length === 0) return utf8Slice(this, 0, length);
return slowToString.apply(this, arguments);
};
Buffer.prototype.equals = function equals(b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer');
if (this === b) return true;
return Buffer.compare(this, b) === 0;
};
Buffer.prototype.inspect = function inspect() {
var str = '';
var max = exports.INSPECT_MAX_BYTES;
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
if (this.length > max) str += ' ... ';
}
return '<Buffer ' + str + '>';
};
Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer');
}
if (start === undefined) {
start = 0;
}
if (end === undefined) {
end = target ? target.length : 0;
}
if (thisStart === undefined) {
thisStart = 0;
}
if (thisEnd === undefined) {
thisEnd = this.length;
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index');
}
if (thisStart >= thisEnd && start >= end) {
return 0;
}
if (thisStart >= thisEnd) {
return -1;
}
if (start >= end) {
return 1;
}
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0;
var x = thisEnd - thisStart;
var y = end - start;
var len = Math.min(x, y);
var thisCopy = this.slice(thisStart, thisEnd);
var targetCopy = target.slice(start, end);
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1;
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff;
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000;
}
byteOffset = +byteOffset; // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : buffer.length - 1;
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
if (byteOffset >= buffer.length) {
if (dir) return -1;else byteOffset = buffer.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;else return -1;
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding);
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1;
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
} else if (typeof val === 'number') {
val = val & 0xFF; // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
}
}
return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
}
throw new TypeError('val must be string, number or Buffer');
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
var indexSize = 1;
var arrLength = arr.length;
var valLength = val.length;
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase();
if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1;
}
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read(buf, i) {
if (indexSize === 1) {
return buf[i];
} else {
return buf.readUInt16BE(i * indexSize);
}
}
var i;
if (dir) {
var foundIndex = -1;
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for (i = byteOffset; i >= 0; i--) {
var found = true;
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false;
break;
}
}
if (found) return i;
}
}
return -1;
}
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
offset = Number(offset) || 0;
var remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
// must be an even number of digits
var strLen = string.length;
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string');
if (length > strLen / 2) {
length = strLen / 2;
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16);
if (numberIsNaN(parsed)) return i;
buf[offset + i] = parsed;
}
return i;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function latin1Write(buf, string, offset, length) {
return asciiWrite(buf, string, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer.prototype.write = function write(string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8';
length = this.length;
offset = 0;
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0;
if (isFinite(length)) {
length = length >>> 0;
if (encoding === undefined) encoding = 'utf8';
} else {
encoding = length;
length = undefined;
}
} else {
throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
}
var remaining = this.length - offset;
if (length === undefined || length > remaining) length = remaining;
if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds');
}
if (!encoding) encoding = 'utf8';
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length);
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length);
case 'ascii':
return asciiWrite(this, string, offset, length);
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length);
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length);
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
};
Buffer.prototype.toJSON = function toJSON() {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
};
};
function base64Slice(buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf);
} else {
return base64.fromByteArray(buf.slice(start, end));
}
}
function utf8Slice(buf, start, end) {
end = Math.min(buf.length, end);
var res = [];
var i = start;
while (i < end) {
var firstByte = buf[i];
var codePoint = null;
var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte;
}
break;
case 2:
secondByte = buf[i + 1];
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint;
}
}
break;
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint;
}
}
break;
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD;
bytesPerSequence = 1;
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000;
res.push(codePoint >>> 10 & 0x3FF | 0xD800);
codePoint = 0xDC00 | codePoint & 0x3FF;
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000;
function decodeCodePointsArray(codePoints) {
var len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = '';
var i = 0;
while (i < len) {
res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
}
return res;
}
function asciiSlice(buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F);
}
return ret;
}
function latin1Slice(buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i]);
}
return ret;
}
function hexSlice(buf, start, end) {
var len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
var out = '';
for (var i = start; i < end; ++i) {
out += toHex(buf[i]);
}
return out;
}
function utf16leSlice(buf, start, end) {
var bytes = buf.slice(start, end);
var res = '';
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
}
return res;
}
Buffer.prototype.slice = function slice(start, end) {
var len = this.length;
start = ~~start;
end = end === undefined ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) {
end = len;
}
if (end < start) end = start;
var newBuf = this.subarray(start, end);
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype;
return newBuf;
};
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
}
Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
return val;
};
Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
checkOffset(offset, byteLength, this.length);
}
var val = this[offset + --byteLength];
var mul = 1;
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul;
}
return val;
};
Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset];
};
Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | this[offset + 1] << 8;
};
Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] << 8 | this[offset + 1];
};
Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
};
Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var i = byteLength;
var mul = 1;
var val = this[offset + --i];
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 0x80)) return this[offset];
return (0xff - this[offset] + 1) * -1;
};
Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset] | this[offset + 1] << 8;
return val & 0x8000 ? val | 0xFFFF0000 : val;
};
Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset + 1] | this[offset] << 8;
return val & 0x8000 ? val | 0xFFFF0000 : val;
};
Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, true, 23, 4);
};
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, false, 23, 4);
};
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, true, 52, 8);
};
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError('Index out of range');
}
Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var mul = 1;
var i = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = value / mul & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var i = byteLength - 1;
var mul = 1;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = value / mul & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset + 3] = value >>> 24;
this[offset + 2] = value >>> 16;
this[offset + 1] = value >>> 8;
this[offset] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = 0;
var mul = 1;
var sub = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1;
}
this[offset + i] = (value / mul >> 0) - sub & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = byteLength - 1;
var mul = 1;
var sub = 0;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1;
}
this[offset + i] = (value / mul >> 0) - sub & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
if (value < 0) value = 0xff + value + 1;
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
this[offset + 2] = value >>> 16;
this[offset + 3] = value >>> 24;
return offset + 4;
};
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (value < 0) value = 0xffffffff + value + 1;
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
function checkIEEE754(buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range');
if (offset < 0) throw new RangeError('Index out of range');
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38);
}
ieee754.write(buf, value, offset, littleEndian, 23, 4);
return offset + 4;
}
Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert);
};
Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308);
}
ieee754.write(buf, value, offset, littleEndian, 52, 8);
return offset + 8;
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert);
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert);
};
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy(target, targetStart, start, end) {
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
// Copy 0 bytes; we're done
if (end === start) return 0;
if (target.length === 0 || this.length === 0) return 0;
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds');
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds');
if (end < 0) throw new RangeError('sourceEnd out of bounds');
// Are we oob?
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start;
}
var len = end - start;
var i;
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start];
}
} else if (len < 1000) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start];
}
} else {
Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
}
return len;
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill(val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === 'string') {
encoding = end;
end = this.length;
}
if (val.length === 1) {
var code = val.charCodeAt(0);
if (code < 256) {
val = code;
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string');
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding);
}
} else if (typeof val === 'number') {
val = val & 255;
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index');
}
if (end <= start) {
return this;
}
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
if (!val) val = 0;
var i;
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val;
}
} else {
var bytes = Buffer.isBuffer(val) ? val : new Buffer(val, encoding);
var len = bytes.length;
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len];
}
}
return this;
};
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
function base64clean(str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '');
// Node converts strings with length < 2 to ''
if (str.length < 2) return '';
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '=';
}
return str;
}
function toHex(n) {
if (n < 16) return '0' + n.toString(16);
return n.toString(16);
}
function utf8ToBytes(string, units) {
units = units || Infinity;
var codePoint;
var length = string.length;
var leadSurrogate = null;
var bytes = [];
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i);
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue;
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue;
}
// valid lead
leadSurrogate = codePoint;
continue;
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
leadSurrogate = codePoint;
continue;
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
}
leadSurrogate = null;
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break;
bytes.push(codePoint);
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break;
bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break;
bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break;
bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
} else {
throw new Error('Invalid code point');
}
}
return bytes;
}
function asciiToBytes(str) {
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF);
}
return byteArray;
}
function utf16leToBytes(str, units) {
var c, hi, lo;
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break;
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray;
}
function base64ToBytes(str) {
return base64.toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if (i + offset >= dst.length || i >= src.length) break;
dst[i + offset] = src[i];
}
return i;
}
// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
function isArrayBufferView(obj) {
return typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(obj);
}
function numberIsNaN(obj) {
return obj !== obj; // eslint-disable-line no-self-compare
}
},{"base64-js":63,"ieee754":520}],67:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { J: 0.0174923, C: 0.0218654, G: 0.319234, E: 0.183669, B: 0.183669, A: 3.32354, TB: 0.009298 }, B: "ms", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "TB", "J", "C", "G", "E", "B", "A", "", "", ""], E: "IE" }, B: { A: { D: 0.04227, X: 0.097221, g: 1.09057, H: 0, L: 0 }, B: "ms", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "D", "X", "g", "H", "L", "", ""], E: "Edge" }, C: { A: { "0": 2.66724, "1": 0.016908, "2": 0.038043, "4": 0, RB: 0.004227, F: 0.004227, I: 0.004879, J: 0.020136, C: 0.005725, G: 0.012681, E: 0.00533, B: 0.004227, A: 0.008454, D: 0.008454, X: 0.004486, g: 0.00453, H: 0.008454, L: 0.008454, M: 0.004227, N: 0.008454, O: 0.004443, P: 0.004227, Q: 0.012681, R: 0.004227, S: 0.008454, T: 0.008454, U: 0.012681, V: 0.004227, W: 0.004227, u: 0.004227, Y: 0.008454, Z: 0.012681, a: 0.021135, b: 0.008454, c: 0.012681, d: 0.008454, e: 0.012681, f: 0.016908, K: 0.016908, h: 0.046497, i: 0.016908, j: 0.016908, k: 0.025362, l: 0.021135, m: 0.050724, n: 0.021135, o: 0.114129, p: 0.021135, q: 0.097221, r: 0.156399, w: 0.097221, x: 0.08454, v: 0.143718, z: 0.528375, t: 1.41182, s: 0, PB: 0.004534, OB: 0.012681 }, B: "moz", C: ["", "RB", "1", "PB", "OB", "F", "I", "J", "C", "G", "E", "B", "A", "D", "X", "g", "H", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "u", "Y", "Z", "a", "b", "c", "d", "e", "f", "K", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "w", "x", "v", "z", "0", "t", "2", "s", "4"], E: "Firefox" }, D: { A: { "0": 0.076086, "2": 0.274755, "4": 0.410019, "8": 3.2252, F: 0.004706, I: 0.004879, J: 0.004879, C: 0.005591, G: 0.005591, E: 0.005591, B: 0.004534, A: 0.021135, D: 0.004367, X: 0.004879, g: 0.004706, H: 0.004706, L: 0.004227, M: 0.004227, N: 0.008454, O: 0.008454, P: 0.004227, Q: 0.008454, R: 0.029589, S: 0.008454, T: 0.016908, U: 0.008454, V: 0.016908, W: 0.008454, u: 0.008454, Y: 0.016908, Z: 0.012681, a: 0.071859, b: 0.012681, c: 0.029589, d: 0.033816, e: 0.021135, f: 0.054951, K: 0.016908, h: 0.033816, i: 0.029589, j: 0.021135, k: 0.033816, l: 0.033816, m: 0.177534, n: 0.029589, o: 0.312798, p: 0.033816, q: 0.088767, r: 0.067632, w: 1.07789, x: 0.105675, v: 0.160626, z: 0.050724, t: 0.152172, s: 0.376203, DB: 18.7552, AB: 0.067632, SB: 0.04227, BB: 0 }, B: "webkit", C: ["F", "I", "J", "C", "G", "E", "B", "A", "D", "X", "g", "H", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "u", "Y", "Z", "a", "b", "c", "d", "e", "f", "K", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "w", "x", "v", "z", "0", "t", "2", "s", "4", "DB", "8", "AB", "SB", "BB"], E: "Chrome" }, E: { A: { "7": 0.008692, F: 0.008454, I: 0.021135, J: 0.004227, C: 0.012681, G: 0.059178, E: 0.067632, B: 0.304344, A: 0, CB: 0, EB: 0.04227, FB: 0.025362, GB: 0.004227, HB: 0.266301, IB: 1.31037, JB: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "CB", "7", "F", "I", "EB", "J", "FB", "C", "GB", "G", "E", "HB", "B", "IB", "A", "JB", ""], E: "Safari" }, F: { A: { "5": 0.004879, "6": 0.006229, E: 0.0082, A: 0.016581, D: 0.004227, H: 0.00685, L: 0.00685, M: 0.00685, N: 0.005014, O: 0.006015, P: 0.004879, Q: 0.006597, R: 0.006597, S: 0.013434, T: 0.006702, U: 0.006015, V: 0.005595, W: 0.004706, u: 0.008454, Y: 0.004879, Z: 0.004879, a: 0.00533, b: 0.005152, c: 0.005014, d: 0.009758, e: 0.004879, f: 0.029589, K: 0.004227, h: 0.004367, i: 0.004534, j: 0.004367, k: 0.004227, l: 0.008454, m: 0.021135, n: 0.004227, o: 0.667866, p: 0.025362, q: 0, r: 0, KB: 0.00685, LB: 0, MB: 0.008392, NB: 0.004706, QB: 0.004534, y: 0.076086 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "E", "KB", "LB", "MB", "NB", "A", "6", "5", "QB", "D", "y", "H", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "u", "Y", "Z", "a", "b", "c", "d", "e", "f", "K", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", ""], E: "Opera", D: { "5": "o", "6": "o", E: "o", A: "o", D: "o", KB: "o", LB: "o", MB: "o", NB: "o", QB: "o", y: "o" } }, G: { A: { "3": 0, "7": 0, "9": 0, G: 0, A: 0, UB: 0, VB: 0, WB: 0.0541219, XB: 0.0413873, YB: 0.0318364, ZB: 0.581545, aB: 1.98341, bB: 7.55478 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "7", "9", "3", "UB", "VB", "WB", "G", "XB", "YB", "ZB", "aB", "bB", "A", "", ""], E: "iOS Safari" }, H: { A: { cB: 3.08635 }, B: "o", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "cB", "", "", ""], E: "Opera Mini" }, I: { A: { "1": 0, "3": 0.353639, F: 0, s: 0, dB: 0, eB: 0, fB: 0, gB: 0.136723, hB: 0.950487, iB: 0.550836 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "dB", "eB", "fB", "1", "F", "gB", "3", "hB", "iB", "s", "", "", ""], E: "Android Browser" }, J: { A: { C: 0.0331948, B: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "C", "B", "", "", ""], E: "Blackberry Browser" }, K: { A: { "5": 0, "6": 0, B: 0, A: 0, D: 0, K: 0.0137477, y: 0 }, B: "o", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "B", "A", "6", "5", "D", "y", "K", "", "", ""], E: "Opera Mobile", D: { K: "webkit" } }, L: { A: { "8": 28.8994 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "8", "", "", ""], E: "Chrome for Android" }, M: { A: { t: 0.034638 }, B: "moz", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "t", "", "", ""], E: "Firefox for Android" }, N: { A: { B: 0.05773, A: 0.317515 }, B: "ms", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "B", "A", "", "", ""], E: "IE Mobile" }, O: { A: { jB: 9.13289 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "jB", "", "", ""], E: "UC Browser for Android", D: { jB: "webkit" } }, P: { A: { F: 3.79286, I: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "F", "I", "", "", ""], E: "Samsung Internet" }, Q: { A: { kB: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "kB", "", "", ""], E: "QQ Browser" }, R: { A: { lB: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "lB", "", "", ""], E: "Baidu Browser" } };
},{}],68:[function(require,module,exports){
"use strict";
module.exports = { "0": "53", "1": "3", "2": "55", "3": "4.2-4.3", "4": "57", "5": "11.5", "6": "11.1", "7": "3.2", "8": "59", "9": "4.0-4.1", A: "11", B: "10", C: "7", D: "12", E: "9", F: "4", G: "8", H: "15", I: "5", J: "6", K: "37", L: "16", M: "17", N: "18", O: "19", P: "20", Q: "21", R: "22", S: "23", T: "24", U: "25", V: "26", W: "27", X: "13", Y: "29", Z: "30", a: "31", b: "32", c: "33", d: "34", e: "35", f: "36", g: "14", h: "38", i: "39", j: "40", k: "41", l: "42", m: "43", n: "44", o: "45", p: "46", q: "47", r: "48", s: "56", t: "54", u: "28", v: "51", w: "49", x: "50", y: "12.1", z: "52", AB: "60", BB: "62", CB: "3.1", DB: "58", EB: "5.1", FB: "6.1", GB: "7.1", HB: "9.1", IB: "10.1", JB: "TP", KB: "9.5-9.6", LB: "10.0-10.1", MB: "10.5", NB: "10.6", OB: "3.6", PB: "3.5", QB: "11.6", RB: "2", SB: "61", TB: "5.5", UB: "5.0-5.1", VB: "6.0-6.1", WB: "7.0-7.1", XB: "8.1-8.4", YB: "9.0-9.2", ZB: "9.3", aB: "10.0-10.2", bB: "10.3", cB: "all", dB: "2.1", eB: "2.2", fB: "2.3", gB: "4.1", hB: "4.4", iB: "4.4.3-4.4.4", jB: "11.4", kB: "1.2", lB: "7.12" };
},{}],69:[function(require,module,exports){
"use strict";
module.exports = { A: "ie", B: "edge", C: "firefox", D: "chrome", E: "safari", F: "opera", G: "ios_saf", H: "op_mini", I: "android", J: "bb", K: "op_mob", L: "and_chr", M: "and_ff", N: "ie_mob", O: "and_uc", P: "samsung", Q: "and_qq", R: "baidu" };
},{}],70:[function(require,module,exports){
"use strict";
module.exports = { "aac": require("./features/aac"), "ac3-ec3": require("./features/ac3-ec3"), "addeventlistener": require("./features/addeventlistener"), "alternate-stylesheet": require("./features/alternate-stylesheet"), "ambient-light": require("./features/ambient-light"), "apng": require("./features/apng"), "arrow-functions": require("./features/arrow-functions"), "asmjs": require("./features/asmjs"), "async-functions": require("./features/async-functions"), "atob-btoa": require("./features/atob-btoa"), "audio-api": require("./features/audio-api"), "audio": require("./features/audio"), "audiotracks": require("./features/audiotracks"), "autofocus": require("./features/autofocus"), "aux-click": require("./features/aux-click"), "background-attachment": require("./features/background-attachment"), "background-img-opts": require("./features/background-img-opts"), "background-position-x-y": require("./features/background-position-x-y"), "background-repeat-round-space": require("./features/background-repeat-round-space"), "battery-status": require("./features/battery-status"), "beacon": require("./features/beacon"), "beforeafterprint": require("./features/beforeafterprint"), "blobbuilder": require("./features/blobbuilder"), "bloburls": require("./features/bloburls"), "border-image": require("./features/border-image"), "border-radius": require("./features/border-radius"), "broadcastchannel": require("./features/broadcastchannel"), "brotli": require("./features/brotli"), "calc": require("./features/calc"), "canvas-blending": require("./features/canvas-blending"), "canvas-text": require("./features/canvas-text"), "canvas": require("./features/canvas"), "ch-unit": require("./features/ch-unit"), "chacha20-poly1305": require("./features/chacha20-poly1305"), "channel-messaging": require("./features/channel-messaging"), "childnode-remove": require("./features/childnode-remove"), "classlist": require("./features/classlist"), "client-hints-dpr-width-viewport": require("./features/client-hints-dpr-width-viewport"), "clipboard": require("./features/clipboard"), "comparedocumentposition": require("./features/comparedocumentposition"), "console-basic": require("./features/console-basic"), "const": require("./features/const"), "contenteditable": require("./features/contenteditable"), "contentsecuritypolicy": require("./features/contentsecuritypolicy"), "contentsecuritypolicy2": require("./features/contentsecuritypolicy2"), "cors": require("./features/cors"), "credential-management": require("./features/credential-management"), "cryptography": require("./features/cryptography"), "css-all": require("./features/css-all"), "css-animation": require("./features/css-animation"), "css-any-link": require("./features/css-any-link"), "css-appearance": require("./features/css-appearance"), "css-apply-rule": require("./features/css-apply-rule"), "css-at-counter-style": require("./features/css-at-counter-style"), "css-backdrop-filter": require("./features/css-backdrop-filter"), "css-background-offsets": require("./features/css-background-offsets"), "css-backgroundblendmode": require("./features/css-backgroundblendmode"), "css-boxdecorationbreak": require("./features/css-boxdecorationbreak"), "css-boxshadow": require("./features/css-boxshadow"), "css-canvas": require("./features/css-canvas"), "css-case-insensitive": require("./features/css-case-insensitive"), "css-clip-path": require("./features/css-clip-path"), "css-containment": require("./features/css-containment"), "css-counters": require("./features/css-counters"), "css-crisp-edges": require("./features/css-crisp-edges"), "css-cross-fade": require("./features/css-cross-fade"), "css-default-pseudo": require("./features/css-default-pseudo"), "css-descendant-gtgt": require("./features/css-descendant-gtgt"), "css-deviceadaptation": require("./features/css-deviceadaptation"), "css-dir-pseudo": require("./features/css-dir-pseudo"), "css-display-contents": require("./features/css-display-contents"), "css-element-function": require("./features/css-element-function"), "css-exclusions": require("./features/css-exclusions"), "css-featurequeries": require("./features/css-featurequeries"), "css-filter-function": require("./features/css-filter-function"), "css-filters": require("./features/css-filters"), "css-first-letter": require("./features/css-first-letter"), "css-first-line": require("./features/css-first-line"), "css-fixed": require("./features/css-fixed"), "css-focus-within": require("./features/css-focus-within"), "css-font-rendering-controls": require("./features/css-font-rendering-controls"), "css-font-stretch": require("./features/css-font-stretch"), "css-gencontent": require("./features/css-gencontent"), "css-gradients": require("./features/css-gradients"), "css-grid": require("./features/css-grid"), "css-hanging-punctuation": require("./features/css-hanging-punctuation"), "css-has": require("./features/css-has"), "css-hyphenate": require("./features/css-hyphenate"), "css-hyphens": require("./features/css-hyphens"), "css-image-orientation": require("./features/css-image-orientation"), "css-image-set": require("./features/css-image-set"), "css-in-out-of-range": require("./features/css-in-out-of-range"), "css-indeterminate-pseudo": require("./features/css-indeterminate-pseudo"), "css-initial-letter": require("./features/css-initial-letter"), "css-initial-value": require("./features/css-initial-value"), "css-letter-spacing": require("./features/css-letter-spacing"), "css-line-clamp": require("./features/css-line-clamp"), "css-logical-props": require("./features/css-logical-props"), "css-marker-pseudo": require("./features/css-marker-pseudo"), "css-masks": require("./features/css-masks"), "css-matches-pseudo": require("./features/css-matches-pseudo"), "css-media-interaction": require("./features/css-media-interaction"), "css-media-resolution": require("./features/css-media-resolution"), "css-media-scripting": require("./features/css-media-scripting"), "css-mediaqueries": require("./features/css-mediaqueries"), "css-mixblendmode": require("./features/css-mixblendmode"), "css-motion-paths": require("./features/css-motion-paths"), "css-namespaces": require("./features/css-namespaces"), "css-not-sel-list": require("./features/css-not-sel-list"), "css-nth-child-of": require("./features/css-nth-child-of"), "css-opacity": require("./features/css-opacity"), "css-optional-pseudo": require("./features/css-optional-pseudo"), "css-overflow-anchor": require("./features/css-overflow-anchor"), "css-page-break": require("./features/css-page-break"), "css-paged-media": require("./features/css-paged-media"), "css-placeholder-shown": require("./features/css-placeholder-shown"), "css-placeholder": require("./features/css-placeholder"), "css-read-only-write": require("./features/css-read-only-write"), "css-rebeccapurple": require("./features/css-rebeccapurple"), "css-reflections": require("./features/css-reflections"), "css-regions": require("./features/css-regions"), "css-repeating-gradients": require("./features/css-repeating-gradients"), "css-resize": require("./features/css-resize"), "css-revert-value": require("./features/css-revert-value"), "css-rrggbbaa": require("./features/css-rrggbbaa"), "css-scroll-behavior": require("./features/css-scroll-behavior"), "css-scrollbar": require("./features/css-scrollbar"), "css-sel2": require("./features/css-sel2"), "css-sel3": require("./features/css-sel3"), "css-selection": require("./features/css-selection"), "css-shapes": require("./features/css-shapes"), "css-snappoints": require("./features/css-snappoints"), "css-sticky": require("./features/css-sticky"), "css-supports-api": require("./features/css-supports-api"), "css-table": require("./features/css-table"), "css-text-align-last": require("./features/css-text-align-last"), "css-text-indent": require("./features/css-text-indent"), "css-text-justify": require("./features/css-text-justify"), "css-text-orientation": require("./features/css-text-orientation"), "css-text-spacing": require("./features/css-text-spacing"), "css-textshadow": require("./features/css-textshadow"), "css-touch-action-2": require("./features/css-touch-action-2"), "css-touch-action": require("./features/css-touch-action"), "css-transitions": require("./features/css-transitions"), "css-unicode-bidi": require("./features/css-unicode-bidi"), "css-unset-value": require("./features/css-unset-value"), "css-variables": require("./features/css-variables"), "css-widows-orphans": require("./features/css-widows-orphans"), "css-writing-mode": require("./features/css-writing-mode"), "css-zoom": require("./features/css-zoom"), "css3-attr": require("./features/css3-attr"), "css3-boxsizing": require("./features/css3-boxsizing"), "css3-colors": require("./features/css3-colors"), "css3-cursors-grab": require("./features/css3-cursors-grab"), "css3-cursors-newer": require("./features/css3-cursors-newer"), "css3-cursors": require("./features/css3-cursors"), "css3-tabsize": require("./features/css3-tabsize"), "currentcolor": require("./features/currentcolor"), "custom-elements": require("./features/custom-elements"), "custom-elementsv1": require("./features/custom-elementsv1"), "customevent": require("./features/customevent"), "datalist": require("./features/datalist"), "dataset": require("./features/dataset"), "datauri": require("./features/datauri"), "details": require("./features/details"), "deviceorientation": require("./features/deviceorientation"), "devicepixelratio": require("./features/devicepixelratio"), "dialog": require("./features/dialog"), "dispatchevent": require("./features/dispatchevent"), "document-currentscript": require("./features/document-currentscript"), "document-evaluate-xpath": require("./features/document-evaluate-xpath"), "document-execcommand": require("./features/document-execcommand"), "documenthead": require("./features/documenthead"), "dom-manip-convenience": require("./features/dom-manip-convenience"), "dom-range": require("./features/dom-range"), "domcontentloaded": require("./features/domcontentloaded"), "domfocusin-domfocusout-events": require("./features/domfocusin-domfocusout-events"), "dommatrix": require("./features/dommatrix"), "download": require("./features/download"), "dragndrop": require("./features/dragndrop"), "element-closest": require("./features/element-closest"), "element-from-point": require("./features/element-from-point"), "eme": require("./features/eme"), "eot": require("./features/eot"), "es5": require("./features/es5"), "es6-class": require("./features/es6-class"), "es6-module": require("./features/es6-module"), "es6-number": require("./features/es6-number"), "eventsource": require("./features/eventsource"), "fetch": require("./features/fetch"), "fieldset-disabled": require("./features/fieldset-disabled"), "fileapi": require("./features/fileapi"), "filereader": require("./features/filereader"), "filereadersync": require("./features/filereadersync"), "filesystem": require("./features/filesystem"), "flac": require("./features/flac"), "flexbox": require("./features/flexbox"), "flow-root": require("./features/flow-root"), "focusin-focusout-events": require("./features/focusin-focusout-events"), "font-feature": require("./features/font-feature"), "font-kerning": require("./features/font-kerning"), "font-loading": require("./features/font-loading"), "font-size-adjust": require("./features/font-size-adjust"), "font-smooth": require("./features/font-smooth"), "font-unicode-range": require("./features/font-unicode-range"), "font-variant-alternates": require("./features/font-variant-alternates"), "fontface": require("./features/fontface"), "form-attribute": require("./features/form-attribute"), "form-submit-attributes": require("./features/form-submit-attributes"), "form-validation": require("./features/form-validation"), "forms": require("./features/forms"), "fullscreen": require("./features/fullscreen"), "gamepad": require("./features/gamepad"), "geolocation": require("./features/geolocation"), "getboundingclientrect": require("./features/getboundingclientrect"), "getcomputedstyle": require("./features/getcomputedstyle"), "getelementsbyclassname": require("./features/getelementsbyclassname"), "getrandomvalues": require("./features/getrandomvalues"), "hardwareconcurrency": require("./features/hardwareconcurrency"), "hashchange": require("./features/hashchange"), "heif": require("./features/heif"), "hevc": require("./features/hevc"), "hidden": require("./features/hidden"), "high-resolution-time": require("./features/high-resolution-time"), "history": require("./features/history"), "html-media-capture": require("./features/html-media-capture"), "html5semantic": require("./features/html5semantic"), "http-live-streaming": require("./features/http-live-streaming"), "http2": require("./features/http2"), "iframe-sandbox": require("./features/iframe-sandbox"), "iframe-seamless": require("./features/iframe-seamless"), "iframe-srcdoc": require("./features/iframe-srcdoc"), "imagecapture": require("./features/imagecapture"), "ime": require("./features/ime"), "img-naturalwidth-naturalheight": require("./features/img-naturalwidth-naturalheight"), "imports": require("./features/imports"), "indeterminate-checkbox": require("./features/indeterminate-checkbox"), "indexeddb": require("./features/indexeddb"), "indexeddb2": require("./features/indexeddb2"), "inline-block": require("./features/inline-block"), "innertext": require("./features/innertext"), "input-autocomplete-onoff": require("./features/input-autocomplete-onoff"), "input-color": require("./features/input-color"), "input-datetime": require("./features/input-datetime"), "input-email-tel-url": require("./features/input-email-tel-url"), "input-event": require("./features/input-event"), "input-file-accept": require("./features/input-file-accept"), "input-file-multiple": require("./features/input-file-multiple"), "input-inputmode": require("./features/input-inputmode"), "input-minlength": require("./features/input-minlength"), "input-number": require("./features/input-number"), "input-pattern": require("./features/input-pattern"), "input-placeholder": require("./features/input-placeholder"), "input-range": require("./features/input-range"), "input-search": require("./features/input-search"), "insert-adjacent": require("./features/insert-adjacent"), "insertadjacenthtml": require("./features/insertadjacenthtml"), "internationalization": require("./features/internationalization"), "intersectionobserver": require("./features/intersectionobserver"), "intrinsic-width": require("./features/intrinsic-width"), "jpeg2000": require("./features/jpeg2000"), "jpegxr": require("./features/jpegxr"), "json": require("./features/json"), "kerning-pairs-ligatures": require("./features/kerning-pairs-ligatures"), "keyboardevent-charcode": require("./features/keyboardevent-charcode"), "keyboardevent-code": require("./features/keyboardevent-code"), "keyboardevent-getmodifierstate": require("./features/keyboardevent-getmodifierstate"), "keyboardevent-key": require("./features/keyboardevent-key"), "keyboardevent-location": require("./features/keyboardevent-location"), "keyboardevent-which": require("./features/keyboardevent-which"), "lazyload": require("./features/lazyload"), "let": require("./features/let"), "link-icon-png": require("./features/link-icon-png"), "link-icon-svg": require("./features/link-icon-svg"), "link-rel-dns-prefetch": require("./features/link-rel-dns-prefetch"), "link-rel-preconnect": require("./features/link-rel-preconnect"), "link-rel-prefetch": require("./features/link-rel-prefetch"), "link-rel-preload": require("./features/link-rel-preload"), "link-rel-prerender": require("./features/link-rel-prerender"), "localecompare": require("./features/localecompare"), "matchesselector": require("./features/matchesselector"), "matchmedia": require("./features/matchmedia"), "mathml": require("./features/mathml"), "maxlength": require("./features/maxlength"), "media-attribute": require("./features/media-attribute"), "media-session-api": require("./features/media-session-api"), "mediacapture-fromelement": require("./features/mediacapture-fromelement"), "mediarecorder": require("./features/mediarecorder"), "mediasource": require("./features/mediasource"), "menu": require("./features/menu"), "meter": require("./features/meter"), "midi": require("./features/midi"), "minmaxwh": require("./features/minmaxwh"), "mp3": require("./features/mp3"), "mpeg4": require("./features/mpeg4"), "multibackgrounds": require("./features/multibackgrounds"), "multicolumn": require("./features/multicolumn"), "mutation-events": require("./features/mutation-events"), "mutationobserver": require("./features/mutationobserver"), "namevalue-storage": require("./features/namevalue-storage"), "nav-timing": require("./features/nav-timing"), "netinfo": require("./features/netinfo"), "node-contains": require("./features/node-contains"), "node-parentelement": require("./features/node-parentelement"), "notifications": require("./features/notifications"), "object-fit": require("./features/object-fit"), "object-observe": require("./features/object-observe"), "objectrtc": require("./features/objectrtc"), "offline-apps": require("./features/offline-apps"), "ogg-vorbis": require("./features/ogg-vorbis"), "ogv": require("./features/ogv"), "ol-reversed": require("./features/ol-reversed"), "once-event-listener": require("./features/once-event-listener"), "online-status": require("./features/online-status"), "opus": require("./features/opus"), "outline": require("./features/outline"), "pad-start-end": require("./features/pad-start-end"), "page-transition-events": require("./features/page-transition-events"), "pagevisibility": require("./features/pagevisibility"), "passive-event-listener": require("./features/passive-event-listener"), "payment-request": require("./features/payment-request"), "permissions-api": require("./features/permissions-api"), "picture": require("./features/picture"), "ping": require("./features/ping"), "png-alpha": require("./features/png-alpha"), "pointer-events": require("./features/pointer-events"), "pointer": require("./features/pointer"), "pointerlock": require("./features/pointerlock"), "progress": require("./features/progress"), "promises": require("./features/promises"), "proximity": require("./features/proximity"), "proxy": require("./features/proxy"), "publickeypinning": require("./features/publickeypinning"), "push-api": require("./features/push-api"), "queryselector": require("./features/queryselector"), "readonly-attr": require("./features/readonly-attr"), "referrer-policy": require("./features/referrer-policy"), "registerprotocolhandler": require("./features/registerprotocolhandler"), "rel-noopener": require("./features/rel-noopener"), "rel-noreferrer": require("./features/rel-noreferrer"), "rellist": require("./features/rellist"), "rem": require("./features/rem"), "requestanimationframe": require("./features/requestanimationframe"), "requestidlecallback": require("./features/requestidlecallback"), "resizeobserver": require("./features/resizeobserver"), "resource-timing": require("./features/resource-timing"), "rest-parameters": require("./features/rest-parameters"), "rtcpeerconnection": require("./features/rtcpeerconnection"), "ruby": require("./features/ruby"), "same-site-cookie-attribute": require("./features/same-site-cookie-attribute"), "screen-orientation": require("./features/screen-orientation"), "script-async": require("./features/script-async"), "script-defer": require("./features/script-defer"), "scrollintoview": require("./features/scrollintoview"), "scrollintoviewifneeded": require("./features/scrollintoviewifneeded"), "sdch": require("./features/sdch"), "selection-api": require("./features/selection-api"), "serviceworkers": require("./features/serviceworkers"), "setimmediate": require("./features/setimmediate"), "sha-2": require("./features/sha-2"), "shadowdom": require("./features/shadowdom"), "shadowdomv1": require("./features/shadowdomv1"), "sharedworkers": require("./features/sharedworkers"), "sni": require("./features/sni"), "spdy": require("./features/spdy"), "speech-recognition": require("./features/speech-recognition"), "speech-synthesis": require("./features/speech-synthesis"), "spellcheck-attribute": require("./features/spellcheck-attribute"), "sql-storage": require("./features/sql-storage"), "srcset": require("./features/srcset"), "stopimmediatepropagation": require("./features/stopimmediatepropagation"), "stream": require("./features/stream"), "stricttransportsecurity": require("./features/stricttransportsecurity"), "style-scoped": require("./features/style-scoped"), "subresource-integrity": require("./features/subresource-integrity"), "svg-css": require("./features/svg-css"), "svg-filters": require("./features/svg-filters"), "svg-fonts": require("./features/svg-fonts"), "svg-fragment": require("./features/svg-fragment"), "svg-html": require("./features/svg-html"), "svg-html5": require("./features/svg-html5"), "svg-img": require("./features/svg-img"), "svg-smil": require("./features/svg-smil"), "svg": require("./features/svg"), "tabindex-attr": require("./features/tabindex-attr"), "template-literals": require("./features/template-literals"), "template": require("./features/template"), "testfeat": require("./features/testfeat"), "text-decoration": require("./features/text-decoration"), "text-emphasis": require("./features/text-emphasis"), "text-overflow": require("./features/text-overflow"), "text-size-adjust": require("./features/text-size-adjust"), "text-stroke": require("./features/text-stroke"), "textcontent": require("./features/textcontent"), "textencoder": require("./features/textencoder"), "tls1-1": require("./features/tls1-1"), "tls1-2": require("./features/tls1-2"), "tls1-3": require("./features/tls1-3"), "token-binding": require("./features/token-binding"), "touch": require("./features/touch"), "transforms2d": require("./features/transforms2d"), "transforms3d": require("./features/transforms3d"), "ttf": require("./features/ttf"), "typedarrays": require("./features/typedarrays"), "u2f": require("./features/u2f"), "upgradeinsecurerequests": require("./features/upgradeinsecurerequests"), "url": require("./features/url"), "urlsearchparams": require("./features/urlsearchparams"), "use-strict": require("./features/use-strict"), "user-select-none": require("./features/user-select-none"), "user-timing": require("./features/user-timing"), "vibration": require("./features/vibration"), "video": require("./features/video"), "videotracks": require("./features/videotracks"), "viewport-units": require("./features/viewport-units"), "wai-aria": require("./features/wai-aria"), "wasm": require("./features/wasm"), "wav": require("./features/wav"), "wbr-element": require("./features/wbr-element"), "web-animation": require("./features/web-animation"), "web-app-manifest": require("./features/web-app-manifest"), "web-bluetooth": require("./features/web-bluetooth"), "web-share": require("./features/web-share"), "webgl": require("./features/webgl"), "webgl2": require("./features/webgl2"), "webm": require("./features/webm"), "webp": require("./features/webp"), "websockets": require("./features/websockets"), "webvr": require("./features/webvr"), "webvtt": require("./features/webvtt"), "webworkers": require("./features/webworkers"), "will-change": require("./features/will-change"), "woff": require("./features/woff"), "woff2": require("./features/woff2"), "word-break": require("./features/word-break"), "wordwrap": require("./features/wordwrap"), "x-doc-messaging": require("./features/x-doc-messaging"), "x-frame-options": require("./features/x-frame-options"), "xhr2": require("./features/xhr2"), "xhtml": require("./features/xhtml"), "xhtmlsmil": require("./features/xhtmlsmil"), "xml-serializer": require("./features/xml-serializer") };
},{"./features/aac":71,"./features/ac3-ec3":72,"./features/addeventlistener":73,"./features/alternate-stylesheet":74,"./features/ambient-light":75,"./features/apng":76,"./features/arrow-functions":77,"./features/asmjs":78,"./features/async-functions":79,"./features/atob-btoa":80,"./features/audio":82,"./features/audio-api":81,"./features/audiotracks":83,"./features/autofocus":84,"./features/aux-click":85,"./features/background-attachment":86,"./features/background-img-opts":87,"./features/background-position-x-y":88,"./features/background-repeat-round-space":89,"./features/battery-status":90,"./features/beacon":91,"./features/beforeafterprint":92,"./features/blobbuilder":93,"./features/bloburls":94,"./features/border-image":95,"./features/border-radius":96,"./features/broadcastchannel":97,"./features/brotli":98,"./features/calc":99,"./features/canvas":102,"./features/canvas-blending":100,"./features/canvas-text":101,"./features/ch-unit":103,"./features/chacha20-poly1305":104,"./features/channel-messaging":105,"./features/childnode-remove":106,"./features/classlist":107,"./features/client-hints-dpr-width-viewport":108,"./features/clipboard":109,"./features/comparedocumentposition":110,"./features/console-basic":111,"./features/const":112,"./features/contenteditable":113,"./features/contentsecuritypolicy":114,"./features/contentsecuritypolicy2":115,"./features/cors":116,"./features/credential-management":117,"./features/cryptography":118,"./features/css-all":119,"./features/css-animation":120,"./features/css-any-link":121,"./features/css-appearance":122,"./features/css-apply-rule":123,"./features/css-at-counter-style":124,"./features/css-backdrop-filter":125,"./features/css-background-offsets":126,"./features/css-backgroundblendmode":127,"./features/css-boxdecorationbreak":128,"./features/css-boxshadow":129,"./features/css-canvas":130,"./features/css-case-insensitive":131,"./features/css-clip-path":132,"./features/css-containment":133,"./features/css-counters":134,"./features/css-crisp-edges":135,"./features/css-cross-fade":136,"./features/css-default-pseudo":137,"./features/css-descendant-gtgt":138,"./features/css-deviceadaptation":139,"./features/css-dir-pseudo":140,"./features/css-display-contents":141,"./features/css-element-function":142,"./features/css-exclusions":143,"./features/css-featurequeries":144,"./features/css-filter-function":145,"./features/css-filters":146,"./features/css-first-letter":147,"./features/css-first-line":148,"./features/css-fixed":149,"./features/css-focus-within":150,"./features/css-font-rendering-controls":151,"./features/css-font-stretch":152,"./features/css-gencontent":153,"./features/css-gradients":154,"./features/css-grid":155,"./features/css-hanging-punctuation":156,"./features/css-has":157,"./features/css-hyphenate":158,"./features/css-hyphens":159,"./features/css-image-orientation":160,"./features/css-image-set":161,"./features/css-in-out-of-range":162,"./features/css-indeterminate-pseudo":163,"./features/css-initial-letter":164,"./features/css-initial-value":165,"./features/css-letter-spacing":166,"./features/css-line-clamp":167,"./features/css-logical-props":168,"./features/css-marker-pseudo":169,"./features/css-masks":170,"./features/css-matches-pseudo":171,"./features/css-media-interaction":172,"./features/css-media-resolution":173,"./features/css-media-scripting":174,"./features/css-mediaqueries":175,"./features/css-mixblendmode":176,"./features/css-motion-paths":177,"./features/css-namespaces":178,"./features/css-not-sel-list":179,"./features/css-nth-child-of":180,"./features/css-opacity":181,"./features/css-optional-pseudo":182,"./features/css-overflow-anchor":183,"./features/css-page-break":184,"./features/css-paged-media":185,"./features/css-placeholder":187,"./features/css-placeholder-shown":186,"./features/css-read-only-write":188,"./features/css-rebeccapurple":189,"./features/css-reflections":190,"./features/css-regions":191,"./features/css-repeating-gradients":192,"./features/css-resize":193,"./features/css-revert-value":194,"./features/css-rrggbbaa":195,"./features/css-scroll-behavior":196,"./features/css-scrollbar":197,"./features/css-sel2":198,"./features/css-sel3":199,"./features/css-selection":200,"./features/css-shapes":201,"./features/css-snappoints":202,"./features/css-sticky":203,"./features/css-supports-api":204,"./features/css-table":205,"./features/css-text-align-last":206,"./features/css-text-indent":207,"./features/css-text-justify":208,"./features/css-text-orientation":209,"./features/css-text-spacing":210,"./features/css-textshadow":211,"./features/css-touch-action":213,"./features/css-touch-action-2":212,"./features/css-transitions":214,"./features/css-unicode-bidi":215,"./features/css-unset-value":216,"./features/css-variables":217,"./features/css-widows-orphans":218,"./features/css-writing-mode":219,"./features/css-zoom":220,"./features/css3-attr":221,"./features/css3-boxsizing":222,"./features/css3-colors":223,"./features/css3-cursors":226,"./features/css3-cursors-grab":224,"./features/css3-cursors-newer":225,"./features/css3-tabsize":227,"./features/currentcolor":228,"./features/custom-elements":229,"./features/custom-elementsv1":230,"./features/customevent":231,"./features/datalist":232,"./features/dataset":233,"./features/datauri":234,"./features/details":235,"./features/deviceorientation":236,"./features/devicepixelratio":237,"./features/dialog":238,"./features/dispatchevent":239,"./features/document-currentscript":240,"./features/document-evaluate-xpath":241,"./features/document-execcommand":242,"./features/documenthead":243,"./features/dom-manip-convenience":244,"./features/dom-range":245,"./features/domcontentloaded":246,"./features/domfocusin-domfocusout-events":247,"./features/dommatrix":248,"./features/download":249,"./features/dragndrop":250,"./features/element-closest":251,"./features/element-from-point":252,"./features/eme":253,"./features/eot":254,"./features/es5":255,"./features/es6-class":256,"./features/es6-module":257,"./features/es6-number":258,"./features/eventsource":259,"./features/fetch":260,"./features/fieldset-disabled":261,"./features/fileapi":262,"./features/filereader":263,"./features/filereadersync":264,"./features/filesystem":265,"./features/flac":266,"./features/flexbox":267,"./features/flow-root":268,"./features/focusin-focusout-events":269,"./features/font-feature":270,"./features/font-kerning":271,"./features/font-loading":272,"./features/font-size-adjust":273,"./features/font-smooth":274,"./features/font-unicode-range":275,"./features/font-variant-alternates":276,"./features/fontface":277,"./features/form-attribute":278,"./features/form-submit-attributes":279,"./features/form-validation":280,"./features/forms":281,"./features/fullscreen":282,"./features/gamepad":283,"./features/geolocation":284,"./features/getboundingclientrect":285,"./features/getcomputedstyle":286,"./features/getelementsbyclassname":287,"./features/getrandomvalues":288,"./features/hardwareconcurrency":289,"./features/hashchange":290,"./features/heif":291,"./features/hevc":292,"./features/hidden":293,"./features/high-resolution-time":294,"./features/history":295,"./features/html-media-capture":296,"./features/html5semantic":297,"./features/http-live-streaming":298,"./features/http2":299,"./features/iframe-sandbox":300,"./features/iframe-seamless":301,"./features/iframe-srcdoc":302,"./features/imagecapture":303,"./features/ime":304,"./features/img-naturalwidth-naturalheight":305,"./features/imports":306,"./features/indeterminate-checkbox":307,"./features/indexeddb":308,"./features/indexeddb2":309,"./features/inline-block":310,"./features/innertext":311,"./features/input-autocomplete-onoff":312,"./features/input-color":313,"./features/input-datetime":314,"./features/input-email-tel-url":315,"./features/input-event":316,"./features/input-file-accept":317,"./features/input-file-multiple":318,"./features/input-inputmode":319,"./features/input-minlength":320,"./features/input-number":321,"./features/input-pattern":322,"./features/input-placeholder":323,"./features/input-range":324,"./features/input-search":325,"./features/insert-adjacent":326,"./features/insertadjacenthtml":327,"./features/internationalization":328,"./features/intersectionobserver":329,"./features/intrinsic-width":330,"./features/jpeg2000":331,"./features/jpegxr":332,"./features/json":333,"./features/kerning-pairs-ligatures":334,"./features/keyboardevent-charcode":335,"./features/keyboardevent-code":336,"./features/keyboardevent-getmodifierstate":337,"./features/keyboardevent-key":338,"./features/keyboardevent-location":339,"./features/keyboardevent-which":340,"./features/lazyload":341,"./features/let":342,"./features/link-icon-png":343,"./features/link-icon-svg":344,"./features/link-rel-dns-prefetch":345,"./features/link-rel-preconnect":346,"./features/link-rel-prefetch":347,"./features/link-rel-preload":348,"./features/link-rel-prerender":349,"./features/localecompare":350,"./features/matchesselector":351,"./features/matchmedia":352,"./features/mathml":353,"./features/maxlength":354,"./features/media-attribute":355,"./features/media-session-api":356,"./features/mediacapture-fromelement":357,"./features/mediarecorder":358,"./features/mediasource":359,"./features/menu":360,"./features/meter":361,"./features/midi":362,"./features/minmaxwh":363,"./features/mp3":364,"./features/mpeg4":365,"./features/multibackgrounds":366,"./features/multicolumn":367,"./features/mutation-events":368,"./features/mutationobserver":369,"./features/namevalue-storage":370,"./features/nav-timing":371,"./features/netinfo":372,"./features/node-contains":373,"./features/node-parentelement":374,"./features/notifications":375,"./features/object-fit":376,"./features/object-observe":377,"./features/objectrtc":378,"./features/offline-apps":379,"./features/ogg-vorbis":380,"./features/ogv":381,"./features/ol-reversed":382,"./features/once-event-listener":383,"./features/online-status":384,"./features/opus":385,"./features/outline":386,"./features/pad-start-end":387,"./features/page-transition-events":388,"./features/pagevisibility":389,"./features/passive-event-listener":390,"./features/payment-request":391,"./features/permissions-api":392,"./features/picture":393,"./features/ping":394,"./features/png-alpha":395,"./features/pointer":397,"./features/pointer-events":396,"./features/pointerlock":398,"./features/progress":399,"./features/promises":400,"./features/proximity":401,"./features/proxy":402,"./features/publickeypinning":403,"./features/push-api":404,"./features/queryselector":405,"./features/readonly-attr":406,"./features/referrer-policy":407,"./features/registerprotocolhandler":408,"./features/rel-noopener":409,"./features/rel-noreferrer":410,"./features/rellist":411,"./features/rem":412,"./features/requestanimationframe":413,"./features/requestidlecallback":414,"./features/resizeobserver":415,"./features/resource-timing":416,"./features/rest-parameters":417,"./features/rtcpeerconnection":418,"./features/ruby":419,"./features/same-site-cookie-attribute":420,"./features/screen-orientation":421,"./features/script-async":422,"./features/script-defer":423,"./features/scrollintoview":424,"./features/scrollintoviewifneeded":425,"./features/sdch":426,"./features/selection-api":427,"./features/serviceworkers":428,"./features/setimmediate":429,"./features/sha-2":430,"./features/shadowdom":431,"./features/shadowdomv1":432,"./features/sharedworkers":433,"./features/sni":434,"./features/spdy":435,"./features/speech-recognition":436,"./features/speech-synthesis":437,"./features/spellcheck-attribute":438,"./features/sql-storage":439,"./features/srcset":440,"./features/stopimmediatepropagation":441,"./features/stream":442,"./features/stricttransportsecurity":443,"./features/style-scoped":444,"./features/subresource-integrity":445,"./features/svg":454,"./features/svg-css":446,"./features/svg-filters":447,"./features/svg-fonts":448,"./features/svg-fragment":449,"./features/svg-html":450,"./features/svg-html5":451,"./features/svg-img":452,"./features/svg-smil":453,"./features/tabindex-attr":455,"./features/template":457,"./features/template-literals":456,"./features/testfeat":458,"./features/text-decoration":459,"./features/text-emphasis":460,"./features/text-overflow":461,"./features/text-size-adjust":462,"./features/text-stroke":463,"./features/textcontent":464,"./features/textencoder":465,"./features/tls1-1":466,"./features/tls1-2":467,"./features/tls1-3":468,"./features/token-binding":469,"./features/touch":470,"./features/transforms2d":471,"./features/transforms3d":472,"./features/ttf":473,"./features/typedarrays":474,"./features/u2f":475,"./features/upgradeinsecurerequests":476,"./features/url":477,"./features/urlsearchparams":478,"./features/use-strict":479,"./features/user-select-none":480,"./features/user-timing":481,"./features/vibration":482,"./features/video":483,"./features/videotracks":484,"./features/viewport-units":485,"./features/wai-aria":486,"./features/wasm":487,"./features/wav":488,"./features/wbr-element":489,"./features/web-animation":490,"./features/web-app-manifest":491,"./features/web-bluetooth":492,"./features/web-share":493,"./features/webgl":494,"./features/webgl2":495,"./features/webm":496,"./features/webp":497,"./features/websockets":498,"./features/webvr":499,"./features/webvtt":500,"./features/webworkers":501,"./features/will-change":502,"./features/woff":503,"./features/woff2":504,"./features/word-break":505,"./features/wordwrap":506,"./features/x-doc-messaging":507,"./features/x-frame-options":508,"./features/xhr2":509,"./features/xhtml":510,"./features/xhtmlsmil":511,"./features/xml-serializer":512}],71:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "132": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E", "16": "B A" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "132": "t" }, N: { "1": "B", "2": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "AAC audio file format" };
},{}],72:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB", "132": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "132": "B" }, K: { "2": "5 6 B A D K", "132": "y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "132": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "AC-3 (Dolby Digital) and EC-3 (Dolby Digital Plus) codecs" };
},{}],73:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "130": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "257": "1 RB F I J PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "EventTarget.addEventListener()" };
},{}],74:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "J C TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D KB LB MB NB QB y", "16": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "16": "8" }, M: { "16": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "2": "kB" }, R: { "16": "lB" } }, B: 1, C: "Alternate stylesheet" };
},{}],75:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "132": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "322": "8 DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "Ambient Light API" };
},{}],76:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "1": "8 AB SB BB", "2": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "5 6 A D p q r KB LB MB NB QB y", "2": "E H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "5 6 B A D y", "2": "K" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Animated PNG (APNG)" };
},{}],77:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Arrow functions" };
},{}],78:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "322": "D" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W", "132": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "132": "K" }, L: { "132": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "132": "I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 6, C: "asm.js" };
},{}],79:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X", "194": "g" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "2 4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Async functions" };
},{}],80:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB LB", "16": "MB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "16": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Base64 encoding and decoding" };
},{}],81:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB" }, D: { "1": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E", "33": "B A D X g H L M N O P Q R S T U V W u Y Z a b c" }, E: { "2": "7 F I CB EB", "33": "J C G E B A FB GB HB IB JB" }, F: { "1": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q" }, G: { "2": "3 7 9 UB", "33": "G A VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Web Audio API" };
},{}],82:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "132": "F I J C G E B A D X g H L M N O PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E", "4": "KB LB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "2": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Audio element" };
},{}],83:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "194": "0 2 4 c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Audio Tracks" };
},{}],84:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Autofocus attribute" };
},{}],85:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "129": "0 2 4 t s" }, D: { "1": "2 4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "16": "kB" }, R: { "1": "lB" } }, B: 5, C: "Auxclick" };
},{}],86:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "132": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "132": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "132": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "132": "E KB LB" }, G: { "2": "3 7 9", "772": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 F s dB eB fB hB iB", "132": "3 gB" }, J: { "260": "C B" }, K: { "1": "5 6 A D K y", "132": "B" }, L: { "1028": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "132": "jB" }, P: { "2": "F", "1028": "I" }, Q: { "1": "kB" }, R: { "1028": "lB" } }, B: 4, C: "CSS background-attachment" };
},{}],87:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "36": "OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "516": "F I J C G E B A D X g" }, E: { "1": "C G E B A GB HB IB JB", "772": "7 F I J CB EB FB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB", "36": "LB" }, G: { "1": "G A WB XB YB ZB aB bB", "4": "3 7 9 VB", "516": "UB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "36": "dB", "516": "1 3 F gB", "548": "eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Background-image options" };
},{}],88:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "background-position-x & background-position-y" };
},{}],89:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G TB", "132": "E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "0 2 4 8 b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "5 6 A D O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E H L M N KB LB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS background-repeat round and space" };
},{}],90:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "m n o p q r w x v", "2": "0 1 2 4 RB F I J C G E z t s PB OB", "132": "L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "164": "B A D X g H" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f", "66": "K" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "132": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "Battery Status API" };
},{}],91:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB" }, D: { "1": "0 2 4 8 i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Beacon API" };
},{}],92:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "2": "I", "16": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 2, C: "Printing Events" };
},{}],93:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB", "36": "J C G E B A D" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C", "36": "G E B A D X g H L M N O" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB fB", "36": "1 3 F gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Blob constructing" };
},{}],94:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C", "33": "G E B A D X g H L M N O P Q R" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "33": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB", "33": "VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 dB eB fB", "33": "3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "33": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Blob URLs" };
},{}],95:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "g H L", "129": "D X" }, C: { "1": "0 2 4 x v z t s", "2": "1 RB", "260": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "804": "F I J C G E B A D X g PB OB" }, D: { "260": "0 2 4 8 v z t s DB AB SB BB", "388": "Z a b c d e f K h i j k l m n o p q r w x", "1412": "H L M N O P Q R S T U V W u Y", "1956": "F I J C G E B A D X g" }, E: { "129": "B A HB IB JB", "1412": "J C G E FB GB", "1956": "7 F I CB EB" }, F: { "2": "E KB LB", "260": "h i j k l m n o p q r", "388": "H L M N O P Q R S T U V W u Y Z a b c d e f K", "1796": "MB NB", "1828": "5 6 A D QB y" }, G: { "129": "A ZB aB bB", "1412": "G VB WB XB YB", "1956": "3 7 9 UB" }, H: { "1828": "cB" }, I: { "388": "s hB iB", "1956": "1 3 F dB eB fB gB" }, J: { "1412": "B", "1924": "C" }, K: { "2": "B", "388": "K", "1828": "5 6 A D y" }, L: { "260": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "388": "jB" }, P: { "260": "I", "388": "F" }, Q: { "260": "kB" }, R: { "260": "lB" } }, B: 4, C: "CSS3 Border images" };
},{}],96:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 x v z t s", "257": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "289": "1 PB OB", "292": "RB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F" }, E: { "1": "I C G E B A GB HB IB JB", "33": "7 F CB", "129": "J EB FB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "33": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "33": "dB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Border-radius (rounded corners)" };
},{}],97:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "1": "2 4 8 t s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "BroadcastChannel" };
},{}],98:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m PB OB" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "194": "w", "257": "x" }, E: { "2": "7 F I J C G E B CB EB FB GB HB IB", "513": "A JB" }, F: { "1": "h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y", "194": "f K" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "257": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 6, C: "Brotli Accept-Encoding/Content-Encoding" };
},{}],99:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G TB", "260": "E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "F I J C G E B A D X g H" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N", "33": "O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "33": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB", "33": "VB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "132": "hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "calc() as CSS unit value" };
},{}],100:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Canvas blend modes" };
},{}],101:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "8": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "8": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "8": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Text API for Canvas" };
},{}],102:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "132": "1 RB PB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "132": "7 CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "260": "cB" }, I: { "1": "1 3 F s gB hB iB", "132": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Canvas (basic support)" };
},{}],103:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "ch (character) unit" };
},{}],104:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b", "129": "c d e f K h i j k l m n o p q r" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB", "16": "iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "ChaCha20-Poly1305 cipher suites for TLS" };
},{}],105:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U PB OB", "194": "V W u Y Z a b c d e f K h i j" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB LB", "16": "MB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Channel messaging" };
},{}],106:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "16": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "ChildNode.remove()" };
},{}],107:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "8": "J C G E TB", "900": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB PB", "516": "T U", "772": "F I J C G E B A D X g H L M N O P Q R S OB" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F I J C", "516": "T U V W", "772": "S", "900": "G E B A D X g H L M N O P Q R" }, E: { "1": "C G E B A GB HB IB JB", "8": "7 F I CB", "900": "J EB FB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "8": "6 E A KB LB MB NB", "900": "5 D QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "8": "3 7 9", "900": "UB VB" }, H: { "900": "cB" }, I: { "1": "s hB iB", "8": "dB eB fB", "900": "1 3 F gB" }, J: { "1": "B", "900": "C" }, K: { "1": "K", "8": "B A", "900": "5 6 D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "900": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "classList (DOMTokenList)" };
},{}],108:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Client Hints: DPR, Width, Viewport-Width" };
},{}],109:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2436": "J C G E B A TB" }, B: { "2436": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "772": "R S T U V W u Y Z a b c d e f K h i j", "4100": "0 2 4 k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D", "2564": "X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "10244": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 CB", "2308": "B A IB JB", "2820": "F I J C G E EB FB GB HB" }, F: { "2": "5 6 E A KB LB MB NB QB", "16": "D", "516": "y", "2564": "H L M N O P Q R S T U V W u Y", "10244": "Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9", "2820": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "2308": "s hB iB" }, J: { "2": "C", "2308": "B" }, K: { "2": "5 6 B A D", "16": "y", "3076": "K" }, L: { "2052": "8" }, M: { "1028": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2052": "I", "2308": "F" }, Q: { "10244": "kB" }, R: { "2052": "lB" } }, B: 5, C: "Clipboard API" };
},{}],110:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "16": "1 RB PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g", "132": "H L M N O P Q R S T U V W u Y" }, E: { "1": "B A IB JB", "16": "7 F I J CB", "132": "C G E FB GB HB", "260": "EB" }, F: { "1": "D M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "5 6 E A KB LB MB NB", "132": "H L" }, G: { "1": "A aB bB", "16": "7", "132": "3 9 G UB VB WB XB YB ZB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "132": "1 3 F fB gB" }, J: { "132": "C B" }, K: { "1": "D K y", "16": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.compareDocumentPosition()" };
},{}],111:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C TB", "132": "G E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB" }, G: { "1": "3 7 9 UB", "513": "G A VB WB XB YB ZB aB bB" }, H: { "4097": "cB" }, I: { "1025": "1 3 F s dB eB fB gB hB iB" }, J: { "258": "C B" }, K: { "2": "B", "258": "5 6 A D K y" }, L: { "1025": "8" }, M: { "2049": "t" }, N: { "258": "B A" }, O: { "258": "jB" }, P: { "1025": "F I" }, Q: { "1": "kB" }, R: { "1025": "lB" } }, B: 1, C: "Basic console logging functions" };
},{}],112:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "132": "1 RB F I J C G E B A D PB OB", "260": "X g H L M N O P Q R S T U V W u Y Z a b c d e" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "260": "F I J C G E B A D X g H L M N O P", "772": "Q R S T U V W u Y Z a b c d e f K h i j", "1028": "k l m n o p q r" }, E: { "1": "B A IB JB", "260": "7 F I CB", "772": "J C G E EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "E KB", "132": "5 6 A LB MB NB", "644": "D QB y", "772": "H L M N O P Q R S T U V W", "1028": "u Y Z a b c d e" }, G: { "1": "A aB bB", "260": "3 7 9", "772": "G UB VB WB XB YB ZB" }, H: { "644": "cB" }, I: { "1": "s", "16": "dB eB", "260": "fB", "772": "1 3 F gB hB iB" }, J: { "772": "C B" }, K: { "1": "K", "132": "5 6 B A", "644": "D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "772": "jB" }, P: { "1": "I", "1028": "F" }, Q: { "772": "kB" }, R: { "1028": "lB" } }, B: 6, C: "const" };
},{}],113:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB", "4": "1" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "contenteditable attribute (basic support)" };
},{}],114:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "129": "F I J C G E B A D X g H L M N O P Q R" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X", "257": "g H L M N O P Q R S T" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I CB", "257": "J FB", "260": "EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9", "257": "VB", "260": "UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C", "257": "B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "257": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Content Security Policy 1.0" };
},{}],115:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB", "132": "a b c d", "260": "e", "516": "f K h i j k l m n", "8196": "0 2 4 o p q r w x v z t s" }, D: { "1": "0 2 4 8 j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e", "1028": "f K h", "2052": "i" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R KB LB MB NB QB y", "1028": "S T U", "2052": "V" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "4100": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Content Security Policy Level 2" };
},{}],116:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C TB", "132": "B", "260": "G E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D" }, E: { "2": "7 CB", "513": "J C G E B A FB GB HB IB JB", "644": "F I EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB" }, G: { "513": "G A VB WB XB YB ZB aB bB", "644": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "132": "1 3 F dB eB fB gB" }, J: { "1": "B", "132": "C" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "132": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Cross-Origin Resource Sharing" };
},{}],117:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "4 8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q", "66": "r w x", "129": "0 2 v z t s" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "Credential Management API" };
},{}],118:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E B", "164": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a PB OB", "322": "b c" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, E: { "1": "A", "8": "7 F I J C CB EB FB", "545": "G E B GB HB IB JB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "8": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A", "8": "3 7 9 UB VB WB", "545": "G XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "8": "1 3 F dB eB fB gB hB iB" }, J: { "8": "C B" }, K: { "1": "K", "8": "5 6 B A D y" }, L: { "1": "8" }, M: { "8": "t" }, N: { "8": "B", "164": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Web Cryptography" };
},{}],119:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS all property" };
},{}],120:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F PB OB", "33": "I J C G E B A D X g H" }, D: { "1": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, E: { "1": "E B A HB IB JB", "2": "7 CB", "33": "J C G EB FB GB", "292": "F I" }, F: { "1": "Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "33": "D H L M N O P Q R S T U V W u Y" }, G: { "1": "A YB ZB aB bB", "33": "G VB WB XB", "164": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s", "33": "3 F gB hB iB", "164": "1 dB eB fB" }, J: { "33": "C B" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "33": "jB" }, P: { "1": "F I" }, Q: { "33": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS Animation" };
},{}],121:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 x v z t s", "16": "1 RB F I J C G E B A D X g H L M N O P PB OB", "33": "Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w" }, D: { "16": "F I J C G E B A D X g H L M N O P Q R S", "33": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 F I J CB EB", "33": "C G E B A FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9 UB", "33": "G A VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "1 3 F dB eB fB gB hB iB", "33": "s" }, J: { "16": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "33": "t" }, N: { "2": "B A" }, O: { "16": "jB" }, P: { "16": "F", "33": "I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 5, C: "CSS :any-link selector" };
},{}],122:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "388": "D X g H L" }, C: { "164": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "676": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB" }, D: { "164": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "164": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "164": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "164": "1 3 F s dB eB fB gB hB iB" }, J: { "164": "C B" }, K: { "2": "5 6 B A D y", "164": "K" }, L: { "164": "8" }, M: { "164": "t" }, N: { "2": "B", "388": "A" }, O: { "164": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 5, C: "CSS Appearance" };
},{}],123:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "16": "H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "194": "0 2 4 8 v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y", "194": "h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "194": "K" }, L: { "194": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "2": "kB" }, R: { "194": "lB" } }, B: 7, C: "CSS @apply rule" };
},{}],124:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "132": "0 2 4 c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "132": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Counter Styles" };
},{}],125:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p", "194": "0 2 4 8 q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "33": "E B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c KB LB MB NB QB y", "194": "d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB", "33": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "194": "K" }, L: { "194": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "194": "kB" }, R: { "194": "lB" } }, B: 7, C: "CSS Backdrop Filter" };
},{}],126:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D PB OB" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS background-position edge offsets" };
},{}],127:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB" }, D: { "1": "0 2 4 8 e f K h i j k l m n o q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d", "260": "p" }, E: { "2": "7 F I J C CB EB FB", "132": "G E B A GB HB IB JB" }, F: { "1": "R S T U V W u Y Z a b d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q KB LB MB NB QB y", "260": "c" }, G: { "2": "3 7 9 UB VB WB", "132": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "260": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS background-blend-mode" };
},{}],128:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q", "164": "0 2 4 8 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J CB EB", "164": "C G E B A FB GB HB IB JB" }, F: { "2": "E KB LB MB NB", "129": "5 6 A D QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 UB VB", "164": "G A WB XB YB ZB aB bB" }, H: { "132": "cB" }, I: { "2": "1 3 F dB eB fB gB", "164": "s hB iB" }, J: { "2": "C", "164": "B" }, K: { "2": "B", "129": "5 6 A D y", "164": "K" }, L: { "164": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 5, C: "CSS box-decoration-break" };
},{}],129:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "33": "PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "33": "I", "164": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "33": "3 9", "164": "7" }, H: { "2": "cB" }, I: { "1": "3 F s gB hB iB", "164": "1 dB eB fB" }, J: { "1": "B", "33": "C" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Box-shadow" };
},{}],130:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "2": "0 2 4 8 r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "2": "7 CB", "33": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D e f K h i j k l m n o p q r KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d" }, G: { "33": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "s", "33": "1 3 F dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "2": "I", "33": "F" }, Q: { "33": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS Canvas Drawings" };
},{}],131:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Case-insensitive CSS attribute selectors" };
},{}],132:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "2 4 t s", "2": "1 RB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB", "644": "0 q r w x v z" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S", "260": "2 4 8 s DB AB SB BB", "292": "0 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "2": "7 F I J CB EB FB", "292": "C G E B A GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "260": "l m n o p q r", "292": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k" }, G: { "2": "3 7 9 UB VB", "292": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "260": "s", "292": "hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "292": "K" }, L: { "260": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "292": "jB" }, P: { "292": "F I" }, Q: { "292": "kB" }, R: { "260": "lB" } }, B: 4, C: "CSS clip-path property (for HTML)" };
},{}],133:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "1": "0 2 4 8 z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "194": "v" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y", "194": "h i" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS Containment" };
},{}],134:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS Counters" };
},{}],135:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J TB", "2340": "C G E B A" }, B: { "2": "D X g H L" }, C: { "2": "1 RB PB", "545": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "1025": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A IB JB", "2": "7 F I CB EB", "164": "J", "4644": "C G E FB GB HB" }, F: { "2": "5 6 E A H L M N O P Q R S T U V W KB LB MB NB", "545": "D QB y", "1025": "u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "A aB bB", "2": "3 7 9", "4260": "UB VB", "4644": "G WB XB YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "1025": "s" }, J: { "2": "C", "4260": "B" }, K: { "2": "5 6 B A", "545": "D y", "1025": "K" }, L: { "1025": "8" }, M: { "545": "t" }, N: { "2340": "B A" }, O: { "4260": "jB" }, P: { "1025": "F I" }, Q: { "2": "kB" }, R: { "1025": "lB" } }, B: 7, C: "Crisp edges/pixelated images" };
},{}],136:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L", "33": "0 2 4 8 M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A IB JB", "2": "7 F I CB", "33": "J C G E EB FB GB HB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "A aB bB", "2": "3 7 9", "33": "G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "33": "s hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS Cross-Fade Function" };
},{}],137:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "16": "1 RB PB OB" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "16": "F I J C G E B A D X g", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "1": "A IB JB", "16": "7 F I CB", "132": "J C G E B EB FB GB HB" }, F: { "1": "h i j k l m n o p q r", "16": "5 6 E A KB LB MB NB", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K", "260": "D QB y" }, G: { "1": "A bB", "16": "3 7 9 UB VB", "132": "G WB XB YB ZB aB" }, H: { "260": "cB" }, I: { "1": "s", "16": "1 dB eB fB", "132": "3 F gB hB iB" }, J: { "16": "C", "132": "B" }, K: { "16": "5 6 B A D", "132": "K", "260": "y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "132": "jB" }, P: { "1": "I", "132": "F" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 7, C: ":default CSS pseudo-class" };
},{}],138:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Explicit descendant combinator >>" };
},{}],139:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "164": "B A" }, B: { "164": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u", "66": "0 2 4 8 Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y", "66": "j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "292": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "B K", "292": "5 6 A D y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "164": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "66": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Device Adaptation" };
},{}],140:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L PB OB", "33": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: ":dir() CSS pseudo-class" };
},{}],141:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS display: contents" };
},{}],142:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "33": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "164": "1 RB PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "33": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS element() function" };
},{}],143:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "33": "B A" }, B: { "33": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "33": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Exclusions Level 1" };
},{}],144:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Feature Queries" };
},{}],145:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G CB EB FB GB", "33": "E" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB", "33": "YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS filter() function" };
},{}],146:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1028": "X g H L", "1346": "D" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "196": "d", "516": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c OB" }, D: { "1": "0 2 4 8 t s DB AB SB BB", "2": "F I J C G E B A D X g H L M", "33": "N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, E: { "1": "B A HB IB JB", "2": "7 F I CB EB", "33": "J C G E FB GB" }, F: { "1": "j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i" }, G: { "1": "A ZB aB bB", "2": "3 7 9 UB", "33": "G VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "33": "hB iB" }, J: { "2": "C", "33": "B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 5, C: "CSS Filter Effects" };
},{}],147:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "16": "TB", "516": "G", "1540": "J C" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "132": "1", "260": "RB" }, D: { "1": "0 2 4 8 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "I J C G", "132": "F" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "I CB", "132": "7 F" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "E KB", "260": "5 6 A LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "16": "dB eB", "132": "fB" }, J: { "1": "C B" }, K: { "1": "D K y", "260": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "::first-letter CSS pseudo-element selector" };
},{}],148:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "132": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS first-line pseudo-element" };
},{}],149:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "C G E B A", "2": "TB", "8": "J" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9", "132": "UB VB WB" }, H: { "2": "cB" }, I: { "1": "1 s hB iB", "260": "dB eB fB", "513": "3 F gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS position:fixed" };
},{}],150:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "AB SB BB", "2": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "194": "8" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o KB LB MB NB QB y", "194": "p q r" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: ":focus-within CSS pseudo-class" };
},{}],151:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o PB OB", "322": "0 2 4 p q r w x v z t s" }, D: { "1": "AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "194": "0 2 4 8 w x v z t s DB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y", "194": "f K h i j k l m n o p" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "194": "K" }, L: { "194": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "194": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS font-rendering controls" };
},{}],152:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G PB OB" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS font-stretch" };
},{}],153:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C TB", "132": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS Generated content for pseudo-elements" };
},{}],154:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "33": "F I J C G E B A D X g H OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "B A D X g H L M N O P Q R S T U", "36": "F I J C G E" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 CB", "33": "J EB", "36": "F I" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E A KB LB MB NB", "33": "D QB", "164": "5 6" }, G: { "1": "G A WB XB YB ZB aB bB", "33": "UB VB", "36": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "33": "3 F gB", "36": "1 dB eB fB" }, J: { "1": "B", "36": "C" }, K: { "1": "K y", "2": "B A", "33": "D", "164": "5 6" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Gradients" };
},{}],155:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "8": "E", "292": "B A" }, B: { "1": "L", "292": "D X g H" }, C: { "1": "2 4 t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB", "8": "O P Q R S T U V W u Y Z a b c d e f K h i", "584": "j k l m n o p q r w x v", "1025": "0 z" }, D: { "1": "8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T", "8": "U V W u", "200": "0 2 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "1025": "4" }, E: { "1": "A IB JB", "2": "7 F I CB EB", "8": "J C G E B FB GB HB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y", "200": "u Y Z a b c d e f K h i j k l m" }, G: { "1": "A bB", "2": "3 7 9 UB", "8": "G VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 F dB eB fB gB", "8": "3 hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "8": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "292": "B A" }, O: { "2": "jB" }, P: { "2": "I", "8": "F" }, Q: { "200": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Grid Layout" };
},{}],156:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "16": "H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS hanging-punctuation" };
},{}],157:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: ":has() CSS relational pseudo-class" };
},{}],158:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "J C G E B A TB" }, B: { "16": "D X g H L" }, C: { "16": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "2 4 8 s DB AB SB BB", "16": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "16": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "16": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "16": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "16": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "16": "8" }, M: { "16": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 5, C: "CSS4 Hyphenation" };
},{}],159:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "33": "B A" }, B: { "33": "D X g H L" }, C: { "1": "0 2 4 m n o p q r w x v z t s", "2": "1 RB F I PB OB", "33": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, D: { "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t", "132": "2 4 8 s DB AB SB BB" }, E: { "2": "7 F I CB", "33": "J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y", "132": "l m n o p q r" }, G: { "2": "7 9", "33": "3 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "132": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "36": "jB" }, P: { "2": "F", "132": "I" }, Q: { "2": "kB" }, R: { "132": "lB" } }, B: 5, C: "CSS Hyphenation" };
},{}],160:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "132": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 image-orientation" };
},{}],161:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P", "33": "0 2 4 8 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I CB EB", "33": "J C G E B A FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 UB", "33": "G A VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "33": "s hB iB" }, J: { "2": "C", "33": "B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS image-set" };
},{}],162:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D", "260": "X g H L" }, C: { "1": "0 2 4 x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "516": "Y Z a b c d e f K h i j k l m n o p q r w" }, D: { "1": "0 2 4 8 t s DB AB SB BB", "2": "F", "16": "I J C G E B A D X g", "260": "z", "772": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v" }, E: { "1": "A IB JB", "2": "7 F CB", "16": "I", "772": "J C G E B EB FB GB HB" }, F: { "1": "j k l m n o p q r", "16": "E KB", "260": "5 6 A D i LB MB NB QB y", "772": "H L M N O P Q R S T U V W u Y Z a b c d e f K h" }, G: { "1": "A bB", "2": "3 7 9", "772": "G UB VB WB XB YB ZB aB" }, H: { "132": "cB" }, I: { "1": "s", "2": "1 dB eB fB", "260": "3 F gB hB iB" }, J: { "2": "C", "260": "B" }, K: { "260": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "260": "jB" }, P: { "1": "I", "260": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: ":in-range and :out-of-range CSS pseudo-classes" };
},{}],163:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "B A", "388": "E" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 v z t s", "16": "1 RB PB OB", "132": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "388": "F I" }, D: { "1": "0 2 4 8 i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h" }, E: { "1": "A IB JB", "16": "7 F I J CB", "132": "C G E B FB GB HB", "388": "EB" }, F: { "1": "V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "5 6 E A KB LB MB NB", "132": "H L M N O P Q R S T U", "516": "D QB y" }, G: { "1": "A bB", "16": "3 7 9 UB VB", "132": "G WB XB YB ZB aB" }, H: { "516": "cB" }, I: { "1": "s", "16": "1 dB eB fB iB", "132": "hB", "388": "3 F gB" }, J: { "16": "C", "132": "B" }, K: { "1": "K", "16": "5 6 B A D", "516": "y" }, L: { "1": "8" }, M: { "132": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: ":indeterminate CSS pseudo-class" };
},{}],164:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "4": "E", "164": "B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB", "164": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Initial Letter" };
},{}],165:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS initial value" };
},{}],166:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "16": "TB", "132": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "C G E B A FB GB HB IB JB", "16": "CB", "132": "7 F I J EB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E KB", "132": "5 6 A D H L LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "2": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "132": "1 3 F fB gB" }, J: { "132": "C B" }, K: { "1": "K", "132": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "letter-spacing CSS property" };
},{}],167:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "16": "F I J C G E B A D X", "33": "0 2 4 8 g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F CB", "33": "I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9", "33": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "dB eB", "33": "1 3 F s fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS line-clamp" };
},{}],168:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "RB", "164": "1 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j PB OB" }, D: { "292": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "292": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "292": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "292": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "292": "1 3 F s dB eB fB gB hB iB" }, J: { "292": "C B" }, K: { "2": "5 6 B A D y", "292": "K" }, L: { "292": "8" }, M: { "164": "t" }, N: { "2": "B A" }, O: { "292": "jB" }, P: { "292": "F I" }, Q: { "292": "kB" }, R: { "292": "lB" } }, B: 7, C: "CSS Logical Properties" };
},{}],169:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS ::marker pseudo-element" };
},{}],170:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 t s", "2": "1 RB", "260": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB" }, D: { "164": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "164": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "164": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "164": "s hB iB", "676": "1 3 F dB eB fB gB" }, J: { "164": "C B" }, K: { "2": "5 6 B A D y", "164": "K" }, L: { "164": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "164": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 4, C: "CSS Masks" };
},{}],171:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "16": "1 RB PB OB", "548": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "16": "F I J C G E B A D X g", "164": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F CB", "16": "I", "164": "J C G EB FB GB", "257": "E B A HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9 UB VB", "164": "G WB XB", "257": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "1 dB eB fB", "164": "3 F s gB hB iB" }, J: { "16": "C", "164": "B" }, K: { "2": "5 6 B A D y", "164": "K" }, L: { "164": "8" }, M: { "548": "t" }, N: { "2": "B A" }, O: { "164": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 5, C: ":matches() CSS pseudo-class" };
},{}],172:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Media Queries: interaction media features" };
},{}],173:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "260": "F I J C G E B A D X g H PB OB" }, D: { "1": "0 2 4 8 Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "548": "F I J C G E B A D X g H L M N O P Q R S T U V W u" }, E: { "2": "7 CB", "548": "F I J C G E B A EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E", "548": "5 6 A D KB LB MB NB QB" }, G: { "16": "7", "548": "3 9 G A UB VB WB XB YB ZB aB bB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "548": "1 3 F fB gB" }, J: { "548": "C B" }, K: { "1": "K y", "548": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Media Queries: resolution feature" };
},{}],174:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "16": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB y", "16": "q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "Media Queries: scripting media feature" };
},{}],175:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "8": "J C G TB", "129": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "129": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "129": "F I J EB", "388": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "G A WB XB YB ZB aB bB", "129": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "129": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS3 Media Queries" };
},{}],176:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u", "194": "Y Z a b c d e f K h i j" }, E: { "2": "7 F I J C CB EB FB", "260": "G E B A GB HB IB JB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u KB LB MB NB QB y" }, G: { "2": "3 7 9 UB VB WB", "260": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Blending of HTML/SVG elements" };
},{}],177:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "194": "m n o" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y", "194": "Z a b" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 7, C: "CSS Motion Path" };
},{}],178:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "16": "7 CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "16": "7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS namespaces" };
},{}],179:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t PB OB", "16": "2 4 s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "selector list argument of :not()" };
},{}],180:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "selector list argument of :nth-child and :nth-last-child CSS pseudo-classes" };
},{}],181:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "4": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS3 Opacity" };
},{}],182:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E KB", "132": "5 6 A D LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "132": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "132": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: ":optional CSS pseudo-class" };
},{}],183:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "4 8 s DB AB SB BB", "2": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS overflow-anchor (Scroll Anchoring)" };
},{}],184:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "388": "B A", "900": "J C G E TB" }, B: { "388": "D X g H L" }, C: { "900": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "900": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "772": "B", "900": "7 F I J C G E A CB EB FB GB HB IB JB" }, F: { "16": "E KB", "129": "5 6 A D LB MB NB QB y", "900": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "900": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "129": "cB" }, I: { "900": "1 3 F s dB eB fB gB hB iB" }, J: { "900": "C B" }, K: { "129": "5 6 B A D y", "900": "K" }, L: { "900": "8" }, M: { "900": "t" }, N: { "388": "B A" }, O: { "900": "jB" }, P: { "900": "F I" }, Q: { "900": "kB" }, R: { "900": "lB" } }, B: 2, C: "CSS page-break properties" };
},{}],185:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "132": "G E B A" }, B: { "132": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N PB OB", "132": "0 2 4 O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "132": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "16": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D y", "258": "K" }, L: { "1": "8" }, M: { "132": "t" }, N: { "258": "B A" }, O: { "258": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS Paged Media (@page)" };
},{}],186:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB" }, D: { "1": "0 2 4 8 q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: ":placeholder-shown CSS pseudo-class" };
},{}],187:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "36": "B A" }, B: { "36": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB PB OB", "33": "O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "164": "F I J C G E B A D X g H L M N" }, D: { "1": "4 8 DB AB SB BB", "36": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "1": "A IB JB", "2": "7 F CB", "36": "I J C G E B EB FB GB HB" }, F: { "1": "n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "36": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m" }, G: { "1": "A bB", "2": "7 9", "36": "3 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "36": "1 3 F dB eB fB gB hB iB" }, J: { "36": "C B" }, K: { "2": "5 6 B A D y", "36": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "36": "B A" }, O: { "36": "jB" }, P: { "36": "F I" }, Q: { "36": "kB" }, R: { "1": "lB" } }, B: 5, C: "::placeholder CSS pseudo-element" };
},{}],188:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "16": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB", "33": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "16": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c", "132": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 F I J CB EB FB", "132": "C G E B A GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9 UB VB WB", "132": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "16": "C B" }, K: { "2": "5 6 B A D y", "132": "K" }, L: { "132": "8" }, M: { "33": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "2": "F", "132": "I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 1, C: "CSS :read-only and :read-write selectors" };
},{}],189:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "132": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB", "16": "FB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Rebeccapurple color" };
},{}],190:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "33": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "33": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "33": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "33": "1 3 F s dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS Reflections" };
},{}],191:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "420": "B A" }, B: { "420": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "36": "H L M N", "66": "O P Q R S T U V W u Y Z a b c d" }, E: { "2": "7 F I J CB EB", "33": "C G E B A FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 UB VB", "33": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "420": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Regions" };
},{}],192:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "33": "F I J C G E B A D X g H OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E", "33": "B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB", "33": "J EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E A KB LB MB NB", "33": "D QB", "36": "5 6" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9", "33": "UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 dB eB fB", "33": "3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "B A", "33": "D", "36": "5 6" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Repeating Gradients" };
},{}],193:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "F" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB", "132": "y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS resize property" };
},{}],194:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS revert value" };
},{}],195:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v", "194": "0 2 4 8 z t s DB AB SB BB" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h KB LB MB NB QB y", "194": "i j k l m n o p q r" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "194": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "194": "kB" }, R: { "194": "lB" } }, B: 7, C: "#rrggbbaa hex color notation" };
},{}],196:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "450": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y", "450": "u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "450": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSSOM Scroll-behavior" };
},{}],197:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "289": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 F I CB", "289": "J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "289": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9 UB VB", "289": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "dB eB", "289": "1 3 F s fB gB hB iB" }, J: { "289": "C B" }, K: { "2": "5 6 B A D y", "289": "K" }, L: { "289": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "289": "jB" }, P: { "289": "F I" }, Q: { "289": "kB" }, R: { "289": "lB" } }, B: 7, C: "CSS scrollbar styling" };
},{}],198:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "C G E B A", "2": "TB", "8": "J" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS 2.1 selectors" };
},{}],199:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J", "132": "C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "2": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS3 selectors" };
},{}],200:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "33": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 D K y", "16": "6 B A" }, L: { "1": "8" }, M: { "33": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "::selection CSS pseudo-element" };
},{}],201:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c", "194": "d e f" }, E: { "1": "A IB JB", "2": "7 F I J C CB EB FB", "33": "G E B GB HB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 UB VB WB", "33": "G XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Shapes Level 1" };
},{}],202:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "6308": "B", "6436": "A" }, B: { "6436": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h PB OB", "2052": "0 2 4 i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "A JB", "2": "7 F I J C G CB EB FB GB", "3108": "E B HB IB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB", "3108": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2052": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Scroll snap points" };
},{}],203:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "L", "2": "D X g H" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U PB OB", "194": "V W u Y Z a", "516": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R K h i j k l m n o p q r w x v", "322": "0 2 S T U V W u Y Z a b c d e f z t", "1028": "4 8 s DB AB SB BB" }, E: { "2": "7 F I J CB EB", "33": "G E B A GB HB IB JB", "2084": "C FB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h KB LB MB NB QB y", "322": "i j k", "1028": "l m n o p q r" }, G: { "2": "3 7 9 UB", "33": "G A XB YB ZB aB bB", "2084": "VB WB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "1028": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1028": "8" }, M: { "516": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "322": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS position:sticky" };
},{}],204:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O PB OB", "66": "P Q R" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB", "132": "y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D", "132": "y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS.supports() API" };
},{}],205:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "132": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS Table display" };
},{}],206:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "4": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A PB OB", "33": "D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, D: { "1": "0 2 4 8 q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d", "322": "e f K h i j k l m n o p" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q KB LB MB NB QB y", "578": "R S T U V W u Y Z a b c" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 text-align-last" };
},{}],207:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "132": "D X g H L" }, C: { "132": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K", "388": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "132": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "132": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y", "388": "U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "132": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "132": "cB" }, I: { "132": "1 3 F s dB eB fB gB hB iB" }, J: { "132": "C B" }, K: { "132": "5 6 B A D y", "388": "K" }, L: { "388": "8" }, M: { "132": "t" }, N: { "132": "B A" }, O: { "132": "jB" }, P: { "132": "F", "388": "I" }, Q: { "388": "kB" }, R: { "388": "lB" } }, B: 5, C: "CSS text-indent" };
},{}],208:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "J C TB", "132": "G E B A" }, B: { "132": "D X g H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "1025": "2 4 s", "1602": "t" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "322": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y", "322": "Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "322": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "322": "K" }, L: { "322": "8" }, M: { "1602": "t" }, N: { "132": "B A" }, O: { "2": "jB" }, P: { "2": "F", "322": "I" }, Q: { "322": "kB" }, R: { "322": "lB" } }, B: 5, C: "CSS text-justify" };
},{}],209:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "2": "7 F I J C G E CB EB FB GB HB", "16": "B", "33": "A IB JB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS text-orientation" };
},{}],210:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "161": "G E B A" }, B: { "161": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "16": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Text 4 text-spacing" };
},{}],211:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "129": "B A" }, B: { "129": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "260": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "4": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "B", "4": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Text-shadow" };
},{}],212:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "A", "164": "B" }, B: { "132": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t", "260": "2" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y", "260": "l" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "132": "A", "164": "B" }, O: { "2": "jB" }, P: { "1": "I", "16": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS touch-action level 2 values" };
},{}],213:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E TB", "289": "B" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "194": "Y Z a b c d e f K h i j k l m n o p q r w x v", "1025": "0 2 4 z t s" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB YB", "516": "A ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "289": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS touch-action property" };
},{}],214:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "I J C G E B A D X g H", "164": "F" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "33": "J EB", "164": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB", "33": "D", "164": "5 6 A MB NB QB" }, G: { "1": "G A WB XB YB ZB aB bB", "33": "VB", "164": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "33": "1 3 F dB eB fB gB" }, J: { "1": "B", "33": "C" }, K: { "1": "K y", "33": "D", "164": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 Transitions" };
},{}],215:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 x v z t s", "33": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "132": "1 RB F I J C G E PB OB", "292": "B A D X g H L" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L", "548": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "132": "7 F I J C G CB EB FB GB", "548": "E B A HB IB JB" }, F: { "132": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "132": "3 7 9 G UB VB WB XB", "548": "A YB ZB aB bB" }, H: { "16": "cB" }, I: { "1": "s", "16": "1 3 F dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 4, C: "CSS unicode-bidi property" };
},{}],216:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS unset value" };
},{}],217:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "260": "H L" }, C: { "1": "0 2 4 a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q", "194": "r" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y", "194": "e" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Variables (Custom Properties)" };
},{}],218:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C TB", "129": "G E" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "129": "5 6 E A KB LB MB NB QB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS widows & orphans" };
},{}],219:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB", "322": "f K h i j" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J", "16": "C", "33": "G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "2": "7 F CB", "16": "I", "33": "J C G E B A EB FB GB HB IB JB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d" }, G: { "16": "3 7 9", "33": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB fB", "33": "1 3 F gB hB iB" }, J: { "33": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "36": "B A" }, O: { "33": "jB" }, P: { "1": "I", "33": "F" }, Q: { "33": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS writing-mode property" };
},{}],220:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C TB", "129": "G E B A" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "CSS zoom" };
},{}],221:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 attr() function" };
},{}],222:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "8": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "33": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "33": "7 F I CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "33": "3 7 9" }, H: { "1": "cB" }, I: { "1": "3 F s gB hB iB", "33": "1 dB eB fB" }, J: { "1": "B", "33": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Box-sizing" };
},{}],223:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "4": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "2": "E", "4": "KB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS3 Colors" };
},{}],224:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "33": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB" }, D: { "33": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "33": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D QB y", "2": "5 6 E A KB LB MB NB", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "33": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 Cursors: grab & grabbing" };
},{}],225:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "33": "1 RB F I J C G E B A D X g H L M N O P Q R S PB OB" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, E: { "1": "E B A HB IB JB", "33": "7 F I J C G CB EB FB GB" }, F: { "1": "D T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB", "33": "H L M N O P Q R S" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 Cursors: zoom-in & zoom-out" };
},{}],226:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "132": "J C G TB" }, B: { "1": "g H L", "260": "D X" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "4": "1 RB PB OB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "4": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "260": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 Cursors (original values)" };
},{}],227:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB PB OB", "33": "0 2 4 t s", "164": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, D: { "1": "0 2 4 8 l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P", "132": "Q R S T U V W u Y Z a b c d e f K h i j k" }, E: { "2": "7 F I J CB EB", "132": "C G E B A FB GB HB IB JB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "E KB LB MB", "132": "H L M N O P Q R S T U V W u", "164": "5 6 A D NB QB y" }, G: { "2": "3 7 9 UB VB", "132": "G A WB XB YB ZB aB bB" }, H: { "164": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "132": "hB iB" }, J: { "132": "C B" }, K: { "1": "K", "2": "B", "164": "5 6 A D y" }, L: { "1": "8" }, M: { "33": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 tab-size" };
},{}],228:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS currentColor value" };
},{}],229:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "8": "B A" }, B: { "8": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB", "194": "S T U V W u Y", "200": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V", "66": "W u Y Z a b" }, E: { "2": "7 F I CB EB", "8": "J C G E B A FB GB HB IB JB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "66": "H L M N O" }, G: { "2": "3 7 9 UB VB", "8": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "200": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Custom Elements v0" };
},{}],230:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "8": "B A" }, B: { "8": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB", "8": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v", "8": "0 z", "132": "2 4 8 t s DB AB SB BB" }, E: { "2": "7 F I J C CB EB FB GB", "8": "G E B HB", "132": "A IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j KB LB MB NB QB y", "132": "k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB YB ZB aB", "132": "A bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "132": "8" }, M: { "8": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "132": "I" }, Q: { "8": "kB" }, R: { "132": "lB" } }, B: 1, C: "Custom Elements v1" };
},{}],231:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB", "132": "J C G E B" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F", "16": "I J C G X g", "388": "E B A D" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F CB", "16": "I J", "388": "EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB", "132": "5 6 A" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "9", "16": "3 7", "388": "UB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "388": "1 3 F gB" }, J: { "1": "B", "388": "C" }, K: { "1": "D K y", "2": "B", "132": "5 6 A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "CustomEvent" };
},{}],232:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E", "260": "B A" }, B: { "260": "D X g H L" }, C: { "8": "1 RB PB OB", "516": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "8": "F I J C G E B A D X g H L M N O", "132": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "8": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "8": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "iB", "8": "1 3 F dB eB fB gB hB", "132": "s" }, J: { "1": "B", "8": "C" }, K: { "1": "5 6 B A D y", "8": "K" }, L: { "1": "8" }, M: { "516": "t" }, N: { "8": "B A" }, O: { "8": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Datalist element" };
},{}],233:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "4": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "4": "1 RB F I PB OB", "129": "0 2 4 v z t s" }, D: { "1": "0 o p q r w x v z t", "4": "F I J", "129": "2 4 8 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n s DB AB SB BB" }, E: { "4": "7 F I CB", "129": "J C G E B A EB FB GB HB IB JB" }, F: { "1": "5 6 D b c d e f K h i j k QB y", "4": "E A KB LB MB NB", "129": "H L M N O P Q R S T U V W u Y Z a l m n o p q r" }, G: { "4": "3 7 9", "129": "G A UB VB WB XB YB ZB aB bB" }, H: { "4": "cB" }, I: { "4": "dB eB fB", "129": "1 3 F s gB hB iB" }, J: { "129": "C B" }, K: { "1": "5 6 D y", "4": "B A", "129": "K" }, L: { "129": "8" }, M: { "129": "t" }, N: { "1": "A", "4": "B" }, O: { "129": "jB" }, P: { "129": "F I" }, Q: { "1": "kB" }, R: { "129": "lB" } }, B: 1, C: "dataset & data-* attributes" };
},{}],234:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "132": "G", "260": "E B A" }, B: { "260": "D X H L", "772": "g" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Data URIs" };
},{}],235:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "E B A TB", "8": "J C G" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "RB", "8": "1 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB", "194": "q r" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F I J C G E B A", "257": "O P Q R S T U V W u Y Z a b c d e", "769": "D X g H L M N" }, E: { "1": "A IB JB", "8": "7 F I CB EB", "257": "J C G E B FB GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 D QB y", "8": "E A KB LB MB NB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "8": "3 7 9 UB" }, H: { "8": "cB" }, I: { "1": "3 F s gB hB iB", "8": "1 dB eB fB" }, J: { "1": "B", "8": "C" }, K: { "1": "K", "8": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "769": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Details & Summary elements" };
},{}],236:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "132": "A" }, B: { "1": "D X g H L" }, C: { "2": "1 RB PB", "4": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "F I OB" }, D: { "2": "F I J", "4": "0 2 4 8 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "4": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "7 9", "4": "3 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "dB eB fB", "4": "1 3 F s gB hB iB" }, J: { "2": "C", "4": "B" }, K: { "1": "D y", "2": "5 6 B A", "4": "K" }, L: { "4": "8" }, M: { "4": "t" }, N: { "1": "A", "2": "B" }, O: { "4": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 4, C: "DeviceOrientation & DeviceMotion events" };
},{}],237:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Window.devicePixelRatio" };
},{}],238:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "194": "0 2 4 t s" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a", "322": "b c d e f" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N KB LB MB NB QB y", "578": "O P Q R S" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Dialog element" };
},{}],239:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "16": "TB", "129": "E B", "130": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "129": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "EventTarget.dispatchEvent" };
},{}],240:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "document.currentScript" };
},{}],241:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "16": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "document.evaluate & XPath" };
},{}],242:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A FB GB HB IB JB", "16": "7 F I CB EB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "16": "E KB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "7 9", "16": "3 UB VB" }, H: { "2": "cB" }, I: { "1": "3 gB hB iB", "2": "1 F s dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Document.execCommand()" };
},{}],243:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "16": "I" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "document.head" };
},{}],244:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "2 4 8 t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v", "194": "0 z" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y", "194": "j" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "194": "kB" }, R: { "2": "lB" } }, B: 1, C: "DOM manipulation convenience methods" };
},{}],245:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Document Object Model Range" };
},{}],246:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "DOMContentLoaded" };
},{}],247:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "16": "I" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "5 6 E A KB LB MB NB" }, G: { "1": "G A WB XB YB ZB aB bB", "16": "3 7 9 UB VB" }, H: { "16": "cB" }, I: { "1": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "DOMFocusIn & DOMFocusOut events" };
},{}],248:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "516": "c d e f K h i j k l m n o p q r" }, D: { "16": "F I J C", "132": "0 2 4 8 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "388": "G" }, E: { "1": "A JB", "16": "7 F CB", "132": "I J C G E B EB FB GB HB IB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9", "132": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "132": "3 F s gB hB iB", "292": "1 dB eB fB" }, J: { "16": "C", "132": "B" }, K: { "2": "5 6 B A D y", "132": "K" }, L: { "132": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "132": "jB" }, P: { "132": "F I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 4, C: "DOMMatrix" };
},{}],249:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O PB OB" }, D: { "1": "0 2 4 8 g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Download attribute" };
},{}],250:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "644": "J C G E TB", "772": "B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "8": "5 6 E A KB LB MB NB QB" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "y", "2": "K", "8": "5 6 B A D" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Drag and Drop" };
},{}],251:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 1, C: "Element.closest()" };
},{}],252:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "16": "RB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "16": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "E KB LB MB NB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "D K y", "16": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "document.elementFromPoint()" };
},{}],253:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "164": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "1": "0 2 4 8 l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d", "132": "e f K h i j k" }, E: { "2": "7 F I J CB EB FB", "164": "C G E B A GB HB IB JB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q KB LB MB NB QB y", "132": "R S T U V W u" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 3, C: "Encrypted Media Extensions" };
},{}],254:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "2": "TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "EOT - Embedded OpenType fonts" };
},{}],255:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C TB", "260": "E", "1026": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "4": "1 RB PB OB", "132": "F I J C G E B A D X g H L M N O P" }, D: { "1": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F I J C G E B A D X g H L M N", "132": "O P Q R" }, E: { "1": "J C G E B A FB GB HB IB JB", "4": "7 F I CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "4": "5 6 E A D KB LB MB NB QB", "132": "y" }, G: { "1": "G A VB WB XB YB ZB aB bB", "4": "3 7 9 UB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "4": "1 dB eB fB", "132": "3 gB", "900": "F" }, J: { "1": "B", "4": "C" }, K: { "1": "K", "4": "5 6 B A D", "132": "y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "ECMAScript 5" };
},{}],256:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k", "132": "l m n o p q r" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u KB LB MB NB QB y", "132": "Y Z a b c d e" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "ES6 classes" };
},{}],257:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "194": "H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "322": "2 4 t s" }, D: { "1": "SB BB", "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "194": "AB" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB y", "194": "q r" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "ES6 module" };
},{}],258:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H PB OB", "132": "L M N O P Q R S T", "260": "U V W u Y Z", "516": "a" }, D: { "1": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N", "1028": "O P Q R S T U V W u Y Z a b c" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "1028": "H L M N O P" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 F dB eB fB", "1028": "3 gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "ES6 Number" };
},{}],259:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "4": "E KB LB MB NB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 D K y", "4": "B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Server-sent events" };
},{}],260:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c PB OB", "1025": "i", "1218": "d e f K h" }, D: { "1": "0 2 4 8 l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i", "260": "j", "772": "k" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y", "260": "W", "772": "u" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Fetch" };
},{}],261:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "TB", "132": "G E", "388": "J C B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H", "16": "L M N O" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "16": "E KB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "388": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B", "260": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "disabled attribute of the fieldset element" };
},{}],262:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "260": "B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "260": "F I J C G E B A D X g H L M N O P Q R S T U V W OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I", "260": "X g H L M N O P Q R S T U V W u Y Z a b c d e f K", "388": "J C G E B A D" }, E: { "1": "B A IB JB", "2": "7 F I CB", "260": "J C G E FB GB HB", "388": "EB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E A KB LB MB NB", "260": "5 6 D H L M N O P Q R S T QB y" }, G: { "1": "A aB bB", "2": "3 7 9 UB", "260": "G VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "dB eB fB", "260": "hB", "388": "1 3 F gB" }, J: { "260": "B", "388": "C" }, K: { "1": "K", "2": "B A", "260": "5 6 D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B", "260": "A" }, O: { "260": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "File API" };
},{}],263:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E A KB LB MB NB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 D K y", "2": "B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "FileReader API" };
},{}],264:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB", "16": "5 6 A MB NB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 D K y", "2": "B", "16": "6 A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "FileReaderSync" };
},{}],265:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C", "33": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "36": "G E B A D" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "33": "B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "33": "I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Filesystem & FileWriter API" };
},{}],266:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB" }, D: { "1": "4 8 s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m", "16": "n o p", "388": "0 2 q r w x v z t" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB fB", "16": "1 3 F gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "y", "16": "5 6 B A D", "129": "K" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "129": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "FLAC audio format" };
},{}],267:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "1028": "A", "1316": "B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "164": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "516": "R S T U V W" }, D: { "1": "0 2 4 8 Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "Q R S T U V W u", "164": "F I J C G E B A D X g H L M N O P" }, E: { "1": "E B A HB IB JB", "33": "C G FB GB", "164": "7 F I J CB EB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB", "33": "H L" }, G: { "1": "A YB ZB aB bB", "33": "G WB XB", "164": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "164": "1 3 F dB eB fB gB" }, J: { "1": "B", "164": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "292": "B" }, O: { "164": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Flexible Box Layout Module" };
},{}],268:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB" }, D: { "1": "8 DB AB SB BB", "2": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "display: flow-root" };
},{}],269:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "2": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB", "16": "5 6 A" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "3 F s gB hB iB", "2": "dB eB fB", "16": "1" }, J: { "1": "C B" }, K: { "1": "D K y", "2": "B", "16": "5 6 A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "focusin & focusout events" };
},{}],270:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "H L M N O P Q R S T U V W u Y Z a b c", "164": "F I J C G E B A D X g" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H", "33": "Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q", "292": "L M N O P" }, E: { "1": "B A HB IB JB", "2": "7 C G E CB FB GB", "4": "F I J EB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d" }, G: { "1": "A ZB aB bB", "2": "G WB XB YB", "4": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "33": "hB iB" }, J: { "2": "C", "33": "B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "1": "I", "33": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS font-feature-settings" };
},{}],271:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S PB OB", "194": "T U V W u Y Z a b c" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u", "33": "Y Z a b" }, E: { "1": "B A HB IB JB", "2": "7 F I J CB EB FB", "33": "C G E GB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H KB LB MB NB QB y", "33": "L M N O" }, G: { "2": "3 7 9 UB VB WB", "33": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB", "33": "hB" }, J: { "2": "C", "33": "B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 font-kerning" };
},{}],272:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB", "194": "e f K h i j" }, D: { "1": "0 2 4 8 e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Font Loading" };
},{}],273:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "194": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y", "194": "Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "258": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "194": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS font-size-adjust" };
},{}],274:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB", "804": "0 2 4 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F", "676": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "676": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "676": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS font-smooth" };
},{}],275:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "4": "E B A" }, B: { "4": "D X g H L" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB", "194": "f K h i j k l m" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "1": "B A IB JB", "4": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "4": "H L M N O P Q R" }, G: { "1": "A aB bB", "4": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "4": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C", "4": "B" }, K: { "2": "5 6 B A D y", "4": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "4": "B A" }, O: { "4": "jB" }, P: { "1": "I", "4": "F" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 4, C: "Font unicode-range subsetting" };
},{}],276:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "130": "B A" }, B: { "130": "D X g H L" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "130": "F I J C G E B A D X g H L M N O P Q R S", "322": "T U V W u Y Z a b c" }, D: { "2": "F I J C G E B A D X g H", "130": "0 2 4 8 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A HB IB JB", "2": "7 C G E CB FB GB", "130": "F I J EB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "130": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "A ZB aB bB", "2": "7 G WB XB YB", "130": "3 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "130": "s hB iB" }, J: { "2": "C", "130": "B" }, K: { "2": "5 6 B A D y", "130": "K" }, L: { "130": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "130": "jB" }, P: { "130": "F I" }, Q: { "130": "kB" }, R: { "130": "lB" } }, B: 4, C: "CSS font-variant-alternates" };
},{}],277:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "132": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "2": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "2": "E KB" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "260": "7 9" }, H: { "2": "cB" }, I: { "1": "3 F s gB hB iB", "2": "dB", "4": "1 eB fB" }, J: { "1": "B", "4": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "@font-face Web fonts" };
},{}],278:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "16": "I" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Form attribute" };
},{}],279:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB", "16": "LB MB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "3 F s gB hB iB", "2": "dB eB fB", "16": "1" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 A D K y", "16": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Attributes for form submission" };
},{}],280:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E" }, E: { "1": "A IB JB", "2": "7 F CB", "132": "I J C G E B EB FB GB HB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "2": "E KB" }, G: { "1": "A bB", "2": "7", "132": "3 9 G UB VB WB XB YB ZB aB" }, H: { "516": "cB" }, I: { "1": "s iB", "2": "1 dB eB fB", "132": "3 F gB hB" }, J: { "1": "B", "132": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Form validation" };
},{}],281:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "4": "B A", "8": "J C G E" }, B: { "4": "D X g H L" }, C: { "4": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB PB OB" }, D: { "4": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "4": "F I J C G E B A EB FB GB HB IB JB", "8": "7 CB" }, F: { "1": "5 6 E A D KB LB MB NB QB y", "4": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "7", "4": "3 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "4": "s hB iB" }, J: { "2": "C", "4": "B" }, K: { "1": "5 6 B A D y", "4": "K" }, L: { "4": "8" }, M: { "4": "t" }, N: { "4": "B A" }, O: { "1": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 1, C: "HTML5 form features" };
},{}],282:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "548": "A" }, B: { "516": "D X g H L" }, C: { "2": "1 RB F I J C G E PB OB", "676": "B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p", "1700": "0 2 4 q r w x v z t s" }, D: { "2": "F I J C G E B A D X g", "676": "H L M N O", "804": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I CB", "676": "EB", "804": "J C G E B A FB GB HB IB JB" }, F: { "1": "y", "2": "5 6 E A D KB LB MB NB QB", "804": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "292": "B" }, K: { "2": "5 6 B A D y", "804": "K" }, L: { "804": "8" }, M: { "1700": "t" }, N: { "2": "B", "548": "A" }, O: { "804": "jB" }, P: { "804": "F I" }, Q: { "804": "kB" }, R: { "804": "lB" } }, B: 1, C: "Full Screen API" };
},{}],283:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P", "33": "Q R S T" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Gamepad API" };
},{}],284:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t PB OB", "8": "1 RB", "129": "2 4 s" }, D: { "1": "I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "4": "F", "129": "0 2 4 8 x v z t s DB AB SB BB" }, E: { "1": "I J C G E A EB FB GB HB IB JB", "8": "7 F CB", "129": "B" }, F: { "1": "5 6 A D L M N O P Q R S T U V W u Y Z a b c d e f K h NB QB y", "2": "E H KB", "8": "LB MB", "129": "i j k l m n o p q r" }, G: { "1": "3 7 9 G UB VB WB XB YB ZB", "129": "A aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F dB eB fB gB hB iB", "129": "s" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "8": "B" }, L: { "129": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F", "129": "I" }, Q: { "129": "kB" }, R: { "129": "lB" } }, B: 2, C: "Geolocation" };
},{}],285:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "644": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "RB", "260": "F I J C G E B A", "1156": "1", "1284": "PB", "1796": "OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "16": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "16": "E KB", "132": "LB MB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "132": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Element.getBoundingClientRect()" };
},{}],286:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "RB", "132": "1 PB OB" }, D: { "1": "0 2 4 8 A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "260": "F I J C G E B" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "260": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "260": "E KB LB MB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "260": "3 7 9" }, H: { "260": "cB" }, I: { "1": "3 F s gB hB iB", "260": "1 dB eB fB" }, J: { "1": "B", "260": "C" }, K: { "1": "5 6 A D K y", "260": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "getComputedStyle" };
},{}],287:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "getElementsByClassName" };
},{}],288:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "33": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P PB OB" }, D: { "1": "0 2 4 8 A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B", "33": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "crypto.getRandomValues()" };
},{}],289:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q PB OB" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, E: { "2": "7 F I J C CB EB FB GB", "129": "A IB JB", "194": "G E B HB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "2": "3 7 9 UB VB WB", "129": "A bB", "194": "G XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "navigator.hardwareConcurrency" };
},{}],290:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "8": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "8": "1 RB PB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "8": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "8": "E KB LB MB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "2": "dB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "8": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Hashchange event" };
},{}],291:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B CB EB FB GB HB IB", "129": "A JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB YB ZB aB bB", "129": "A" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "HEIF/ISO Base Media File Format" };
},{}],292:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "132": "A" }, B: { "132": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B CB EB FB GB HB IB", "513": "A JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "258": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "258": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "258": "I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "HEVC/H.265 video format" };
},{}],293:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "3 F s gB hB iB", "2": "1 dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 D K y", "2": "B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "hidden attribute" };
},{}],294:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O", "33": "P Q R S" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A YB ZB aB bB", "2": "3 7 9 UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "High Resolution Time API" };
},{}],295:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F CB", "4": "I EB" }, F: { "1": "5 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "6 E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "7 9", "4": "3" }, H: { "2": "cB" }, I: { "1": "3 s eB fB hB iB", "2": "1 F dB gB" }, J: { "1": "C B" }, K: { "1": "5 6 D K y", "2": "B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Session history management" };
},{}],296:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 UB", "129": "G A VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB", "257": "eB fB" }, J: { "1": "B", "16": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "516": "jB" }, P: { "1": "F I" }, Q: { "16": "kB" }, R: { "1": "lB" } }, B: 4, C: "HTML Media Capture" };
},{}],297:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G", "260": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "RB", "132": "1 PB OB", "260": "F I J C G E B A D X g H L M N O P" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I", "260": "J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "132": "7 F CB", "260": "I J EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "132": "E A KB LB MB NB", "260": "5 6 D QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "132": "7", "260": "3 9 UB VB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "132": "dB", "260": "1 3 F eB fB gB" }, J: { "260": "C B" }, K: { "1": "K", "132": "B", "260": "5 6 A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "260": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "New semantic elements" };
},{}],298:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "HTTP Live Streaming (HLS)" };
},{}],299:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "388": "A" }, B: { "257": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB", "257": "0 2 4 f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "257": "k l m n o p q r w x", "1281": "0 2 4 8 v z t s DB AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "772": "E B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y", "257": "u Y Z a b c d e f K", "1281": "h i j k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB", "257": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "257": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "257": "K" }, L: { "1281": "8" }, M: { "257": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "257": "F", "1281": "I" }, Q: { "1281": "kB" }, R: { "257": "lB" } }, B: 6, C: "HTTP/2 protocol" };
},{}],300:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L PB OB", "4": "M N O P Q R S T U V W" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "2": "7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "2": "dB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "sandbox attribute for iframes" };
},{}],301:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "66": "P Q R S T U V" }, E: { "2": "7 F I J G E B A CB EB FB HB IB JB", "130": "C GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB XB YB ZB aB bB", "130": "WB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "seamless attribute for iframes" };
},{}],302:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E B A" }, B: { "8": "D X g H L" }, C: { "1": "0 2 4 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "RB", "8": "1 F I J C G E B A D X g H L M N O P Q R S T PB OB" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X", "8": "g H L M N O" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 CB", "8": "F I EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E A KB LB MB NB", "8": "5 6 D QB y" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "7", "8": "3 9 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "8": "1 3 F dB eB fB gB" }, J: { "1": "B", "8": "C" }, K: { "1": "K", "2": "B A", "8": "5 6 D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "srcdoc attribute for iframes" };
},{}],303:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB", "194": "0 2 4 e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "322": "0 2 4 8 t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y", "322": "j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "322": "kB" }, R: { "1": "lB" } }, B: 5, C: "ImageCapture API" };
},{}],304:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "161": "A" }, B: { "161": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B", "161": "A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "Input Method Editor API" };
},{}],305:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "naturalWidth & naturalHeight image properties" };
},{}],306:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "8": "B A" }, B: { "8": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB", "8": "Z a", "200": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y", "322": "Z a b c d", "584": "e" }, E: { "2": "7 F I CB EB", "8": "J C G E B A FB GB HB IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L KB LB MB NB QB y", "1090": "M N O P Q", "2120": "R" }, G: { "2": "3 7 9 UB VB", "8": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "8": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "HTML Imports" };
},{}],307:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB", "16": "PB" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "indeterminate checkbox" };
},{}],308:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "B A D X g H", "36": "F I J C G E" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "B", "8": "F I J C G E", "33": "S", "36": "A D X g H L M N O P Q R" }, E: { "1": "B A IB JB", "8": "7 F I J C CB EB FB", "260": "G E GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E KB LB", "8": "5 6 A D MB NB QB y" }, G: { "1": "A aB bB", "8": "3 7 9 UB VB WB", "260": "G XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "8": "1 3 F dB eB fB gB" }, J: { "1": "B", "8": "C" }, K: { "1": "K", "2": "B", "8": "5 6 A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "IndexedDB" };
},{}],309:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m PB OB", "132": "n o p", "260": "q r w x" }, D: { "1": "8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q", "132": "r w x v", "260": "0 2 4 z t s" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y", "132": "e f K h", "260": "i j k l m n" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB", "16": "aB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "260": "s" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D y", "132": "K" }, L: { "260": "8" }, M: { "16": "t" }, N: { "2": "B A" }, O: { "16": "jB" }, P: { "16": "F", "260": "I" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 5, C: "IndexedDB 2.0" };
},{}],310:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "4": "TB", "132": "J C" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "36": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS inline-block" };
},{}],311:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.innerText" };
},{}],312:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B TB", "132": "A" }, B: { "132": "D X g H L" }, C: { "1": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB", "516": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "M N O P Q R S T U V", "2": "F I J C G E B A D X g H L", "132": "W u Y Z a b c d e f K h i j", "260": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J EB FB", "2": "7 F I CB", "2052": "C G E B A GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9", "1025": "G A UB VB WB XB YB ZB aB bB" }, H: { "1025": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2052": "B A" }, O: { "1025": "jB" }, P: { "1": "F I" }, Q: { "260": "kB" }, R: { "1": "lB" } }, B: 1, C: "autocomplete attribute: on & off values" };
},{}],313:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "5 6 A D M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E H L KB LB MB NB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Color input type" };
},{}],314:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "132": "D" }, C: { "1": "4 s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "1090": "0 2 t" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9", "260": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 dB eB fB", "514": "3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Date and time input types" };
},{}],315:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "132": "dB eB fB" }, J: { "1": "B", "132": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Email, telephone & URL input types" };
},{}],316:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "2561": "B A", "2692": "E" }, B: { "2561": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "16": "RB", "1537": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r OB", "1796": "1 PB" }, D: { "16": "F I J C G E B A D X g", "1025": "0 2 4 8 e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "1537": "H L M N O P Q R S T U V W u Y Z a b c d" }, E: { "16": "7 F I J CB", "1025": "C G E B A FB GB HB IB JB", "1537": "EB" }, F: { "1": "y", "16": "5 6 E A D KB LB MB NB", "260": "QB", "1025": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "1537": "H L M N O P Q" }, G: { "16": "3 7 9", "1025": "G A XB YB ZB aB bB", "1537": "UB VB WB" }, H: { "2": "cB" }, I: { "16": "dB eB", "1025": "s iB", "1537": "1 3 F fB gB hB" }, J: { "1025": "B", "1537": "C" }, K: { "1": "5 6 B A D y", "1025": "K" }, L: { "1025": "8" }, M: { "1537": "t" }, N: { "2561": "B A" }, O: { "1537": "jB" }, P: { "1025": "F I" }, Q: { "1025": "kB" }, R: { "1025": "lB" } }, B: 1, C: "input event" };
},{}],317:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F", "16": "I J C G Q R S T U", "132": "E B A D X g H L M N O P" }, E: { "2": "7 F I CB EB", "132": "J C G E B A FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "VB WB", "132": "G A XB YB ZB aB bB", "514": "3 7 9 UB" }, H: { "2": "cB" }, I: { "2": "dB eB fB", "260": "1 3 F gB", "514": "s hB iB" }, J: { "132": "B", "260": "C" }, K: { "2": "5 6 B A D y", "260": "K" }, L: { "260": "8" }, M: { "2": "t" }, N: { "514": "B", "1028": "A" }, O: { "2": "jB" }, P: { "260": "F I" }, Q: { "1": "kB" }, R: { "260": "lB" } }, B: 1, C: "accept attribute for file input" };
},{}],318:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB LB MB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "130": "cB" }, I: { "130": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "130": "5 6 B A D K y" }, L: { "132": "8" }, M: { "130": "t" }, N: { "2": "B A" }, O: { "130": "jB" }, P: { "130": "F", "132": "I" }, Q: { "1": "kB" }, R: { "132": "lB" } }, B: 1, C: "Multiple file selection" };
},{}],319:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L PB OB", "4": "M N O P", "194": "0 2 4 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "194": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "inputmode attribute" };
},{}],320:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB" }, D: { "1": "0 2 4 8 j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 1, C: "Minimum length attribute for input fields" };
},{}],321:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "129": "B A" }, B: { "129": "D X", "1025": "g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "513": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "388": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 dB eB fB", "388": "3 F s gB hB iB" }, J: { "2": "C", "388": "B" }, K: { "1": "5 6 B A D y", "388": "K" }, L: { "388": "8" }, M: { "641": "t" }, N: { "388": "B A" }, O: { "388": "jB" }, P: { "388": "F I" }, Q: { "1": "kB" }, R: { "388": "lB" } }, B: 1, C: "Number input type" };
},{}],322:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E" }, E: { "1": "A IB JB", "2": "7 F CB", "16": "I", "388": "J C G E B EB FB GB HB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "A bB", "16": "3 7 9", "388": "G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D y", "132": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Pattern attribute for input fields" };
},{}],323:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "132": "7 F CB" }, F: { "1": "5 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB", "132": "6 A" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 s dB eB fB hB iB", "4": "F gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "input placeholder attribute" };
},{}],324:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "3 s hB iB", "4": "1 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Range input type" };
},{}],325:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "129": "B A" }, B: { "129": "D X g H L" }, C: { "2": "1 RB PB OB", "129": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g Q R S T U", "129": "H L M N O P" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB", "16": "5 6 A" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "129": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "129": "1 3 F fB gB" }, J: { "1": "C", "129": "B" }, K: { "1": "D", "2": "B", "16": "5 6 A", "129": "K y" }, L: { "1": "8" }, M: { "129": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Search input type" };
},{}],326:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Element.insertAdjacentElement() & Element.insertAdjacentText()" };
},{}],327:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "16": "TB", "132": "J C G E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "16": "E KB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Element.insertAdjacentHTML()" };
},{}],328:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Internationalization API" };
},{}],329:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "194": "0 2 4 z t s" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "IntersectionObserver" };
},{}],330:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "RB", "932": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q", "545": "R S T U V W u Y Z a b c d e f K h i j k l m n o", "1537": "0 2 4 8 p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J CB EB", "516": "A JB", "548": "E B HB IB", "676": "C G FB GB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "513": "d", "545": "H L M N O P Q R S T U V W u Y Z a b", "1537": "c e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 UB VB", "548": "A YB ZB aB bB", "676": "G WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "545": "hB iB", "1537": "s" }, J: { "2": "C", "545": "B" }, K: { "2": "5 6 B A D y", "1537": "K" }, L: { "1537": "8" }, M: { "932": "t" }, N: { "2": "B A" }, O: { "545": "jB" }, P: { "545": "F", "1537": "I" }, Q: { "545": "kB" }, R: { "1537": "lB" } }, B: 5, C: "Intrinsic & Extrinsic Sizing" };
},{}],331:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F CB", "129": "I EB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "JPEG 2000 image format" };
},{}],332:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "JPEG XR image format" };
},{}],333:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C TB", "129": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "JSON parsing" };
},{}],334:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "16": "7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "132": "1 3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Improved kerning pairs & ligatures" };
},{}],335:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "16": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "16": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "16": "D" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "y", "2": "5 6 B A", "16": "D", "130": "K" }, L: { "1": "8" }, M: { "130": "t" }, N: { "130": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "KeyboardEvent.charCode" };
},{}],336:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k", "194": "l m n o p q" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u KB LB MB NB QB y", "194": "Y Z a b c d" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "194": "K" }, L: { "194": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "2": "kB" }, R: { "194": "lB" } }, B: 5, C: "KeyboardEvent.code" };
},{}],337:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A H L KB LB MB NB QB", "16": "D" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K y", "2": "5 6 B A", "16": "D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "KeyboardEvent.getModifierState()" };
},{}],338:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "260": "E B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB", "132": "S T U V W u" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "h i j k l m n o p q r y", "2": "5 6 E A H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB", "16": "D" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "y", "2": "5 6 B A K", "16": "D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "KeyboardEvent.key" };
},{}],339:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "C G E B A FB GB HB IB JB", "16": "7 J CB", "132": "F I EB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "16": "D", "132": "H L" }, G: { "1": "G A XB YB ZB aB bB", "16": "3 7 9", "132": "UB VB WB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "132": "1 3 F fB gB" }, J: { "132": "C B" }, K: { "1": "K y", "2": "5 6 B A", "16": "D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "KeyboardEvent.location" };
},{}],340:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "16": "I" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "16": "E KB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB", "16": "dB eB", "132": "hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D y", "132": "K" }, L: { "132": "8" }, M: { "132": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "2": "F", "132": "I" }, Q: { "1": "kB" }, R: { "132": "lB" } }, B: 7, C: "KeyboardEvent.which" };
},{}],341:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Resource Hints: Lazyload" };
},{}],342:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 n o p q r w x v z t s", "194": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N", "322": "O P Q R S T U V W u Y Z a b c d e f K h i j", "516": "k l m n o p q r" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "322": "H L M N O P Q R S T U V W", "516": "u Y Z a b c d e" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "I", "516": "F" }, Q: { "2": "kB" }, R: { "516": "lB" } }, B: 6, C: "let" };
},{}],343:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "129": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "257": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "129": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "513": "5 6 E A D KB LB MB NB QB y" }, G: { "1026": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1026": "cB" }, I: { "1": "1 3 F dB eB fB gB", "513": "s hB iB" }, J: { "1": "C", "1026": "B" }, K: { "1026": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1026": "B A" }, O: { "257": "jB" }, P: { "1": "I", "513": "F" }, Q: { "129": "kB" }, R: { "1": "lB" } }, B: 1, C: "PNG favicons" };
},{}],344:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB PB OB", "260": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "1025": "0 2 4 k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "516": "E B A HB IB JB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m KB LB MB NB QB y" }, G: { "130": "3 7 9 G UB VB WB XB", "516": "A YB ZB aB bB" }, H: { "130": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "130": "B" }, K: { "130": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "130": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "SVG favicons" };
},{}],345:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G TB", "132": "E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "16": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Resource Hints: dns-prefetch" };
},{}],346:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h PB OB", "129": "i" }, D: { "1": "0 2 4 8 p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "16": "t" }, N: { "2": "B A" }, O: { "16": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Resource Hints: preconnect" };
},{}],347:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "F s hB iB", "2": "1 3 dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Resource Hints: prefetch" };
},{}],348:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "Resource Hints: preload" };
},{}],349:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "8 F I J C G E B A D DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Resource Hints: prerender" };
},{}],350:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "16": "TB", "132": "J C G E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "132": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S" }, E: { "1": "B A IB JB", "132": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "5 6 E A D KB LB MB NB QB", "132": "y" }, G: { "1": "A aB bB", "132": "3 7 9 G UB VB WB XB YB ZB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "132": "1 3 F dB eB fB gB" }, J: { "132": "C B" }, K: { "1": "K", "16": "5 6 B A D", "132": "y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "132": "B" }, O: { "132": "jB" }, P: { "1": "I", "132": "F" }, Q: { "132": "kB" }, R: { "1": "lB" } }, B: 6, C: "localeCompare()" };
},{}],351:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "36": "E B A" }, B: { "1": "H L", "36": "D X g" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "36": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c OB" }, D: { "1": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "36": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c" }, E: { "1": "G E B A GB HB IB JB", "2": "7 F CB", "36": "I J C EB FB" }, F: { "1": "Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "6 E A KB LB MB NB", "36": "5 D H L M N O P QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "7", "36": "3 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB", "36": "1 3 F eB fB gB hB iB" }, J: { "36": "C B" }, K: { "1": "K", "2": "B A", "36": "5 6 D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "36": "B A" }, O: { "36": "jB" }, P: { "1": "I", "36": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "matches() DOM method" };
},{}],352:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB" }, D: { "1": "0 2 4 8 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "matchMedia" };
},{}],353:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "E B A TB", "8": "J C G" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "129": "1 RB PB OB" }, D: { "1": "T", "8": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A IB JB", "260": "7 F I J C G E CB EB FB GB HB" }, F: { "2": "E", "4": "5 6 A D KB LB MB NB QB y", "8": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "8": "3 7 9" }, H: { "8": "cB" }, I: { "8": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "B", "8": "C" }, K: { "8": "5 6 B A D K y" }, L: { "8": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "4": "jB" }, P: { "8": "F I" }, Q: { "8": "kB" }, R: { "8": "lB" } }, B: 2, C: "MathML" };
},{}],354:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "16": "TB", "900": "J C G E" }, B: { "1025": "D X g H L" }, C: { "1": "0 2 4 v z t s", "900": "1 RB PB OB", "1025": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "I CB", "900": "7 F" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E", "132": "5 6 A D KB LB MB NB QB y" }, G: { "1": "3 9 A UB VB WB YB ZB aB bB", "16": "7", "2052": "G XB" }, H: { "132": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "132": "5 6 B A D y", "4100": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "4100": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "maxlength attribute for input and textarea elements" };
},{}],355:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c", "2": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 A D H L M N O P Q R S T LB MB NB QB y", "2": "E U V W u Y Z a b c d e f K h i j k l m n o p q r KB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "16": "cB" }, I: { "1": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "16": "C B" }, K: { "1": "D K y", "16": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 1, C: "Media attribute" };
},{}],356:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "4 8 DB AB SB BB", "2": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "2": "7 F I J C G E B CB EB FB GB HB IB", "16": "A JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB y", "16": "q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Media Session API" };
},{}],357:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "193": "0 2 4 8 v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Media Capture from DOM Elements API" };
},{}],358:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p", "194": "q r" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c KB LB MB NB QB y", "194": "d e" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "MediaRecorder API" };
},{}],359:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "260": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB", "194": "U V W u Y Z a b c d e f K h i j k" }, D: { "1": "0 2 4 8 a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L", "33": "S T U V W u Y Z", "66": "M N O P Q R" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "I", "514": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "Media Source Extensions" };
},{}],360:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C PB OB", "132": "0 2 4 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "322": "r w x v", "578": "k l m n o p q", "2114": "0 2 4 8 z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y", "322": "e f K h", "2114": "i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1156": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2114": "kB" }, R: { "2": "lB" } }, B: 1, C: "Toolbar/context menu" };
},{}],361:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H PB OB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "meter element" };
},{}],362:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Web MIDI API" };
},{}],363:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "8": "J TB", "129": "C", "257": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS min/max-width/height" };
},{}],364:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "132": "F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "2": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "MP3 audio format" };
},{}],365:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P PB OB", "4": "Q R S T U V W u Y Z a b c d" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "2": "CB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "4": "1 3 F dB eB gB", "132": "fB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "260": "t" }, N: { "1": "B A" }, O: { "4": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "MPEG-4/H.264 video format" };
},{}],366:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Multiple backgrounds" };
},{}],367:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "132": "0 2 4 z t s", "164": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "132": "0 2 4 8 x v z t s DB AB SB BB", "420": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w" }, E: { "132": "E B A HB IB JB", "164": "C G GB", "420": "7 F I J CB EB FB" }, F: { "1": "5 6 D QB y", "2": "E A KB LB MB NB", "132": "K h i j k l m n o p q r", "420": "H L M N O P Q R S T U V W u Y Z a b c d e f" }, G: { "132": "A YB ZB aB bB", "164": "G WB XB", "420": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "132": "s", "420": "1 3 F dB eB fB gB hB iB" }, J: { "420": "C B" }, K: { "1": "5 6 D y", "2": "B A", "132": "K" }, L: { "132": "8" }, M: { "132": "t" }, N: { "1": "B A" }, O: { "420": "jB" }, P: { "132": "I", "420": "F" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 4, C: "CSS3 Multiple column layout" };
},{}],368:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "260": "E B A" }, B: { "260": "D X g H L" }, C: { "2": "1 RB F I PB OB", "260": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "16": "F I J C G E B A D X g", "132": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 CB", "132": "F I J C G E B A EB FB GB HB IB JB" }, F: { "1": "D QB y", "2": "E KB LB MB NB", "16": "5 6 A", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "7 9", "132": "3 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "dB eB", "132": "1 3 F s fB gB hB iB" }, J: { "132": "C B" }, K: { "1": "D y", "2": "B", "16": "5 6 A", "132": "K" }, L: { "132": "8" }, M: { "260": "t" }, N: { "260": "B A" }, O: { "132": "jB" }, P: { "132": "F I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 5, C: "Mutation events" };
},{}],369:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G TB", "8": "E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X PB OB" }, D: { "1": "0 2 4 8 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M", "33": "N O P Q R S T U V" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "33": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB", "33": "VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 dB eB fB", "8": "3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "8": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Mutation Observer" };
},{}],370:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "TB", "8": "J C" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "4": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Web Storage - name/value pairs" };
},{}],371:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J PB OB" }, D: { "1": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I", "33": "J C G E B A D" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A YB ZB aB bB", "2": "3 7 9 UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "3 F s gB hB iB", "2": "1 dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Navigation Timing API" };
},{}],372:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB hB iB", "132": "1 3 F eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "132": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 7, C: "Network Information API" };
},{}],373:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "TB", "644": "E B A", "2308": "J C G" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "16": "7 F I J CB", "1668": "EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "16": "5 6 E A D KB LB MB NB", "132": "QB" }, G: { "1": "G A WB XB YB ZB aB bB", "16": "3 7 9 UB VB" }, H: { "16": "cB" }, I: { "1": "s hB iB", "16": "1 dB eB fB", "1668": "3 F gB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.contains()" };
},{}],374:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "TB", "132": "E B A", "260": "J C G" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "5 6 E A KB LB MB NB", "132": "D QB y" }, G: { "1": "G A VB WB XB YB ZB aB bB", "16": "3 7 9 UB" }, H: { "16": "cB" }, I: { "1": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.parentElement" };
},{}],375:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F", "36": "I J C G E B A D X g H L M N O P Q" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "36": "s hB iB" }, J: { "1": "B", "2": "C" }, K: { "2": "5 6 B A D y", "36": "K" }, L: { "258": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "36": "F", "258": "I" }, Q: { "2": "kB" }, R: { "258": "lB" } }, B: 1, C: "Web Notifications" };
},{}],376:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "L", "2": "D X g H" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB" }, D: { "1": "0 2 4 8 a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z" }, E: { "1": "B A IB JB", "2": "7 F I J C CB EB FB", "132": "G E GB HB" }, F: { "1": "O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E H L M N KB LB MB", "33": "5 6 A D NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 UB VB WB", "132": "G XB YB ZB" }, H: { "33": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "2": "C B" }, K: { "1": "K", "2": "B", "33": "5 6 A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 object-fit/object-position" };
},{}],377:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "f K h i j k l m n o p q r w", "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f", "2": "5 6 E A D H L M N O P Q R K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F", "2": "I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Object.observe data binding" };
},{}],378:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "130": "B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Object RTC (ORTC) API for WebRTC" };
},{}],379:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "E TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "4": "1", "8": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "8": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB", "8": "LB MB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Offline web applications" };
},{}],380:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Ogg Vorbis audio format" };
},{}],381:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "8": "E B A" }, B: { "8": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Ogg/Theora video format" };
},{}],382:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M PB OB" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H", "16": "L M N O" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "16": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "16": "D" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Reversed attribute of ordered lists" };
},{}],383:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "L", "2": "D X g H" }, C: { "1": "0 2 4 x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w PB OB" }, D: { "1": "2 4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "\"once\" event listener option" };
},{}],384:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C TB", "260": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s PB OB", "2": "1 RB", "516": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, D: { "1": "0 2 4 8 g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB", "4": "y" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "16": "7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "B", "132": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "132": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Online/offline status" };
},{}],385:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Opus" };
},{}],386:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "260": "G", "388": "E B A" }, B: { "1": "H L", "388": "D X g" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB", "129": "y", "260": "5 6 E A KB LB MB NB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "D K y", "260": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "388": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS outline properties" };
},{}],387:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q PB OB" }, D: { "1": "4 8 DB AB SB BB", "2": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "16": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "16": "s" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D y", "16": "K" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "String.prototype.padStart(), String.prototype.padEnd()" };
},{}],388:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "PageTransitionEvent" };
},{}],389:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E PB OB", "33": "B A D X g H L M" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X", "33": "g H L M N O P Q R S T U V W u Y Z a b" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB", "33": "H L M N O" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "33": "hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "I", "33": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Page Visibility" };
},{}],390:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "L", "2": "D X g H" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Passive event listeners" };
},{}],391:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X", "322": "g" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t PB OB", "4162": "2 4 s" }, D: { "1": "AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "194": "0 2 4 t s DB", "1090": "8" }, E: { "2": "7 F I J C G E CB EB FB GB HB", "514": "B A IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y", "194": "j k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB YB ZB", "514": "A aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2049": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "194": "kB" }, R: { "2": "lB" } }, B: 5, C: "Payment Request API" };
},{}],392:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o PB OB" }, D: { "1": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Permissions API" };
},{}],393:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c PB OB", "578": "d e f K" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f", "194": "K" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y", "322": "T" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Picture element" };
},{}],394:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "RB", "194": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "194": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Ping attribute" };
},{}],395:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "C G E B A", "2": "TB", "8": "J" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "PNG alpha transparency" };
},{}],396:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "CSS pointer-events (for HTML)" };
},{}],397:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E TB", "164": "B" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I PB OB", "8": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "328": "0 2 4 k l m n o p q r w x v z t s" }, D: { "1": "2 4 8 s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q", "8": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v", "584": "0 z t" }, E: { "2": "7 F I J CB EB", "8": "C G E B A FB GB HB IB JB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "8": "H L M N O P Q R S T U V W u Y Z a b c d e f K h", "584": "i j k" }, G: { "8": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "8": "1 3 F dB eB fB gB hB iB" }, J: { "8": "C B" }, K: { "2": "B", "8": "5 6 A D K y" }, L: { "1": "8" }, M: { "328": "t" }, N: { "1": "A", "36": "B" }, O: { "8": "jB" }, P: { "2": "I", "8": "F" }, Q: { "584": "kB" }, R: { "2": "lB" } }, B: 2, C: "Pointer events" };
},{}],398:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X PB OB", "33": "g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H", "33": "R S T U V W u Y Z a b c d e f", "66": "L M N O P Q" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "PointerLock API" };
},{}],399:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB" }, G: { "2": "3 7 9 UB VB", "132": "G A WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "progress element" };
},{}],400:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "8": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "4": "W u", "8": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "b", "8": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a" }, E: { "1": "G E B A GB HB IB JB", "8": "7 F I J C CB EB FB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "4": "O", "8": "5 6 E A D H L M N KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "8": "3 7 9 UB VB WB" }, H: { "8": "cB" }, I: { "1": "s iB", "8": "1 3 F dB eB fB gB hB" }, J: { "8": "C B" }, K: { "1": "K", "8": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Promises" };
},{}],401:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "Proximity API" };
},{}],402:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N h i j k l m n o p q r", "66": "O P Q R S T U V W u Y Z a b c d e f K" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D U V W u Y Z a b c d e KB LB MB NB QB y", "66": "H L M N O P Q R S T" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Proxy object" };
},{}],403:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O KB LB MB NB QB y", "4": "S", "16": "P Q R T" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Public Key Pinning" };
},{}],404:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m PB OB", "257": "0 2 4 n p q r w x v t s", "1281": "o z" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m", "257": "0 2 4 8 x v z t s DB AB SB BB", "388": "n o p q r w" }, E: { "2": "7 F I J C G E CB EB FB GB", "514": "B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f KB LB MB NB QB y", "16": "K h i j k", "257": "l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 5, C: "Push API" };
},{}],405:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C", "132": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "8": "E KB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "querySelector/querySelectorAll" };
},{}],406:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "16": "1 RB PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E KB", "132": "5 6 A D LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "16": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "132": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "257": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "readonly attribute of input and textarea elements" };
},{}],407:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB" }, D: { "1": "AB SB BB", "2": "F I J C G E B A D X g H L M N O P", "260": "0 2 4 8 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB" }, E: { "2": "7 F I J C CB EB FB", "132": "G E B A GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 UB VB WB", "132": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Referrer Policy" };
},{}],408:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "2": "F I J C G E B A D", "129": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A KB LB MB NB", "129": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "129": "B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Custom protocol handling" };
},{}],409:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "rel=noopener" };
},{}],410:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "132": "A" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB" }, D: { "1": "0 2 4 8 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Link type \"noreferrer\"" };
},{}],411:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "132": "0 2 4 8 x v z t s DB AB SB BB" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f KB LB MB NB QB y", "132": "K h i j k l m n o p q r" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "132": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "132": "I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "relList (DOMTokenList)" };
},{}],412:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G TB", "132": "E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "1": "3 9 G A VB WB XB YB ZB aB bB", "2": "7", "260": "UB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "rem (root em) units" };
},{}],413:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "A D X g H L M N O P Q R", "164": "F I J C G E B" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E", "33": "R S", "164": "N O P Q", "420": "B A D X g H L M" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "33": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB", "33": "VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "requestAnimationFrame" };
},{}],414:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "0 2 4 8 q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "requestIdleCallback" };
},{}],415:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "194": "2 4 8 t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j KB LB MB NB QB y", "194": "k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "194": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Resize Observer" };
},{}],416:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB", "194": "a b c d" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Resource Timing" };
},{}],417:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m", "194": "n o p" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z KB LB MB NB QB y", "194": "a b c" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Rest parameters" };
},{}],418:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "33": "R S T U V W u Y Z a b c d e f K h i j k l m" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R", "33": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "2": "5 6 E A D H L M KB LB MB NB QB y", "33": "N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "33": "s" }, J: { "2": "C", "130": "B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 5, C: "WebRTC Peer-to-peer connections" };
},{}],419:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "4": "J C G E B A TB" }, B: { "4": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "8": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "4": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F" }, E: { "4": "I J C G E B A EB FB GB HB IB JB", "8": "7 F CB" }, F: { "4": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "8": "5 6 E A D KB LB MB NB QB y" }, G: { "4": "G A UB VB WB XB YB ZB aB bB", "8": "3 7 9" }, H: { "8": "cB" }, I: { "4": "1 3 F s gB hB iB", "8": "dB eB fB" }, J: { "4": "B", "8": "C" }, K: { "4": "K", "8": "5 6 B A D y" }, L: { "4": "8" }, M: { "1": "t" }, N: { "4": "B A" }, O: { "4": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 1, C: "Ruby annotation" };
},{}],420:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "'SameSite' cookie attribute" };
},{}],421:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "36": "A" }, B: { "36": "D X g H L" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M PB OB", "36": "N O P Q R S T U V W u Y Z a b c d e f K h i j k l m" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B", "36": "A" }, O: { "1": "jB" }, P: { "1": "I", "16": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Screen Orientation" };
},{}],422:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "132": "I" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "async attribute for external scripts" };
},{}],423:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "132": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "257": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "defer attribute for external scripts" };
},{}],424:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "132": "G E B A" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "132": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB" }, D: { "132": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I CB", "132": "J C G E B A EB FB GB HB IB JB" }, F: { "2": "E KB LB MB NB", "16": "5 6 A", "132": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y" }, G: { "16": "3 7 9", "132": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "dB eB", "132": "1 3 F s fB gB hB iB" }, J: { "132": "C B" }, K: { "132": "5 6 B A D K y" }, L: { "132": "8" }, M: { "132": "t" }, N: { "132": "B A" }, O: { "132": "jB" }, P: { "132": "F I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 5, C: "scrollIntoView" };
},{}],425:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Element.scrollIntoViewIfNeeded()" };
},{}],426:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "2": "8 AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "SDCH Accept-Encoding/Content-Encoding" };
},{}],427:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "16": "TB", "260": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 z t s", "132": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l PB OB", "2180": "m n o p q r w x v" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "132": "5 6 E A D KB LB MB NB QB y" }, G: { "16": "3", "132": "7 9", "516": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "16": "1 F dB eB fB gB", "1025": "3" }, J: { "1": "B", "16": "C" }, K: { "1": "K", "16": "5 6 B A D", "132": "y" }, L: { "1": "8" }, M: { "132": "t" }, N: { "1": "A", "16": "B" }, O: { "1025": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Selection API" };
},{}],428:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "322": "H L" }, C: { "1": "0 2 4 n p q r w x v t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "194": "c d e f K h i j k l m", "513": "o z" }, D: { "1": "0 2 4 8 o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i", "4": "j k l m n" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y", "4": "W u Y Z a" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "4": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "4": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "4": "jB" }, P: { "1": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 5, C: "Service Workers" };
},{}],429:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Efficient Script Yielding: setImmediate()" };
},{}],430:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "2": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "260": "dB" }, J: { "1": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "16": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "SHA-2 SSL certificates" };
},{}],431:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "194": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T", "33": "U V W u Y Z a b c d" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "33": "hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "33": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Shadow DOM v0" };
},{}],432:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, E: { "2": "7 F I J C G E CB EB FB GB HB", "132": "B A IB JB" }, F: { "1": "j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB YB ZB", "132": "A aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "4": "I" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 5, C: "Shadow DOM v1" };
},{}],433:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J EB", "2": "7 F C G E B A CB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB LB MB" }, G: { "1": "UB VB", "2": "3 7 9 G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D y", "2": "K", "16": "B" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F", "2": "I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Shared Web Workers" };
},{}],434:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J TB", "132": "C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Server Name Indication" };
},{}],435:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "2": "D X g H L" }, C: { "1": "X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "2": "0 1 2 4 RB F I J C G E B A D v z t s PB OB" }, D: { "1": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "2": "0 2 4 8 v z t s DB AB SB BB" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i l n y", "2": "5 6 E A D j k m o p q r KB LB MB NB QB" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "1 3 F gB hB iB", "2": "s dB eB fB" }, J: { "2": "C B" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F", "2": "I" }, Q: { "2": "kB" }, R: { "16": "lB" } }, B: 7, C: "SPDY protocol" };
},{}],436:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "322": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T", "164": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y", "164": "W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "164": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 7, C: "Speech Recognition API" };
},{}],437:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB", "194": "a b c d e f K h i j k l m n o p q r" }, D: { "1": "0 c d e f K h i j k l m n o p q r w x v z t", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b", "257": "2 4 8 s DB AB SB BB" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 7, C: "Speech Synthesis API" };
},{}],438:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "4": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "4": "cB" }, I: { "4": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "B", "4": "C" }, K: { "4": "5 6 B A D K y" }, L: { "4": "8" }, M: { "4": "t" }, N: { "4": "B A" }, O: { "4": "jB" }, P: { "4": "F I" }, Q: { "1": "kB" }, R: { "4": "lB" } }, B: 1, C: "Spellcheck attribute" };
},{}],439:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Web SQL Database" };
},{}],440:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "260": "D", "514": "X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a PB OB", "194": "b c d e f K" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c", "260": "d e f K" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C CB EB FB", "260": "G GB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P KB LB MB NB QB y", "260": "Q R S T" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 UB VB WB", "260": "G XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Srcset and sizes attributes" };
},{}],441:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "16": "D" }, G: { "1": "G A VB WB XB YB ZB aB bB", "16": "3 7 9 UB" }, H: { "16": "cB" }, I: { "1": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Event.stopImmediatePropagation()" };
},{}],442:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L PB OB", "33": "0 2 4 M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P", "164": "0 2 4 8 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "A", "2": "7 F I J C G E B CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A H L M KB LB MB NB QB", "164": "D N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "164": "s" }, J: { "2": "C", "164": "B" }, K: { "2": "5 6 B A", "164": "D K y" }, L: { "164": "8" }, M: { "33": "t" }, N: { "2": "B A" }, O: { "164": "jB" }, P: { "16": "F", "164": "I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 4, C: "getUserMedia/Stream API" };
},{}],443:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "129": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Strict Transport Security" };
},{}],444:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t", "2": "1 4 RB F I J C G E B A D X g H L M N O P s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O K h i j k l m n o p q r w x v z t s DB AB SB BB", "194": "P Q R S T U V W u Y Z a b c d e f" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Scoped CSS" };
},{}],445:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l PB OB" }, D: { "1": "0 2 4 8 o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Subresource Integrity" };
},{}],446:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "260": "F I J C G E B A D X g H L M N O P Q R S" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "CB", "132": "7 F" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "132": "7 9" }, H: { "260": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K", "260": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "SVG in CSS backgrounds" };
},{}],447:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F", "4": "I J C" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "SVG filters" };
},{}],448:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "E B A TB", "8": "J C G" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K", "2": "0 2 4 8 v z t s DB AB SB BB", "130": "h i j k l m n o p q r w x" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "2": "CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y", "2": "K h i j k l m n o p q r", "130": "U V W u Y Z a b c d e f" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "258": "cB" }, I: { "1": "1 3 F gB hB iB", "2": "s dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "130": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F", "130": "I" }, Q: { "1": "kB" }, R: { "130": "lB" } }, B: 7, C: "SVG fonts" };
},{}],449:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e", "132": "f K h i j k l m n o p q r w" }, E: { "2": "7 F I J C E B A CB EB FB HB IB JB", "132": "G GB" }, F: { "1": "K h i j k l m n o p q r y", "2": "H L M N O P Q R", "4": "5 6 A D LB MB NB QB", "16": "E KB", "132": "S T U V W u Y Z a b c d e f" }, G: { "2": "3 7 9 A UB VB WB YB ZB aB bB", "132": "G XB" }, H: { "1": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C", "132": "B" }, K: { "1": "K y", "4": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "132": "jB" }, P: { "1": "I", "132": "F" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 2, C: "SVG fragment identifiers" };
},{}],450:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "388": "E B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB", "4": "1" }, D: { "4": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "4": "F I J C G E B A EB FB GB HB IB JB" }, F: { "4": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "4": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "4": "s hB iB" }, J: { "1": "B", "2": "C" }, K: { "4": "5 6 B A D K y" }, L: { "4": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 2, C: "SVG effects for HTML" };
},{}],451:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G", "129": "E B A" }, B: { "129": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB PB OB" }, D: { "1": "0 2 4 8 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F I J" }, E: { "1": "E B A HB IB JB", "8": "7 F I CB", "129": "J C G EB FB GB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 A NB", "8": "E KB LB MB" }, G: { "1": "A YB ZB aB bB", "8": "3 7 9", "129": "G UB VB WB XB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "129": "1 3 F gB" }, J: { "1": "B", "129": "C" }, K: { "1": "D K y", "8": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Inline SVG in HTML5" };
},{}],452:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, E: { "1": "E B A HB IB JB", "2": "CB", "4": "7", "132": "F I J C G EB FB GB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "132": "3 7 9 G UB VB WB XB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "132": "1 3 F gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "SVG in HTML img element" };
},{}],453:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E B A" }, B: { "8": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB PB OB" }, D: { "1": "I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n", "4": "F", "257": "0 2 4 8 o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A FB GB HB IB JB", "8": "7 CB", "132": "F I EB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a KB LB MB NB QB y", "257": "b c d e f K h i j k l m n o p q r" }, G: { "1": "G A VB WB XB YB ZB aB bB", "132": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "257": "kB" }, R: { "1": "lB" } }, B: 2, C: "SVG SMIL animation" };
},{}],454:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G", "257": "E B A" }, B: { "257": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "4": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "4": "CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "132": "1 3 F gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "257": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "SVG (basic support)" };
},{}],455:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "C G E B A", "16": "J TB" }, B: { "1": "D X g H L" }, C: { "16": "1 RB PB OB", "129": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "16": "7 F I CB", "257": "J C G E B A EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "769": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "16": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "16": "8" }, M: { "16": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "2": "kB" }, R: { "16": "lB" } }, B: 1, C: "tabindex global attribute" };
},{}],456:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "ES6 Template Literals (Template Strings)" };
},{}],457:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D", "388": "X g H L" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U", "132": "V W u Y Z a b c d" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C CB EB", "388": "G GB", "514": "FB" }, F: { "1": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 UB VB WB", "388": "G XB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "HTML templates" };
},{}],458:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G B A TB", "16": "E" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "16": "F I" }, D: { "2": "0 2 4 8 F I J C G E B X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "A D" }, E: { "2": "7 F J CB EB", "16": "I C G E B A FB GB HB IB JB" }, F: { "2": "5 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "6" }, G: { "2": "3 7 9 UB VB", "16": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB gB hB iB", "16": "fB" }, J: { "2": "B", "16": "C" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Test feature - updated" };
},{}],459:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I PB OB", "1028": "0 2 4 f K h i j k l m n o p q r w x v z t s", "1060": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, D: { "1": "4 8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U", "226": "0 2 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "2": "7 F I J C CB EB FB", "804": "G E B A HB IB JB", "1316": "GB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y", "226": "e f K h i j k l m" }, G: { "2": "3 7 9 UB VB WB", "292": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "text-decoration styling" };
},{}],460:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n PB OB", "322": "o" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T", "164": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "G E B A GB HB IB JB", "2": "7 F I J CB EB", "164": "C FB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "164": "s hB iB" }, J: { "2": "C", "164": "B" }, K: { "2": "5 6 B A D y", "164": "K" }, L: { "164": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "164": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 4, C: "text-emphasis styling" };
},{}],461:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "2": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB F I J PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "33": "E KB LB MB NB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "K y", "33": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Text-overflow" };
},{}],462:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "2 4 8 t s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "258": "V" }, E: { "2": "7 F I J C G E B A CB FB GB HB IB JB", "258": "EB" }, F: { "1": "m o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l n KB LB MB NB QB y" }, G: { "2": "3 7 9", "33": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "33": "t" }, N: { "161": "B A" }, O: { "33": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS text-size-adjust" };
},{}],463:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "161": "H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q PB OB", "161": "0 2 4 w x v z t s", "450": "r" }, D: { "33": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "A JB", "33": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "33": "3 9 G A UB VB WB XB YB ZB aB bB", "36": "7" }, H: { "2": "cB" }, I: { "2": "1", "33": "3 F s dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "161": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS text-stroke and text-fill" };
},{}],464:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.textContent" };
},{}],465:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB", "132": "O" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 1, C: "TextEncoder & TextDecoder" };
},{}],466:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C TB", "66": "G E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB", "66": "S" }, D: { "1": "0 2 4 8 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "66": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "TLS 1.1" };
},{}],467:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C TB", "66": "G E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S PB OB", "66": "T U V" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E H L KB", "66": "5 6 A D LB MB NB QB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "66": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "TLS 1.2" };
},{}],468:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB", "66": "v" }, D: { "1": "4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "66": "2 t" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y", "66": "l" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "16": "s" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D K y" }, L: { "16": "8" }, M: { "16": "t" }, N: { "2": "B", "16": "A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 6, C: "TLS 1.3" };
},{}],469:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "257": "H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t PB OB", "16": "2 4 s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h", "16": "0 2 4 i j k l m n o p q r w x v z t s", "194": "8 DB AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "16": "E B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y", "16": "Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB", "16": "A YB ZB aB bB" }, H: { "16": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "16": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "16": "K" }, L: { "16": "8" }, M: { "16": "t" }, N: { "2": "B", "16": "A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 6, C: "Token Binding" };
},{}],470:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "8": "B A" }, B: { "578": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T z t s", "2": "1 RB PB OB", "4": "F I J C G E B A D X g H L M", "194": "U V W u Y Z a b c d e f K h i j k l m n o p q r w x v" }, D: { "1": "0 2 4 8 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B", "260": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Touch events" };
},{}],471:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G", "129": "B A", "161": "E" }, B: { "129": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "33": "F I J C G E B A D X g H PB OB" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "1": "E B A HB IB JB", "33": "7 F I J C G CB EB FB GB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB", "33": "5 6 A D H L M N O P Q R MB NB QB" }, G: { "1": "A YB ZB aB bB", "33": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "33": "1 3 F dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "33": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 2D Transforms" };
},{}],472:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E PB OB", "33": "B A D X g H" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A", "33": "D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "2": "7 CB", "33": "F I J C G EB FB GB", "257": "E B A HB IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R" }, G: { "1": "A YB ZB aB bB", "33": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB fB", "33": "1 3 F gB hB iB" }, J: { "33": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "33": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 3D Transforms" };
},{}],473:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "2": "E KB" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "2": "7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "2": "dB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "TTF/OTF - TrueType and OpenType font support" };
},{}],474:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E TB", "132": "B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB", "260": "EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "7 9", "260": "3" }, H: { "1": "cB" }, I: { "1": "3 F s gB hB iB", "2": "1 dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Typed Arrays" };
},{}],475:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K", "130": "h i j" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "j l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i k KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "FIDO U2F API" };
},{}],476:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k PB OB" }, D: { "1": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Upgrade Insecure Requests" };
},{}],477:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U PB OB" }, D: { "1": "0 2 4 8 b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R", "130": "S T U V W u Y Z a" }, E: { "1": "G E B A GB HB IB JB", "2": "7 F I J CB EB FB", "130": "C" }, F: { "1": "O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "130": "H L M N" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB", "130": "WB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB", "130": "hB" }, J: { "2": "C", "130": "B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "URL API" };
},{}],478:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "132": "Y Z a b c d e f K h i j k l m" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "URLSearchParams" };
},{}],479:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F CB", "132": "I EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 D K y", "2": "6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "ECMAScript 5 Strict Mode" };
},{}],480:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "33": "B A" }, B: { "33": "D X g H L" }, C: { "33": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "2 4 8 t s DB AB SB BB", "33": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, E: { "33": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, G: { "33": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "33": "1 3 F dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "1": "8" }, M: { "33": "t" }, N: { "33": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS user-select: none" };
},{}],481:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "User Timing API" };
},{}],482:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B PB OB", "33": "A D X g H" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Vibration API" };
},{}],483:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "260": "F I J C G E B A D X g H L M N O PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "132": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Video element" };
},{}],484:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Video Tracks" };
},{}],485:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E", "260": "B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O", "260": "P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "260": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB", "516": "WB", "772": "VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Viewport units: vw, vh, vmin, vmax" };
},{}],486:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "4": "G E B A" }, B: { "4": "D X g H L" }, C: { "4": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "4": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "4": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "E", "4": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "4": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "4": "cB" }, I: { "2": "1 3 F dB eB fB gB", "4": "s hB iB" }, J: { "2": "C B" }, K: { "4": "5 6 B A D K y" }, L: { "4": "8" }, M: { "4": "t" }, N: { "4": "B A" }, O: { "2": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 2, C: "WAI-ARIA Accessibility features" };
},{}],487:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "578": "H L" }, C: { "1": "0 2 4 t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB", "194": "q r w x v", "1025": "z" }, D: { "1": "4 8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "322": "0 2 v z t s" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y", "322": "h i j k l m" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "322": "kB" }, R: { "2": "lB" } }, B: 6, C: "WebAssembly" };
},{}],488:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "16": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Wav audio format" };
},{}],489:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C TB", "2": "G E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "wbr (word break opportunity) element" };
},{}],490:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "516": "0 2 4 q r w x v z t s", "580": "c d e f K h i j k l m n o p" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e", "132": "f K h", "260": "0 2 4 8 i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R KB LB MB NB QB y", "132": "S T U", "260": "V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "260": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "260": "K" }, L: { "260": "8" }, M: { "516": "t" }, N: { "2": "B A" }, O: { "260": "jB" }, P: { "260": "F I" }, Q: { "260": "kB" }, R: { "260": "lB" } }, B: 5, C: "Web Animations API" };
},{}],491:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Web App Manifest" };
},{}],492:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n", "194": "o p q r w x v z", "706": "0 2 t", "1025": "4 8 s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y", "450": "f K h i", "706": "j k l", "1025": "m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "1025": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1025": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "706": "kB" }, R: { "2": "lB" } }, B: 7, C: "Web Bluetooth" };
},{}],493:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 F I J C G E B A D X g H L M U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t", "129": "2 4 8 s DB AB SB BB", "258": "N O P Q R S T" }, E: { "2": "7 F I J C G E B A CB EB GB HB IB JB", "16": "FB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB", "129": "s", "514": "iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "642": "8" }, M: { "514": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "642": "I" }, Q: { "2": "kB" }, R: { "16": "lB" } }, B: 5, C: "Web Share Api" };
},{}],494:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E B", "129": "A" }, B: { "129": "D X g H L" }, C: { "1": "0 2 4 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "129": "F I J C G E B A D X g H L M N O P Q R S" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C", "129": "G E B A D X g H L M N O P Q R S T U V W u Y Z a b" }, E: { "1": "G E B A HB IB JB", "2": "7 F I CB", "129": "J C EB FB GB" }, F: { "1": "O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A KB LB MB NB QB", "129": "D H L M N y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B", "129": "A" }, O: { "129": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "WebGL - 3D Canvas graphics" };
},{}],495:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB", "194": "l m n", "450": "U V W u Y Z a b c d e f K h i j k", "2242": "o p q r w x" }, D: { "1": "4 8 s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "578": "0 2 m n o p q r w x v z t" }, E: { "2": "7 F I J C G E B CB EB FB GB HB", "1090": "A IB JB" }, F: { "1": "m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "578": "kB" }, R: { "2": "lB" } }, B: 6, C: "WebGL 2.0" };
},{}],496:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "8": "E B A" }, B: { "4": "g H L", "8": "D X" }, C: { "1": "0 2 4 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "4": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I", "4": "J C G E B A D X g H L M N O P Q R S T" }, E: { "2": "CB", "8": "7 F I J C G E B A EB FB GB HB IB JB" }, F: { "1": "L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E KB LB MB", "4": "5 6 A D H NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB", "4": "1 3 F fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "4": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "1": "I", "4": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "WebM video format" };
},{}],497:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB PB OB", "8": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I", "8": "J C G", "132": "E B A D X g H L M N O P Q R" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB MB", "8": "A NB", "132": "5 6 QB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "3 s hB iB", "2": "1 dB eB fB", "132": "F gB" }, J: { "2": "C B" }, K: { "1": "5 6 D K y", "2": "B", "132": "A" }, L: { "1": "8" }, M: { "8": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "WebP image format" };
},{}],498:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "132": "F I", "292": "J C G E B" }, D: { "1": "0 2 4 8 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g", "260": "H" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F CB", "132": "I EB", "260": "J FB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB MB NB", "132": "5 6 A D QB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "7 9", "132": "3 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "129": "C" }, K: { "1": "K y", "2": "B", "132": "5 6 A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Web Sockets" };
},{}],499:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "513": "H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "194": "2 4 t s" }, D: { "2": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "322": "4 8 DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2049": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1025": "F", "1028": "I" }, Q: { "2": "kB" }, R: { "322": "lB" } }, B: 7, C: "WebVR API" };
},{}],500:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S PB OB", "66": "T U V W u Y Z", "129": "0 2 4 a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "WebVTT - Web Video Text Tracks" };
},{}],501:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "TB", "8": "J C G E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "8": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB", "8": "LB MB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s dB hB iB", "2": "1 3 F eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "8": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Web Workers" };
},{}],502:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "194": "Y Z a b c d e" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS will-change property" };
},{}],503:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 dB eB fB gB", "130": "F" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "WOFF - Web Open Font Format" };
},{}],504:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h PB OB" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "2": "7 F I J C G E CB EB FB GB HB", "132": "B A IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "WOFF 2.0 - Web Open Font Format" };
},{}],505:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 n o p q r w x v z t s DB AB SB BB", "4": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m" }, E: { "1": "E B A HB IB JB", "4": "7 F I J C G CB EB FB GB" }, F: { "1": "a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "4": "H L M N O P Q R S T U V W u Y Z" }, G: { "1": "A YB ZB aB bB", "4": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "4": "1 3 F dB eB fB gB hB iB" }, J: { "4": "C B" }, K: { "2": "5 6 B A D y", "4": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "4": "jB" }, P: { "1": "F I" }, Q: { "4": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 word-break" };
},{}],506:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "4": "J C G E B A TB" }, B: { "4": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB", "4": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F I J C G E B A D X g H L M N O P Q R" }, E: { "1": "C G E B A FB GB HB IB JB", "4": "7 F I J CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB", "4": "5 6 A D MB NB QB" }, G: { "1": "G A WB XB YB ZB aB bB", "4": "3 7 9 UB VB" }, H: { "4": "cB" }, I: { "1": "s hB iB", "4": "1 3 F dB eB fB gB" }, J: { "1": "B", "4": "C" }, K: { "1": "K", "4": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "4": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 Overflow-wrap" };
},{}],507:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "132": "G E", "260": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "4": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Cross-document messaging" };
},{}],508:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "4": "F I J C G E B A D X g H L M", "16": "1 RB PB OB" }, D: { "4": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "4": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "4": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "5 6 E A KB LB MB NB" }, G: { "4": "G A WB XB YB ZB aB bB", "16": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "4": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "4": "C B" }, K: { "4": "K y", "16": "5 6 B A D" }, L: { "4": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "4": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 6, C: "X-Frame-Options HTTP header" };
},{}],509:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "260": "B A", "388": "J C G E", "900": "F I PB OB" }, D: { "1": "0 2 4 8 a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J", "132": "Y Z", "388": "C G E B A D X g H L M N O P Q R S T U V W u" }, E: { "1": "G E B A GB HB IB JB", "2": "7 F CB", "132": "C FB", "388": "I J EB" }, F: { "1": "D N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "132": "H L M" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9", "132": "WB", "388": "UB VB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "dB eB fB", "388": "hB", "900": "1 3 F gB" }, J: { "132": "B", "388": "C" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "XMLHttpRequest advanced features" };
},{}],510:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 1, C: "XHTML served as application/xhtml+xml" };
},{}],511:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "E B A TB", "4": "J C G" }, B: { "2": "D X g H L" }, C: { "8": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "8": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "8": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "8": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "8": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "8": "cB" }, I: { "8": "1 3 F s dB eB fB gB hB iB" }, J: { "8": "C B" }, K: { "8": "5 6 B A D K y" }, L: { "8": "8" }, M: { "8": "t" }, N: { "2": "B A" }, O: { "8": "jB" }, P: { "8": "F I" }, Q: { "8": "kB" }, R: { "8": "lB" } }, B: 7, C: "XHTML+SMIL animation" };
},{}],512:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "132": "E", "260": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "132": "A", "260": "1 RB F I J C PB OB", "516": "G E B" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "G E B A GB HB IB JB", "132": "7 F I J C CB EB FB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E KB", "132": "5 6 A D H L LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "132": "3 7 9 UB VB WB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "132": "1 3 F dB eB fB gB" }, J: { "132": "C B" }, K: { "1": "K", "16": "B", "132": "5 6 A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "DOM Parsing and Serialization" };
},{}],513:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var browsers = require('../../data/browsers');
var browserVersions = require('../../data/browserVersions');
var agentsData = require('../../data/agents');
function unpackBrowserVersions(versionsData) {
return Object.keys(versionsData).reduce(function (usage, version) {
usage[browserVersions[version]] = versionsData[version];
return usage;
}, {});
}
var agents = Object.keys(agentsData).reduce(function (map, key) {
var versionsData = agentsData[key];
map[browsers[key]] = Object.keys(versionsData).reduce(function (data, entry) {
if (entry === 'A') {
data.usage_global = unpackBrowserVersions(versionsData[entry]);
} else if (entry === 'C') {
data.versions = versionsData[entry].reduce(function (list, version) {
if (version === '') {
list.push(null);
} else {
list.push(browserVersions[version]);
}
return list;
}, []);
} else if (entry === 'D') {
data.prefix_exceptions = unpackBrowserVersions(versionsData[entry]);
} else if (entry === 'E') {
data.browser = versionsData[entry];
} else {
data.prefix = versionsData[entry];
}
return data;
}, {});
return map;
}, {});
var statuses = {
1: "ls",
2: "rec",
3: "pr",
4: "cr",
5: "wd",
6: "other",
7: "unoff"
};
var supported = {
y: 1 << 0,
n: 1 << 1,
a: 1 << 2,
p: 1 << 3,
u: 1 << 4,
x: 1 << 5,
d: 1 << 6
};
function unpackSupport(cipher) {
var stats = Object.keys(supported).reduce(function (list, support) {
if (cipher & supported[support]) {
list.push(support);
}
return list;
}, []);
var notes = cipher >> 7;
var notesArray = [];
while (notes) {
var note = Math.floor(Math.log2(notes)) + 1;
notesArray.unshift("#" + note);
notes -= Math.pow(2, note - 1);
}
return stats.concat(notesArray).join(' ');
}
function unpackFeature(packed) {
var unpacked = { status: statuses[packed.B], title: packed.C };
unpacked.stats = Object.keys(packed.A).reduce(function (browserStats, key) {
var browser = packed.A[key];
browserStats[browsers[key]] = Object.keys(browser).reduce(function (stats, support) {
var packedVersions = browser[support].split(' ');
var unpacked = unpackSupport(support);
packedVersions.forEach(function (v) {
return stats[browserVersions[v]] = unpacked;
});
return stats;
}, {});
return browserStats;
}, {});
return unpacked;
}
var features = require('../../data/features');
function unpackRegion(packed) {
return Object.keys(packed).reduce(function (list, browser) {
var data = packed[browser];
list[browsers[browser]] = Object.keys(data).reduce(function (memo, key) {
var stats = data[key];
if (key === '_') {
stats.split(' ').forEach(function (version) {
return memo[version] = null;
});
} else {
memo[key] = stats;
}
return memo;
}, {});
return list;
}, {});
}
exports.agents = agents;
exports.feature = unpackFeature;
exports.features = features;
exports.region = unpackRegion;
},{"../../data/agents":67,"../../data/browserVersions":68,"../../data/browsers":69,"../../data/features":70}],514:[function(require,module,exports){
'use strict';
/* MIT license */
var cssKeywords = require('color-name');
// NOTE: conversions should only return primitive values (i.e. arrays, or
// values that give correct `typeof` results).
// do not use box values types (i.e. Number(), String(), etc.)
var reverseKeywords = {};
for (var key in cssKeywords) {
if (cssKeywords.hasOwnProperty(key)) {
reverseKeywords[cssKeywords[key]] = key;
}
}
var convert = module.exports = {
rgb: { channels: 3, labels: 'rgb' },
hsl: { channels: 3, labels: 'hsl' },
hsv: { channels: 3, labels: 'hsv' },
hwb: { channels: 3, labels: 'hwb' },
cmyk: { channels: 4, labels: 'cmyk' },
xyz: { channels: 3, labels: 'xyz' },
lab: { channels: 3, labels: 'lab' },
lch: { channels: 3, labels: 'lch' },
hex: { channels: 1, labels: ['hex'] },
keyword: { channels: 1, labels: ['keyword'] },
ansi16: { channels: 1, labels: ['ansi16'] },
ansi256: { channels: 1, labels: ['ansi256'] },
hcg: { channels: 3, labels: ['h', 'c', 'g'] },
apple: { channels: 3, labels: ['r16', 'g16', 'b16'] },
gray: { channels: 1, labels: ['gray'] }
};
// hide .channels and .labels properties
for (var model in convert) {
if (convert.hasOwnProperty(model)) {
if (!('channels' in convert[model])) {
throw new Error('missing channels property: ' + model);
}
if (!('labels' in convert[model])) {
throw new Error('missing channel labels property: ' + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error('channel and label counts mismatch: ' + model);
}
var channels = convert[model].channels;
var labels = convert[model].labels;
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], 'channels', { value: channels });
Object.defineProperty(convert[model], 'labels', { value: labels });
}
}
convert.rgb.hsl = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var min = Math.min(r, g, b);
var max = Math.max(r, g, b);
var delta = max - min;
var h;
var s;
var l;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function (rgb) {
var r = rgb[0];
var g = rgb[1];
var b = rgb[2];
var min = Math.min(r, g, b);
var max = Math.max(r, g, b);
var delta = max - min;
var h;
var s;
var v;
if (max === 0) {
s = 0;
} else {
s = delta / max * 1000 / 10;
}
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
v = max / 255 * 1000 / 10;
return [h, s, v];
};
convert.rgb.hwb = function (rgb) {
var r = rgb[0];
var g = rgb[1];
var b = rgb[2];
var h = convert.rgb.hsl(rgb)[0];
var w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var c;
var m;
var y;
var k;
k = Math.min(1 - r, 1 - g, 1 - b);
c = (1 - r - k) / (1 - k) || 0;
m = (1 - g - k) / (1 - k) || 0;
y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
/**
* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
* */
function comparativeDistance(x, y) {
return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
}
convert.rgb.keyword = function (rgb) {
var reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
var currentClosestDistance = Infinity;
var currentClosestKeyword;
for (var keyword in cssKeywords) {
if (cssKeywords.hasOwnProperty(keyword)) {
var value = cssKeywords[keyword];
// Compute comparative distance
var distance = comparativeDistance(rgb, value);
// Check if its less, if so set as closest
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function (keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
// assume sRGB
r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function (rgb) {
var xyz = convert.rgb.xyz(rgb);
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var l;
var a;
var b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
l = 116 * y - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function (hsl) {
var h = hsl[0] / 360;
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var t1;
var t2;
var t3;
var rgb;
var val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
t1 = 2 * l - t2;
rgb = [0, 0, 0];
for (var i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function (hsl) {
var h = hsl[0];
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var smin = s;
var lmin = Math.max(l, 0.01);
var sv;
var v;
l *= 2;
s *= l <= 1 ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
v = (l + s) / 2;
sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function (hsv) {
var h = hsv[0] / 60;
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var hi = Math.floor(h) % 6;
var f = h - Math.floor(h);
var p = 255 * v * (1 - s);
var q = 255 * v * (1 - s * f);
var t = 255 * v * (1 - s * (1 - f));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function (hsv) {
var h = hsv[0];
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var vmin = Math.max(v, 0.01);
var lmin;
var sl;
var l;
l = (2 - s) * v;
lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= lmin <= 1 ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
convert.hwb.rgb = function (hwb) {
var h = hwb[0] / 360;
var wh = hwb[1] / 100;
var bl = hwb[2] / 100;
var ratio = wh + bl;
var i;
var v;
var f;
var n;
// wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
i = Math.floor(6 * h);
v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) !== 0) {
f = 1 - f;
}
n = wh + f * (v - wh); // linear interpolation
var r;
var g;
var b;
switch (i) {
default:
case 6:
case 0:
r = v;g = n;b = wh;break;
case 1:
r = n;g = v;b = wh;break;
case 2:
r = wh;g = v;b = n;break;
case 3:
r = wh;g = n;b = v;break;
case 4:
r = n;g = wh;b = v;break;
case 5:
r = v;g = wh;b = n;break;
}
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function (cmyk) {
var c = cmyk[0] / 100;
var m = cmyk[1] / 100;
var y = cmyk[2] / 100;
var k = cmyk[3] / 100;
var r;
var g;
var b;
r = 1 - Math.min(1, c * (1 - k) + k);
g = 1 - Math.min(1, m * (1 - k) + k);
b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function (xyz) {
var x = xyz[0] / 100;
var y = xyz[1] / 100;
var z = xyz[2] / 100;
var r;
var g;
var b;
r = x * 3.2406 + y * -1.5372 + z * -0.4986;
g = x * -0.9689 + y * 1.8758 + z * 0.0415;
b = x * 0.0557 + y * -0.2040 + z * 1.0570;
// assume sRGB
r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function (xyz) {
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var l;
var a;
var b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
l = 116 * y - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function (lab) {
var l = lab[0];
var a = lab[1];
var b = lab[2];
var x;
var y;
var z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
var y2 = Math.pow(y, 3);
var x2 = Math.pow(x, 3);
var z2 = Math.pow(z, 3);
y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function (lab) {
var l = lab[0];
var a = lab[1];
var b = lab[2];
var hr;
var h;
var c;
hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function (lch) {
var l = lch[0];
var c = lch[1];
var h = lch[2];
var a;
var b;
var hr;
hr = h / 360 * 2 * Math.PI;
a = c * Math.cos(hr);
b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function (args) {
var r = args[0];
var g = args[1];
var b = args[2];
var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function (args) {
// optimization here; we already know the value and don't need to get
// it converted for us.
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function (args) {
var r = args[0];
var g = args[1];
var b = args[2];
// we use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round((r - 8) / 247 * 24) + 232;
}
var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function (args) {
var color = args % 10;
// handle greyscale
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
var mult = (~~(args > 50) + 1) * 0.5;
var r = (color & 1) * mult * 255;
var g = (color >> 1 & 1) * mult * 255;
var b = (color >> 2 & 1) * mult * 255;
return [r, g, b];
};
convert.ansi256.rgb = function (args) {
// handle greyscale
if (args >= 232) {
var c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
var rem;
var r = Math.floor(args / 36) / 5 * 255;
var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
var b = rem % 6 / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function (args) {
var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
var string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.hex.rgb = function (args) {
var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
var colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split('').map(function (char) {
return char + char;
}).join('');
}
var integer = parseInt(colorString, 16);
var r = integer >> 16 & 0xFF;
var g = integer >> 8 & 0xFF;
var b = integer & 0xFF;
return [r, g, b];
};
convert.rgb.hcg = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var max = Math.max(Math.max(r, g), b);
var min = Math.min(Math.min(r, g), b);
var chroma = max - min;
var grayscale;
var hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else if (max === r) {
hue = (g - b) / chroma % 6;
} else if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma + 4;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function (hsl) {
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var c = 1;
var f = 0;
if (l < 0.5) {
c = 2.0 * s * l;
} else {
c = 2.0 * s * (1.0 - l);
}
if (c < 1.0) {
f = (l - 0.5 * c) / (1.0 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function (hsv) {
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var c = s * v;
var f = 0;
if (c < 1.0) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function (hcg) {
var h = hcg[0] / 360;
var c = hcg[1] / 100;
var g = hcg[2] / 100;
if (c === 0.0) {
return [g * 255, g * 255, g * 255];
}
var pure = [0, 0, 0];
var hi = h % 1 * 6;
var v = hi % 1;
var w = 1 - v;
var mg = 0;
switch (Math.floor(hi)) {
case 0:
pure[0] = 1;pure[1] = v;pure[2] = 0;break;
case 1:
pure[0] = w;pure[1] = 1;pure[2] = 0;break;
case 2:
pure[0] = 0;pure[1] = 1;pure[2] = v;break;
case 3:
pure[0] = 0;pure[1] = w;pure[2] = 1;break;
case 4:
pure[0] = v;pure[1] = 0;pure[2] = 1;break;
default:
pure[0] = 1;pure[1] = 0;pure[2] = w;
}
mg = (1.0 - c) * g;
return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
};
convert.hcg.hsv = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var v = c + g * (1.0 - c);
var f = 0;
if (v > 0.0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var l = g * (1.0 - c) + 0.5 * c;
var s = 0;
if (l > 0.0 && l < 0.5) {
s = c / (2 * l);
} else if (l >= 0.5 && l < 1.0) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var v = c + g * (1.0 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function (hwb) {
var w = hwb[1] / 100;
var b = hwb[2] / 100;
var v = 1 - b;
var c = v - w;
var g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function (apple) {
return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
};
convert.rgb.apple = function (rgb) {
return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
};
convert.gray.rgb = function (args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = convert.gray.hsv = function (args) {
return [0, 0, args[0]];
};
convert.gray.hwb = function (gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function (gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function (gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function (gray) {
var val = Math.round(gray[0] / 100 * 255) & 0xFF;
var integer = (val << 16) + (val << 8) + val;
var string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.rgb.gray = function (rgb) {
var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};
},{"color-name":517}],515:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var conversions = require('./conversions');
var route = require('./route');
var convert = {};
var models = Object.keys(conversions);
function wrapRaw(fn) {
var wrappedFn = function wrappedFn(args) {
if (args === undefined || args === null) {
return args;
}
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments);
}
return fn(args);
};
// preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
var wrappedFn = function wrappedFn(args) {
if (args === undefined || args === null) {
return args;
}
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments);
}
var result = fn(args);
// we're assuming the result is an array here.
// see notice in conversions.js; don't use box types
// in conversion functions.
if ((typeof result === 'undefined' ? 'undefined' : _typeof(result)) === 'object') {
for (var len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
// preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach(function (fromModel) {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], 'channels', { value: conversions[fromModel].channels });
Object.defineProperty(convert[fromModel], 'labels', { value: conversions[fromModel].labels });
var routes = route(fromModel);
var routeModels = Object.keys(routes);
routeModels.forEach(function (toModel) {
var fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
module.exports = convert;
},{"./conversions":514,"./route":516}],516:[function(require,module,exports){
'use strict';
var conversions = require('./conversions');
/*
this function routes a model to all other models.
all functions that are routed have a property `.conversion` attached
to the returned synthetic function. This property is an array
of strings, each with the steps in between the 'from' and 'to'
color models (inclusive).
conversions that are not possible simply are not included.
*/
// https://jsperf.com/object-keys-vs-for-in-with-closure/3
var models = Object.keys(conversions);
function buildGraph() {
var graph = {};
for (var len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
// https://en.wikipedia.org/wiki/Breadth-first_search
function deriveBFS(fromModel) {
var graph = buildGraph();
var queue = [fromModel]; // unshift -> queue -> pop
graph[fromModel].distance = 0;
while (queue.length) {
var current = queue.pop();
var adjacents = Object.keys(conversions[current]);
for (var len = adjacents.length, i = 0; i < len; i++) {
var adjacent = adjacents[i];
var node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current].distance + 1;
node.parent = current;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function (args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
var path = [graph[toModel].parent, toModel];
var fn = conversions[graph[toModel].parent][toModel];
var cur = graph[toModel].parent;
while (graph[cur].parent) {
path.unshift(graph[cur].parent);
fn = link(conversions[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path;
return fn;
}
module.exports = function (fromModel) {
var graph = deriveBFS(fromModel);
var conversion = {};
var models = Object.keys(graph);
for (var len = models.length, i = 0; i < len; i++) {
var toModel = models[i];
var node = graph[toModel];
if (node.parent === null) {
// no possible conversion, or this node is the source model.
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};
},{"./conversions":514}],517:[function(require,module,exports){
"use strict";
module.exports = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
},{}],518:[function(require,module,exports){
"use strict";
module.exports = {
"1.7": "58",
"1.6": "56",
"1.3": "52",
"1.4": "53",
"1.5": "54",
"1.2": "51",
"1.1": "50",
"1.0": "49",
"0.37": "49",
"0.36": "47",
"0.35": "45",
"0.34": "45",
"0.33": "45",
"0.32": "45",
"0.31": "44",
"0.30": "44",
"0.29": "43",
"0.28": "43",
"0.27": "42",
"0.26": "42",
"0.25": "42",
"0.24": "41",
"0.23": "41",
"0.22": "41",
"0.21": "40",
"0.20": "39"
};
},{}],519:[function(require,module,exports){
'use strict';
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};
},{}],520:[function(require,module,exports){
"use strict";
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & (1 << -nBits) - 1;
s >>= -nBits;
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : (s ? -1 : 1) * Infinity;
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128;
};
},{}],521:[function(require,module,exports){
'use strict';
module.exports = {
wrap: wrapRange,
limit: limitRange,
validate: validateRange,
test: testRange,
curry: curry,
name: name
};
function wrapRange(min, max, value) {
var maxLessMin = max - min;
return ((value - min) % maxLessMin + maxLessMin) % maxLessMin + min;
}
function limitRange(min, max, value) {
return Math.max(min, Math.min(max, value));
}
function validateRange(min, max, value, minExclusive, maxExclusive) {
if (!testRange(min, max, value, minExclusive, maxExclusive)) {
throw new Error(value + ' is outside of range [' + min + ',' + max + ')');
}
return value;
}
function testRange(min, max, value, minExclusive, maxExclusive) {
return !(value < min || value > max || maxExclusive && value === max || minExclusive && value === min);
}
function name(min, max, minExcl, maxExcl) {
return (minExcl ? '(' : '[') + min + ',' + max + (maxExcl ? ')' : ']');
}
function curry(min, max, minExclusive, maxExclusive) {
var boundNameFn = name.bind(null, min, max, minExclusive, maxExclusive);
return {
wrap: wrapRange.bind(null, min, max),
limit: limitRange.bind(null, min, max),
validate: function validate(value) {
return validateRange(min, max, value, minExclusive, maxExclusive);
},
test: function test(value) {
return testRange(min, max, value, minExclusive, maxExclusive);
},
toString: boundNameFn,
name: boundNameFn
};
}
},{}],522:[function(require,module,exports){
'use strict';
var abs = Math.abs;
var round = Math.round;
function almostEq(a, b) {
return abs(a - b) <= 9.5367432e-7;
}
//最大公约数 Greatest Common Divisor
function GCD(a, b) {
if (almostEq(b, 0)) return a;
return GCD(b, a % b);
}
function findPrecision(n) {
var e = 1;
while (!almostEq(round(n * e) / e, n)) {
e *= 10;
}
return e;
}
function num2fraction(num) {
if (num === 0 || num === '0') return '0';
if (typeof num === 'string') {
num = parseFloat(num);
}
var precision = findPrecision(num); //精确度
var number = num * precision;
var gcd = abs(GCD(number, precision));
//分子
var numerator = number / gcd;
//分母
var denominator = precision / gcd;
//分数
return round(numerator) + '/' + round(denominator);
}
module.exports = num2fraction;
},{}],523:[function(require,module,exports){
(function (process){
'use strict';
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function splitPath(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function () {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = i >= 0 ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function (p) {
return !!p;
}), !resolvedAbsolute).join('/');
return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function (path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function (p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function (path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function () {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function (p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function (from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function (path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function (path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function (path) {
return splitPath(path)[3];
};
function filter(xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) {
return str.substr(start, len);
} : function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
};
}).call(this,require('_process'))
},{"_process":557}],524:[function(require,module,exports){
'use strict';
var parse = require('./parse');
var walk = require('./walk');
var stringify = require('./stringify');
function ValueParser(value) {
if (this instanceof ValueParser) {
this.nodes = parse(value);
return this;
}
return new ValueParser(value);
}
ValueParser.prototype.toString = function () {
return Array.isArray(this.nodes) ? stringify(this.nodes) : '';
};
ValueParser.prototype.walk = function (cb, bubble) {
walk(this.nodes, cb, bubble);
return this;
};
ValueParser.unit = require('./unit');
ValueParser.walk = walk;
ValueParser.stringify = stringify;
module.exports = ValueParser;
},{"./parse":525,"./stringify":526,"./unit":527,"./walk":528}],525:[function(require,module,exports){
'use strict';
var openParentheses = '('.charCodeAt(0);
var closeParentheses = ')'.charCodeAt(0);
var singleQuote = '\''.charCodeAt(0);
var doubleQuote = '"'.charCodeAt(0);
var backslash = '\\'.charCodeAt(0);
var slash = '/'.charCodeAt(0);
var comma = ','.charCodeAt(0);
var colon = ':'.charCodeAt(0);
var star = '*'.charCodeAt(0);
module.exports = function (input) {
var tokens = [];
var value = input;
var next, quote, prev, token, escape, escapePos, whitespacePos;
var pos = 0;
var code = value.charCodeAt(pos);
var max = value.length;
var stack = [{ nodes: tokens }];
var balanced = 0;
var parent;
var name = '';
var before = '';
var after = '';
while (pos < max) {
// Whitespaces
if (code <= 32) {
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = value.slice(pos, next);
prev = tokens[tokens.length - 1];
if (code === closeParentheses && balanced) {
after = token;
} else if (prev && prev.type === 'div') {
prev.after = token;
} else if (code === comma || code === colon || code === slash && value.charCodeAt(next + 1) !== star) {
before = token;
} else {
tokens.push({
type: 'space',
sourceIndex: pos,
value: token
});
}
pos = next;
// Quotes
} else if (code === singleQuote || code === doubleQuote) {
next = pos;
quote = code === singleQuote ? '\'' : '"';
token = {
type: 'string',
sourceIndex: pos,
quote: quote
};
do {
escape = false;
next = value.indexOf(quote, next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += quote;
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
token.value = value.slice(pos + 1, next);
tokens.push(token);
pos = next + 1;
code = value.charCodeAt(pos);
// Comments
} else if (code === slash && value.charCodeAt(pos + 1) === star) {
token = {
type: 'comment',
sourceIndex: pos
};
next = value.indexOf('*/', pos);
if (next === -1) {
token.unclosed = true;
next = value.length;
}
token.value = value.slice(pos + 2, next);
tokens.push(token);
pos = next + 2;
code = value.charCodeAt(pos);
// Dividers
} else if (code === slash || code === comma || code === colon) {
token = value[pos];
tokens.push({
type: 'div',
sourceIndex: pos - before.length,
value: token,
before: before,
after: ''
});
before = '';
pos += 1;
code = value.charCodeAt(pos);
// Open parentheses
} else if (openParentheses === code) {
// Whitespaces after open parentheses
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = {
type: 'function',
sourceIndex: pos - name.length,
value: name,
before: value.slice(pos + 1, next)
};
pos = next;
if (name === 'url' && code !== singleQuote && code !== doubleQuote) {
next -= 1;
do {
escape = false;
next = value.indexOf(')', next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += ')';
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
// Whitespaces before closed
whitespacePos = next;
do {
whitespacePos -= 1;
code = value.charCodeAt(whitespacePos);
} while (code <= 32);
if (pos !== whitespacePos + 1) {
token.nodes = [{
type: 'word',
sourceIndex: pos,
value: value.slice(pos, whitespacePos + 1)
}];
} else {
token.nodes = [];
}
if (token.unclosed && whitespacePos + 1 !== next) {
token.after = '';
token.nodes.push({
type: 'space',
sourceIndex: whitespacePos + 1,
value: value.slice(whitespacePos + 1, next)
});
} else {
token.after = value.slice(whitespacePos + 1, next);
}
pos = next + 1;
code = value.charCodeAt(pos);
tokens.push(token);
} else {
balanced += 1;
token.after = '';
tokens.push(token);
stack.push(token);
tokens = token.nodes = [];
parent = token;
}
name = '';
// Close parentheses
} else if (closeParentheses === code && balanced) {
pos += 1;
code = value.charCodeAt(pos);
parent.after = after;
after = '';
balanced -= 1;
stack.pop();
parent = stack[balanced];
tokens = parent.nodes;
// Words
} else {
next = pos;
do {
if (code === backslash) {
next += 1;
}
next += 1;
code = value.charCodeAt(next);
} while (next < max && !(code <= 32 || code === singleQuote || code === doubleQuote || code === comma || code === colon || code === slash || code === openParentheses || code === closeParentheses && balanced));
token = value.slice(pos, next);
if (openParentheses === code) {
name = token;
} else {
tokens.push({
type: 'word',
sourceIndex: pos,
value: token
});
}
pos = next;
}
}
for (pos = stack.length - 1; pos; pos -= 1) {
stack[pos].unclosed = true;
}
return stack[0].nodes;
};
},{}],526:[function(require,module,exports){
'use strict';
function stringifyNode(node, custom) {
var type = node.type;
var value = node.value;
var buf;
var customResult;
if (custom && (customResult = custom(node)) !== undefined) {
return customResult;
} else if (type === 'word' || type === 'space') {
return value;
} else if (type === 'string') {
buf = node.quote || '';
return buf + value + (node.unclosed ? '' : buf);
} else if (type === 'comment') {
return '/*' + value + (node.unclosed ? '' : '*/');
} else if (type === 'div') {
return (node.before || '') + value + (node.after || '');
} else if (Array.isArray(node.nodes)) {
buf = stringify(node.nodes);
if (type !== 'function') {
return buf;
}
return value + '(' + (node.before || '') + buf + (node.after || '') + (node.unclosed ? '' : ')');
}
return value;
}
function stringify(nodes, custom) {
var result, i;
if (Array.isArray(nodes)) {
result = '';
for (i = nodes.length - 1; ~i; i -= 1) {
result = stringifyNode(nodes[i], custom) + result;
}
return result;
}
return stringifyNode(nodes, custom);
}
module.exports = stringify;
},{}],527:[function(require,module,exports){
'use strict';
var minus = '-'.charCodeAt(0);
var plus = '+'.charCodeAt(0);
var dot = '.'.charCodeAt(0);
module.exports = function (value) {
var pos = 0;
var length = value.length;
var dotted = false;
var containsNumber = false;
var code;
var number = '';
while (pos < length) {
code = value.charCodeAt(pos);
if (code >= 48 && code <= 57) {
number += value[pos];
containsNumber = true;
} else if (code === dot) {
if (dotted) {
break;
}
dotted = true;
number += value[pos];
} else if (code === plus || code === minus) {
if (pos !== 0) {
break;
}
number += value[pos];
} else {
break;
}
pos += 1;
}
return containsNumber ? {
number: number,
unit: value.slice(pos)
} : false;
};
},{}],528:[function(require,module,exports){
'use strict';
module.exports = function walk(nodes, cb, bubble) {
var i, max, node, result;
for (i = 0, max = nodes.length; i < max; i += 1) {
node = nodes[i];
if (!bubble) {
result = cb(node, i, nodes);
}
if (result !== false && node.type === 'function' && Array.isArray(node.nodes)) {
walk(node.nodes, cb, bubble);
}
if (bubble) {
cb(node, i, nodes);
}
}
};
},{}],529:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents an at-rule.
*
* If it’s followed in the CSS by a {} block, this node will have
* a nodes property representing its children.
*
* @extends Container
*
* @example
* const root = postcss.parse('@charset "UTF-8"; @media print {}');
*
* const charset = root.first;
* charset.type //=> 'atrule'
* charset.nodes //=> undefined
*
* const media = root.last;
* media.nodes //=> []
*/
var AtRule = function (_Container) {
_inherits(AtRule, _Container);
function AtRule(defaults) {
_classCallCheck(this, AtRule);
var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));
_this.type = 'atrule';
return _this;
}
AtRule.prototype.append = function append() {
var _Container$prototype$;
if (!this.nodes) this.nodes = [];
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
};
AtRule.prototype.prepend = function prepend() {
var _Container$prototype$2;
if (!this.nodes) this.nodes = [];
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
};
/**
* @memberof AtRule#
* @member {string} name - the at-rule’s name immediately follows the `@`
*
* @example
* const root = postcss.parse('@media print {}');
* media.name //=> 'media'
* const media = root.first;
*/
/**
* @memberof AtRule#
* @member {string} params - the at-rule’s parameters, the values
* that follow the at-rule’s name but precede
* any {} block
*
* @example
* const root = postcss.parse('@media print, screen {}');
* const media = root.first;
* media.params //=> 'print, screen'
*/
/**
* @memberof AtRule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
*
* PostCSS cleans at-rule parameters from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse(' @media\nprint {\n}')
* root.first.first.raws //=> { before: ' ',
* // between: ' ',
* // afterName: '\n',
* // after: '\n' }
*/
return AtRule;
}(_container2.default);
exports.default = AtRule;
module.exports = exports['default'];
},{"./container":531}],530:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*
* @extends Node
*/
var Comment = function (_Node) {
_inherits(Comment, _Node);
function Comment(defaults) {
_classCallCheck(this, Comment);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'comment';
return _this;
}
/**
* @memberof Comment#
* @member {string} text - the comment’s text
*/
/**
* @memberof Comment#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text.
*/
return Comment;
}(_node2.default);
exports.default = Comment;
module.exports = exports['default'];
},{"./node":538}],531:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _comment = require('./comment');
var _comment2 = _interopRequireDefault(_comment);
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function cleanSource(nodes) {
return nodes.map(function (i) {
if (i.nodes) i.nodes = cleanSource(i.nodes);
delete i.source;
return i;
});
}
/**
* The {@link Root}, {@link AtRule}, and {@link Rule} container nodes
* inherit some common methods to help work with their children.
*
* Note that all containers can store any content. If you write a rule inside
* a rule, PostCSS will parse it.
*
* @extends Node
* @abstract
*/
var Container = function (_Node) {
_inherits(Container, _Node);
function Container() {
_classCallCheck(this, Container);
return _possibleConstructorReturn(this, _Node.apply(this, arguments));
}
Container.prototype.push = function push(child) {
child.parent = this;
this.nodes.push(child);
return this;
};
/**
* Iterates through the container’s immediate children,
* calling `callback` for each child.
*
* Returning `false` in the callback will break iteration.
*
* This method only iterates through the container’s immediate children.
* If you need to recursively iterate through all the container’s descendant
* nodes, use {@link Container#walk}.
*
* Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
* if you are mutating the array of child nodes during iteration.
* PostCSS will adjust the current index to match the mutations.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const root = postcss.parse('a { color: black; z-index: 1 }');
* const rule = root.first;
*
* for ( let decl of rule.nodes ) {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Cycle will be infinite, because cloneBefore moves the current node
* // to the next index
* }
*
* rule.each(decl => {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Will be executed only for color and z-index
* });
*/
Container.prototype.each = function each(callback) {
if (!this.lastEach) this.lastEach = 0;
if (!this.indexes) this.indexes = {};
this.lastEach += 1;
var id = this.lastEach;
this.indexes[id] = 0;
if (!this.nodes) return undefined;
var index = void 0,
result = void 0;
while (this.indexes[id] < this.nodes.length) {
index = this.indexes[id];
result = callback(this.nodes[index], index);
if (result === false) break;
this.indexes[id] += 1;
}
delete this.indexes[id];
return result;
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each node.
*
* Like container.each(), this method is safe to use
* if you are mutating arrays during iteration.
*
* If you only need to iterate through the container’s immediate children,
* use {@link Container#each}.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walk(node => {
* // Traverses all descendant nodes.
* });
*/
Container.prototype.walk = function walk(callback) {
return this.each(function (child, i) {
var result = callback(child, i);
if (result !== false && child.walk) {
result = child.walk(callback);
}
return result;
});
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each declaration node.
*
* If you pass a filter, iteration will only happen over declarations
* with matching properties.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [prop] - string or regular expression
* to filter declarations by property name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkDecls(decl => {
* checkPropertySupport(decl.prop);
* });
*
* root.walkDecls('border-radius', decl => {
* decl.remove();
* });
*
* root.walkDecls(/^background/, decl => {
* decl.value = takeFirstColorFromGradient(decl.value);
* });
*/
Container.prototype.walkDecls = function walkDecls(prop, callback) {
if (!callback) {
callback = prop;
return this.walk(function (child, i) {
if (child.type === 'decl') {
return callback(child, i);
}
});
} else if (prop instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'decl' && prop.test(child.prop)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'decl' && child.prop === prop) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each rule node.
*
* If you pass a filter, iteration will only happen over rules
* with matching selectors.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [selector] - string or regular expression
* to filter rules by selector
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const selectors = [];
* root.walkRules(rule => {
* selectors.push(rule.selector);
* });
* console.log(`Your CSS uses ${selectors.length} selectors`);
*/
Container.prototype.walkRules = function walkRules(selector, callback) {
if (!callback) {
callback = selector;
return this.walk(function (child, i) {
if (child.type === 'rule') {
return callback(child, i);
}
});
} else if (selector instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'rule' && selector.test(child.selector)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'rule' && child.selector === selector) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each at-rule node.
*
* If you pass a filter, iteration will only happen over at-rules
* that have matching names.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [name] - string or regular expression
* to filter at-rules by name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkAtRules(rule => {
* if ( isOld(rule.name) ) rule.remove();
* });
*
* let first = false;
* root.walkAtRules('charset', rule => {
* if ( !first ) {
* first = true;
* } else {
* rule.remove();
* }
* });
*/
Container.prototype.walkAtRules = function walkAtRules(name, callback) {
if (!callback) {
callback = name;
return this.walk(function (child, i) {
if (child.type === 'atrule') {
return callback(child, i);
}
});
} else if (name instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'atrule' && name.test(child.name)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'atrule' && child.name === name) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each comment node.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkComments(comment => {
* comment.remove();
* });
*/
Container.prototype.walkComments = function walkComments(callback) {
return this.walk(function (child, i) {
if (child.type === 'comment') {
return callback(child, i);
}
});
};
/**
* Inserts new nodes to the end of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.append(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
Container.prototype.append = function append() {
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
for (var _iterator = children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var child = _ref;
var nodes = this.normalize(child, this.last);
for (var _iterator2 = nodes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var node = _ref2;
this.nodes.push(node);
}
}
return this;
};
/**
* Inserts new nodes to the start of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.prepend(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
Container.prototype.prepend = function prepend() {
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
children = children.reverse();
for (var _iterator3 = children, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var child = _ref3;
var nodes = this.normalize(child, this.first, 'prepend').reverse();
for (var _iterator4 = nodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var node = _ref4;
this.nodes.unshift(node);
}for (var id in this.indexes) {
this.indexes[id] = this.indexes[id] + nodes.length;
}
}
return this;
};
Container.prototype.cleanRaws = function cleanRaws(keepBetween) {
_Node.prototype.cleanRaws.call(this, keepBetween);
if (this.nodes) {
for (var _iterator5 = this.nodes, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var node = _ref5;
node.cleanRaws(keepBetween);
}
}
};
/**
* Insert new node before old node within the container.
*
* @param {Node|number} exist - child or child’s index.
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*
* @example
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
*/
Container.prototype.insertBefore = function insertBefore(exist, add) {
exist = this.index(exist);
var type = exist === 0 ? 'prepend' : false;
var nodes = this.normalize(add, this.nodes[exist], type).reverse();
for (var _iterator6 = nodes, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref6;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref6 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref6 = _i6.value;
}
var node = _ref6;
this.nodes.splice(exist, 0, node);
}var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist <= index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
/**
* Insert new node after old node within the container.
*
* @param {Node|number} exist - child or child’s index
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*/
Container.prototype.insertAfter = function insertAfter(exist, add) {
exist = this.index(exist);
var nodes = this.normalize(add, this.nodes[exist]).reverse();
for (var _iterator7 = nodes, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
var _ref7;
if (_isArray7) {
if (_i7 >= _iterator7.length) break;
_ref7 = _iterator7[_i7++];
} else {
_i7 = _iterator7.next();
if (_i7.done) break;
_ref7 = _i7.value;
}
var node = _ref7;
this.nodes.splice(exist + 1, 0, node);
}var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist < index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
/**
* Removes node from the container and cleans the parent properties
* from the node and its children.
*
* @param {Node|number} child - child or child’s index
*
* @return {Node} this node for methods chain
*
* @example
* rule.nodes.length //=> 5
* rule.removeChild(decl);
* rule.nodes.length //=> 4
* decl.parent //=> undefined
*/
Container.prototype.removeChild = function removeChild(child) {
child = this.index(child);
this.nodes[child].parent = undefined;
this.nodes.splice(child, 1);
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 1;
}
}
return this;
};
/**
* Removes all children from the container
* and cleans their parent properties.
*
* @return {Node} this node for methods chain
*
* @example
* rule.removeAll();
* rule.nodes.length //=> 0
*/
Container.prototype.removeAll = function removeAll() {
for (var _iterator8 = this.nodes, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) {
var _ref8;
if (_isArray8) {
if (_i8 >= _iterator8.length) break;
_ref8 = _iterator8[_i8++];
} else {
_i8 = _iterator8.next();
if (_i8.done) break;
_ref8 = _i8.value;
}
var node = _ref8;
node.parent = undefined;
}this.nodes = [];
return this;
};
/**
* Passes all declaration values within the container that match pattern
* through callback, replacing those values with the returned result
* of callback.
*
* This method is useful if you are using a custom unit or function
* and need to iterate through all values.
*
* @param {string|RegExp} pattern - replace pattern
* @param {object} opts - options to speed up the search
* @param {string|string[]} opts.props - an array of property names
* @param {string} opts.fast - string that’s used
* to narrow down values and speed up
the regexp search
* @param {function|string} callback - string to replace pattern
* or callback that returns a new
* value.
* The callback will receive
* the same arguments as those
* passed to a function parameter
* of `String#replace`.
*
* @return {Node} this node for methods chain
*
* @example
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
* return 15 * parseInt(string) + 'px';
* });
*/
Container.prototype.replaceValues = function replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts;
opts = {};
}
this.walkDecls(function (decl) {
if (opts.props && opts.props.indexOf(decl.prop) === -1) return;
if (opts.fast && decl.value.indexOf(opts.fast) === -1) return;
decl.value = decl.value.replace(pattern, callback);
});
return this;
};
/**
* Returns `true` if callback returns `true`
* for all of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is every child pass condition
*
* @example
* const noPrefixes = rule.every(i => i.prop[0] !== '-');
*/
Container.prototype.every = function every(condition) {
return this.nodes.every(condition);
};
/**
* Returns `true` if callback returns `true` for (at least) one
* of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is some child pass condition
*
* @example
* const hasPrefix = rule.some(i => i.prop[0] === '-');
*/
Container.prototype.some = function some(condition) {
return this.nodes.some(condition);
};
/**
* Returns a `child`’s index within the {@link Container#nodes} array.
*
* @param {Node} child - child of the current container.
*
* @return {number} child index
*
* @example
* rule.index( rule.nodes[2] ) //=> 2
*/
Container.prototype.index = function index(child) {
if (typeof child === 'number') {
return child;
} else {
return this.nodes.indexOf(child);
}
};
/**
* The container’s first child.
*
* @type {Node}
*
* @example
* rule.first == rules.nodes[0];
*/
Container.prototype.normalize = function normalize(nodes, sample) {
var _this2 = this;
if (typeof nodes === 'string') {
var parse = require('./parse');
nodes = cleanSource(parse(nodes).nodes);
} else if (Array.isArray(nodes)) {
nodes = nodes.slice(0);
for (var _iterator9 = nodes, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) {
var _ref9;
if (_isArray9) {
if (_i9 >= _iterator9.length) break;
_ref9 = _iterator9[_i9++];
} else {
_i9 = _iterator9.next();
if (_i9.done) break;
_ref9 = _i9.value;
}
var i = _ref9;
if (i.parent) i.parent.removeChild(i, 'ignore');
}
} else if (nodes.type === 'root') {
nodes = nodes.nodes.slice(0);
for (var _iterator10 = nodes, _isArray10 = Array.isArray(_iterator10), _i11 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) {
var _ref10;
if (_isArray10) {
if (_i11 >= _iterator10.length) break;
_ref10 = _iterator10[_i11++];
} else {
_i11 = _iterator10.next();
if (_i11.done) break;
_ref10 = _i11.value;
}
var _i10 = _ref10;
if (_i10.parent) _i10.parent.removeChild(_i10, 'ignore');
}
} else if (nodes.type) {
nodes = [nodes];
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation');
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value);
}
nodes = [new _declaration2.default(nodes)];
} else if (nodes.selector) {
var Rule = require('./rule');
nodes = [new Rule(nodes)];
} else if (nodes.name) {
var AtRule = require('./at-rule');
nodes = [new AtRule(nodes)];
} else if (nodes.text) {
nodes = [new _comment2.default(nodes)];
} else {
throw new Error('Unknown node type in node creation');
}
var processed = nodes.map(function (i) {
if (typeof i.before !== 'function') i = _this2.rebuild(i);
if (i.parent) i.parent.removeChild(i);
if (typeof i.raws.before === 'undefined') {
if (sample && typeof sample.raws.before !== 'undefined') {
i.raws.before = sample.raws.before.replace(/[^\s]/g, '');
}
}
i.parent = _this2;
return i;
});
return processed;
};
Container.prototype.rebuild = function rebuild(node, parent) {
var _this3 = this;
var fix = void 0;
if (node.type === 'root') {
var Root = require('./root');
fix = new Root();
} else if (node.type === 'atrule') {
var AtRule = require('./at-rule');
fix = new AtRule();
} else if (node.type === 'rule') {
var Rule = require('./rule');
fix = new Rule();
} else if (node.type === 'decl') {
fix = new _declaration2.default();
} else if (node.type === 'comment') {
fix = new _comment2.default();
}
for (var i in node) {
if (i === 'nodes') {
fix.nodes = node.nodes.map(function (j) {
return _this3.rebuild(j, fix);
});
} else if (i === 'parent' && parent) {
fix.parent = parent;
} else if (node.hasOwnProperty(i)) {
fix[i] = node[i];
}
}
return fix;
};
/**
* @memberof Container#
* @member {Node[]} nodes - an array containing the container’s children
*
* @example
* const root = postcss.parse('a { color: black }');
* root.nodes.length //=> 1
* root.nodes[0].selector //=> 'a'
* root.nodes[0].nodes[0].prop //=> 'color'
*/
_createClass(Container, [{
key: 'first',
get: function get() {
if (!this.nodes) return undefined;
return this.nodes[0];
}
/**
* The container’s last child.
*
* @type {Node}
*
* @example
* rule.last == rule.nodes[rule.nodes.length - 1];
*/
}, {
key: 'last',
get: function get() {
if (!this.nodes) return undefined;
return this.nodes[this.nodes.length - 1];
}
}]);
return Container;
}(_node2.default);
exports.default = Container;
/**
* @callback childCondition
* @param {Node} node - container child
* @param {number} index - child index
* @param {Node[]} nodes - all container children
* @return {boolean}
*/
/**
* @callback childIterator
* @param {Node} node - container child
* @param {number} index - child index
* @return {false|undefined} returning `false` will break iteration
*/
module.exports = exports['default'];
},{"./at-rule":529,"./comment":530,"./declaration":533,"./node":538,"./parse":539,"./root":545,"./rule":546}],532:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _supportsColor = require('supports-color');
var _supportsColor2 = _interopRequireDefault(_supportsColor);
var _chalk = require('chalk');
var _chalk2 = _interopRequireDefault(_chalk);
var _terminalHighlight = require('./terminal-highlight');
var _terminalHighlight2 = _interopRequireDefault(_terminalHighlight);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* The CSS parser throws this error for broken CSS.
*
* Custom parsers can throw this error for broken custom syntax using
* the {@link Node#error} method.
*
* PostCSS will use the input source map to detect the original error location.
* If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
* PostCSS will show the original position in the Sass file.
*
* If you need the position in the PostCSS input
* (e.g., to debug the previous compiler), use `error.input.file`.
*
* @example
* // Catching and checking syntax error
* try {
* postcss.parse('a{')
* } catch (error) {
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
* }
*
* @example
* // Raising error from plugin
* throw node.error('Unknown variable', { plugin: 'postcss-vars' });
*/
var CssSyntaxError = function () {
/**
* @param {string} message - error message
* @param {number} [line] - source line of the error
* @param {number} [column] - source column of the error
* @param {string} [source] - source code of the broken file
* @param {string} [file] - absolute path to the broken file
* @param {string} [plugin] - PostCSS plugin name, if error came from plugin
*/
function CssSyntaxError(message, line, column, source, file, plugin) {
_classCallCheck(this, CssSyntaxError);
/**
* @member {string} - Always equal to `'CssSyntaxError'`. You should
* always check error type
* by `error.name === 'CssSyntaxError'` instead of
* `error instanceof CssSyntaxError`, because
* npm could have several PostCSS versions.
*
* @example
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
*/
this.name = 'CssSyntaxError';
/**
* @member {string} - Error message.
*
* @example
* error.message //=> 'Unclosed block'
*/
this.reason = message;
if (file) {
/**
* @member {string} - Absolute path to the broken file.
*
* @example
* error.file //=> 'a.sass'
* error.input.file //=> 'a.css'
*/
this.file = file;
}
if (source) {
/**
* @member {string} - Source code of the broken file.
*
* @example
* error.source //=> 'a { b {} }'
* error.input.column //=> 'a b { }'
*/
this.source = source;
}
if (plugin) {
/**
* @member {string} - Plugin name, if error came from plugin.
*
* @example
* error.plugin //=> 'postcss-vars'
*/
this.plugin = plugin;
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
/**
* @member {number} - Source line of the error.
*
* @example
* error.line //=> 2
* error.input.line //=> 4
*/
this.line = line;
/**
* @member {number} - Source column of the error.
*
* @example
* error.column //=> 1
* error.input.column //=> 4
*/
this.column = column;
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError);
}
}
CssSyntaxError.prototype.setMessage = function setMessage() {
/**
* @member {string} - Full error text in the GNU error format
* with plugin, file, line and column.
*
* @example
* error.message //=> 'a.css:1:1: Unclosed block'
*/
this.message = this.plugin ? this.plugin + ': ' : '';
this.message += this.file ? this.file : '<css input>';
if (typeof this.line !== 'undefined') {
this.message += ':' + this.line + ':' + this.column;
}
this.message += ': ' + this.reason;
};
/**
* Returns a few lines of CSS source that caused the error.
*
* If the CSS has an input source map without `sourceContent`,
* this method will return an empty string.
*
* @param {boolean} [color] whether arrow will be colored red by terminal
* color codes. By default, PostCSS will detect
* color support by `process.stdout.isTTY`
* and `process.env.NODE_DISABLE_COLORS`.
*
* @example
* error.showSourceCode() //=> " 4 | }
* // 5 | a {
* // > 6 | bad
* // | ^
* // 7 | }
* // 8 | b {"
*
* @return {string} few lines of CSS source that caused the error
*/
CssSyntaxError.prototype.showSourceCode = function showSourceCode(color) {
var _this = this;
if (!this.source) return '';
var css = this.source;
if (typeof color === 'undefined') color = _supportsColor2.default;
if (color) css = (0, _terminalHighlight2.default)(css);
var lines = css.split(/\r?\n/);
var start = Math.max(this.line - 3, 0);
var end = Math.min(this.line + 2, lines.length);
var maxWidth = String(end).length;
function mark(text) {
if (color) {
return _chalk2.default.red.bold(text);
} else {
return text;
}
}
function aside(text) {
if (color) {
return _chalk2.default.gray(text);
} else {
return text;
}
}
return lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
if (number === _this.line) {
var spacing = aside(gutter.replace(/\d/g, ' ')) + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' ');
return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^');
} else {
return ' ' + aside(gutter) + line;
}
}).join('\n');
};
/**
* Returns error position, message and source code of the broken part.
*
* @example
* error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
* // > 1 | a {
* // | ^"
*
* @return {string} error position, message and source code
*/
CssSyntaxError.prototype.toString = function toString() {
var code = this.showSourceCode();
if (code) {
code = '\n\n' + code + '\n';
}
return this.name + ': ' + this.message + code;
};
/**
* @memberof CssSyntaxError#
* @member {Input} input - Input object with PostCSS internal information
* about input file. If input has source map
* from previous tool, PostCSS will use origin
* (for example, Sass) source. You can use this
* object to get PostCSS input source.
*
* @example
* error.input.file //=> 'a.css'
* error.file //=> 'a.sass'
*/
return CssSyntaxError;
}();
exports.default = CssSyntaxError;
module.exports = exports['default'];
},{"./terminal-highlight":549,"chalk":554,"supports-color":556}],533:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents a CSS declaration.
*
* @extends Node
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.type //=> 'decl'
* decl.toString() //=> ' color: black'
*/
var Declaration = function (_Node) {
_inherits(Declaration, _Node);
function Declaration(defaults) {
_classCallCheck(this, Declaration);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'decl';
return _this;
}
/**
* @memberof Declaration#
* @member {string} prop - the declaration’s property name
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.prop //=> 'color'
*/
/**
* @memberof Declaration#
* @member {string} value - the declaration’s value
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.value //=> 'black'
*/
/**
* @memberof Declaration#
* @member {boolean} important - `true` if the declaration
* has an !important annotation.
*
* @example
* const root = postcss.parse('a { color: black !important; color: red }');
* root.first.first.important //=> true
* root.first.last.important //=> undefined
*/
/**
* @memberof Declaration#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `between`: the symbols between the property and value
* for declarations.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans declaration from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
return Declaration;
}(_node2.default);
exports.default = Declaration;
module.exports = exports['default'];
},{"./node":538}],534:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _cssSyntaxError = require('./css-syntax-error');
var _cssSyntaxError2 = _interopRequireDefault(_cssSyntaxError);
var _previousMap = require('./previous-map');
var _previousMap2 = _interopRequireDefault(_previousMap);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var sequence = 0;
/**
* Represents the source CSS.
*
* @example
* const root = postcss.parse(css, { from: file });
* const input = root.source.input;
*/
var Input = function () {
/**
* @param {string} css - input CSS source
* @param {object} [opts] - {@link Processor#process} options
*/
function Input(css) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Input);
/**
* @member {string} - input CSS source
*
* @example
* const input = postcss.parse('a{}', { from: file }).input;
* input.css //=> "a{}";
*/
this.css = css.toString();
if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
this.css = this.css.slice(1);
}
if (opts.from) {
if (/^\w+:\/\//.test(opts.from)) {
/**
* @member {string} - The absolute path to the CSS source file
* defined with the `from` option.
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.file //=> '/home/ai/a.css'
*/
this.file = opts.from;
} else {
this.file = _path2.default.resolve(opts.from);
}
}
var map = new _previousMap2.default(this.css, opts);
if (map.text) {
/**
* @member {PreviousMap} - The input source map passed from
* a compilation step before PostCSS
* (for example, from Sass compiler).
*
* @example
* root.source.input.map.consumer().sources //=> ['a.sass']
*/
this.map = map;
var file = map.consumer().file;
if (!this.file && file) this.file = this.mapResolve(file);
}
if (!this.file) {
sequence += 1;
/**
* @member {string} - The unique ID of the CSS source. It will be
* created if `from` option is not provided
* (because PostCSS does not know the file path).
*
* @example
* const root = postcss.parse(css);
* root.source.input.file //=> undefined
* root.source.input.id //=> "<input css 1>"
*/
this.id = '<input css ' + sequence + '>';
}
if (this.map) this.map.file = this.from;
}
Input.prototype.error = function error(message, line, column) {
var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var result = void 0;
var origin = this.origin(line, column);
if (origin) {
result = new _cssSyntaxError2.default(message, origin.line, origin.column, origin.source, origin.file, opts.plugin);
} else {
result = new _cssSyntaxError2.default(message, line, column, this.css, this.file, opts.plugin);
}
result.input = { line: line, column: column, source: this.css };
if (this.file) result.input.file = this.file;
return result;
};
/**
* Reads the input source map and returns a symbol position
* in the input source (e.g., in a Sass file that was compiled
* to CSS before being passed to PostCSS).
*
* @param {number} line - line in input CSS
* @param {number} column - column in input CSS
*
* @return {filePosition} position in input source
*
* @example
* root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
*/
Input.prototype.origin = function origin(line, column) {
if (!this.map) return false;
var consumer = this.map.consumer();
var from = consumer.originalPositionFor({ line: line, column: column });
if (!from.source) return false;
var result = {
file: this.mapResolve(from.source),
line: from.line,
column: from.column
};
var source = consumer.sourceContentFor(from.source);
if (source) result.source = source;
return result;
};
Input.prototype.mapResolve = function mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file;
} else {
return _path2.default.resolve(this.map.consumer().sourceRoot || '.', file);
}
};
/**
* The CSS source identifier. Contains {@link Input#file} if the user
* set the `from` option, or {@link Input#id} if they did not.
* @type {string}
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.from //=> "/home/ai/a.css"
*
* const root = postcss.parse(css);
* root.source.input.from //=> "<input css 1>"
*/
_createClass(Input, [{
key: 'from',
get: function get() {
return this.file || this.id;
}
}]);
return Input;
}();
exports.default = Input;
/**
* @typedef {object} filePosition
* @property {string} file - path to file
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
module.exports = exports['default'];
},{"./css-syntax-error":532,"./previous-map":542,"path":523}],535:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var _mapGenerator = require('./map-generator');
var _mapGenerator2 = _interopRequireDefault(_mapGenerator);
var _stringify2 = require('./stringify');
var _stringify3 = _interopRequireDefault(_stringify2);
var _result = require('./result');
var _result2 = _interopRequireDefault(_result);
var _parse = require('./parse');
var _parse2 = _interopRequireDefault(_parse);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function isPromise(obj) {
return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.then === 'function';
}
/**
* A Promise proxy for the result of PostCSS transformations.
*
* A `LazyResult` instance is returned by {@link Processor#process}.
*
* @example
* const lazy = postcss([cssnext]).process(css);
*/
var LazyResult = function () {
function LazyResult(processor, css, opts) {
_classCallCheck(this, LazyResult);
this.stringified = false;
this.processed = false;
var root = void 0;
if ((typeof css === 'undefined' ? 'undefined' : _typeof(css)) === 'object' && css.type === 'root') {
root = css;
} else if (css instanceof LazyResult || css instanceof _result2.default) {
root = css.root;
if (css.map) {
if (typeof opts.map === 'undefined') opts.map = {};
if (!opts.map.inline) opts.map.inline = false;
opts.map.prev = css.map;
}
} else {
var parser = _parse2.default;
if (opts.syntax) parser = opts.syntax.parse;
if (opts.parser) parser = opts.parser;
if (parser.parse) parser = parser.parse;
try {
root = parser(css, opts);
} catch (error) {
this.error = error;
}
}
this.result = new _result2.default(processor, root, opts);
}
/**
* Returns a {@link Processor} instance, which will be used
* for CSS transformations.
* @type {Processor}
*/
/**
* Processes input CSS through synchronous plugins
* and calls {@link Result#warnings()}.
*
* @return {Warning[]} warnings from plugins
*/
LazyResult.prototype.warnings = function warnings() {
return this.sync().warnings();
};
/**
* Alias for the {@link LazyResult#css} property.
*
* @example
* lazy + '' === lazy.css;
*
* @return {string} output CSS
*/
LazyResult.prototype.toString = function toString() {
return this.css;
};
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls `onFulfilled` with a Result instance. If a plugin throws
* an error, the `onRejected` callback will be executed.
*
* It implements standard Promise API.
*
* @param {onFulfilled} onFulfilled - callback will be executed
* when all plugins will finish work
* @param {onRejected} onRejected - callback will be executed on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* });
*/
LazyResult.prototype.then = function then(onFulfilled, onRejected) {
return this.async().then(onFulfilled, onRejected);
};
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls onRejected for each error thrown in any plugin.
*
* It implements standard Promise API.
*
* @param {onRejected} onRejected - callback will be executed on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* }).catch(error => {
* console.error(error);
* });
*/
LazyResult.prototype.catch = function _catch(onRejected) {
return this.async().catch(onRejected);
};
LazyResult.prototype.handleError = function handleError(error, plugin) {
try {
this.error = error;
if (error.name === 'CssSyntaxError' && !error.plugin) {
error.plugin = plugin.postcssPlugin;
error.setMessage();
} else if (plugin.postcssVersion) {
var pluginName = plugin.postcssPlugin;
var pluginVer = plugin.postcssVersion;
var runtimeVer = this.result.processor.version;
var a = pluginVer.split('.');
var b = runtimeVer.split('.');
if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
console.error('Your current PostCSS version ' + 'is ' + runtimeVer + ', but ' + pluginName + ' ' + 'uses ' + pluginVer + '. Perhaps this is ' + 'the source of the error below.');
}
}
} catch (err) {
if (console && console.error) console.error(err);
}
};
LazyResult.prototype.asyncTick = function asyncTick(resolve, reject) {
var _this = this;
if (this.plugin >= this.processor.plugins.length) {
this.processed = true;
return resolve();
}
try {
var plugin = this.processor.plugins[this.plugin];
var promise = this.run(plugin);
this.plugin += 1;
if (isPromise(promise)) {
promise.then(function () {
_this.asyncTick(resolve, reject);
}).catch(function (error) {
_this.handleError(error, plugin);
_this.processed = true;
reject(error);
});
} else {
this.asyncTick(resolve, reject);
}
} catch (error) {
this.processed = true;
reject(error);
}
};
LazyResult.prototype.async = function async() {
var _this2 = this;
if (this.processed) {
return new Promise(function (resolve, reject) {
if (_this2.error) {
reject(_this2.error);
} else {
resolve(_this2.stringify());
}
});
}
if (this.processing) {
return this.processing;
}
this.processing = new Promise(function (resolve, reject) {
if (_this2.error) return reject(_this2.error);
_this2.plugin = 0;
_this2.asyncTick(resolve, reject);
}).then(function () {
_this2.processed = true;
return _this2.stringify();
});
return this.processing;
};
LazyResult.prototype.sync = function sync() {
if (this.processed) return this.result;
this.processed = true;
if (this.processing) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
if (this.error) throw this.error;
for (var _iterator = this.result.processor.plugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var plugin = _ref;
var promise = this.run(plugin);
if (isPromise(promise)) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
}
return this.result;
};
LazyResult.prototype.run = function run(plugin) {
this.result.lastPlugin = plugin;
try {
return plugin(this.result.root, this.result);
} catch (error) {
this.handleError(error, plugin);
throw error;
}
};
LazyResult.prototype.stringify = function stringify() {
if (this.stringified) return this.result;
this.stringified = true;
this.sync();
var opts = this.result.opts;
var str = _stringify3.default;
if (opts.syntax) str = opts.syntax.stringify;
if (opts.stringifier) str = opts.stringifier;
if (str.stringify) str = str.stringify;
var map = new _mapGenerator2.default(str, this.result.root, this.result.opts);
var data = map.generate();
this.result.css = data[0];
this.result.map = data[1];
return this.result;
};
_createClass(LazyResult, [{
key: 'processor',
get: function get() {
return this.result.processor;
}
/**
* Options from the {@link Processor#process} call.
* @type {processOptions}
*/
}, {
key: 'opts',
get: function get() {
return this.result.opts;
}
/**
* Processes input CSS through synchronous plugins, converts `Root`
* to a CSS string and returns {@link Result#css}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#css
*/
}, {
key: 'css',
get: function get() {
return this.stringify().css;
}
/**
* An alias for the `css` property. Use it with syntaxes
* that generate non-CSS output.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#content
*/
}, {
key: 'content',
get: function get() {
return this.stringify().content;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#map}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {SourceMapGenerator}
* @see Result#map
*/
}, {
key: 'map',
get: function get() {
return this.stringify().map;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#root}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Root}
* @see Result#root
*/
}, {
key: 'root',
get: function get() {
return this.sync().root;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#messages}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Message[]}
* @see Result#messages
*/
}, {
key: 'messages',
get: function get() {
return this.sync().messages;
}
}]);
return LazyResult;
}();
exports.default = LazyResult;
/**
* @callback onFulfilled
* @param {Result} result
*/
/**
* @callback onRejected
* @param {Error} error
*/
module.exports = exports['default'];
},{"./map-generator":537,"./parse":539,"./result":544,"./stringify":548}],536:[function(require,module,exports){
'use strict';
exports.__esModule = true;
/**
* Contains helpers for safely splitting lists of CSS values,
* preserving parentheses and quotes.
*
* @example
* const list = postcss.list;
*
* @namespace list
*/
var list = {
split: function split(string, separators, last) {
var array = [];
var current = '';
var split = false;
var func = 0;
var quote = false;
var escape = false;
for (var i = 0; i < string.length; i++) {
var letter = string[i];
if (quote) {
if (escape) {
escape = false;
} else if (letter === '\\') {
escape = true;
} else if (letter === quote) {
quote = false;
}
} else if (letter === '"' || letter === '\'') {
quote = letter;
} else if (letter === '(') {
func += 1;
} else if (letter === ')') {
if (func > 0) func -= 1;
} else if (func === 0) {
if (separators.indexOf(letter) !== -1) split = true;
}
if (split) {
if (current !== '') array.push(current.trim());
current = '';
split = false;
} else {
current += letter;
}
}
if (last || current !== '') array.push(current.trim());
return array;
},
/**
* Safely splits space-separated values (such as those for `background`,
* `border-radius`, and other shorthand properties).
*
* @param {string} string - space-separated values
*
* @return {string[]} split values
*
* @example
* postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
*/
space: function space(string) {
var spaces = [' ', '\n', '\t'];
return list.split(string, spaces);
},
/**
* Safely splits comma-separated values (such as those for `transition-*`
* and `background` properties).
*
* @param {string} string - comma-separated values
*
* @return {string[]} split values
*
* @example
* postcss.list.comma('black, linear-gradient(white, black)')
* //=> ['black', 'linear-gradient(white, black)']
*/
comma: function comma(string) {
var comma = ',';
return list.split(string, [comma], true);
}
};
exports.default = list;
module.exports = exports['default'];
},{}],537:[function(require,module,exports){
(function (Buffer){
'use strict';
exports.__esModule = true;
var _sourceMap = require('source-map');
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var MapGenerator = function () {
function MapGenerator(stringify, root, opts) {
_classCallCheck(this, MapGenerator);
this.stringify = stringify;
this.mapOpts = opts.map || {};
this.root = root;
this.opts = opts;
}
MapGenerator.prototype.isMap = function isMap() {
if (typeof this.opts.map !== 'undefined') {
return !!this.opts.map;
} else {
return this.previous().length > 0;
}
};
MapGenerator.prototype.previous = function previous() {
var _this = this;
if (!this.previousMaps) {
this.previousMaps = [];
this.root.walk(function (node) {
if (node.source && node.source.input.map) {
var map = node.source.input.map;
if (_this.previousMaps.indexOf(map) === -1) {
_this.previousMaps.push(map);
}
}
});
}
return this.previousMaps;
};
MapGenerator.prototype.isInline = function isInline() {
if (typeof this.mapOpts.inline !== 'undefined') {
return this.mapOpts.inline;
}
var annotation = this.mapOpts.annotation;
if (typeof annotation !== 'undefined' && annotation !== true) {
return false;
}
if (this.previous().length) {
return this.previous().some(function (i) {
return i.inline;
});
} else {
return true;
}
};
MapGenerator.prototype.isSourcesContent = function isSourcesContent() {
if (typeof this.mapOpts.sourcesContent !== 'undefined') {
return this.mapOpts.sourcesContent;
}
if (this.previous().length) {
return this.previous().some(function (i) {
return i.withContent();
});
} else {
return true;
}
};
MapGenerator.prototype.clearAnnotation = function clearAnnotation() {
if (this.mapOpts.annotation === false) return;
var node = void 0;
for (var i = this.root.nodes.length - 1; i >= 0; i--) {
node = this.root.nodes[i];
if (node.type !== 'comment') continue;
if (node.text.indexOf('# sourceMappingURL=') === 0) {
this.root.removeChild(i);
}
}
};
MapGenerator.prototype.setSourcesContent = function setSourcesContent() {
var _this2 = this;
var already = {};
this.root.walk(function (node) {
if (node.source) {
var from = node.source.input.from;
if (from && !already[from]) {
already[from] = true;
var relative = _this2.relative(from);
_this2.map.setSourceContent(relative, node.source.input.css);
}
}
});
};
MapGenerator.prototype.applyPrevMaps = function applyPrevMaps() {
for (var _iterator = this.previous(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prev = _ref;
var from = this.relative(prev.file);
var root = prev.root || _path2.default.dirname(prev.file);
var map = void 0;
if (this.mapOpts.sourcesContent === false) {
map = new _sourceMap2.default.SourceMapConsumer(prev.text);
if (map.sourcesContent) {
map.sourcesContent = map.sourcesContent.map(function () {
return null;
});
}
} else {
map = prev.consumer();
}
this.map.applySourceMap(map, from, this.relative(root));
}
};
MapGenerator.prototype.isAnnotation = function isAnnotation() {
if (this.isInline()) {
return true;
} else if (typeof this.mapOpts.annotation !== 'undefined') {
return this.mapOpts.annotation;
} else if (this.previous().length) {
return this.previous().some(function (i) {
return i.annotation;
});
} else {
return true;
}
};
MapGenerator.prototype.toBase64 = function toBase64(str) {
if (Buffer) {
return Buffer.from ? Buffer.from(str).toString('base64') : new Buffer(str).toString('base64');
} else {
return window.btoa(unescape(encodeURIComponent(str)));
}
};
MapGenerator.prototype.addAnnotation = function addAnnotation() {
var content = void 0;
if (this.isInline()) {
content = 'data:application/json;base64,' + this.toBase64(this.map.toString());
} else if (typeof this.mapOpts.annotation === 'string') {
content = this.mapOpts.annotation;
} else {
content = this.outputFile() + '.map';
}
var eol = '\n';
if (this.css.indexOf('\r\n') !== -1) eol = '\r\n';
this.css += eol + '/*# sourceMappingURL=' + content + ' */';
};
MapGenerator.prototype.outputFile = function outputFile() {
if (this.opts.to) {
return this.relative(this.opts.to);
} else if (this.opts.from) {
return this.relative(this.opts.from);
} else {
return 'to.css';
}
};
MapGenerator.prototype.generateMap = function generateMap() {
this.generateString();
if (this.isSourcesContent()) this.setSourcesContent();
if (this.previous().length > 0) this.applyPrevMaps();
if (this.isAnnotation()) this.addAnnotation();
if (this.isInline()) {
return [this.css];
} else {
return [this.css, this.map];
}
};
MapGenerator.prototype.relative = function relative(file) {
if (file.indexOf('<') === 0) return file;
if (/^\w+:\/\//.test(file)) return file;
var from = this.opts.to ? _path2.default.dirname(this.opts.to) : '.';
if (typeof this.mapOpts.annotation === 'string') {
from = _path2.default.dirname(_path2.default.resolve(from, this.mapOpts.annotation));
}
file = _path2.default.relative(from, file);
if (_path2.default.sep === '\\') {
return file.replace(/\\/g, '/');
} else {
return file;
}
};
MapGenerator.prototype.sourcePath = function sourcePath(node) {
if (this.mapOpts.from) {
return this.mapOpts.from;
} else {
return this.relative(node.source.input.from);
}
};
MapGenerator.prototype.generateString = function generateString() {
var _this3 = this;
this.css = '';
this.map = new _sourceMap2.default.SourceMapGenerator({ file: this.outputFile() });
var line = 1;
var column = 1;
var lines = void 0,
last = void 0;
this.stringify(this.root, function (str, node, type) {
_this3.css += str;
if (node && type !== 'end') {
if (node.source && node.source.start) {
_this3.map.addMapping({
source: _this3.sourcePath(node),
generated: { line: line, column: column - 1 },
original: {
line: node.source.start.line,
column: node.source.start.column - 1
}
});
} else {
_this3.map.addMapping({
source: '<no source>',
original: { line: 1, column: 0 },
generated: { line: line, column: column - 1 }
});
}
}
lines = str.match(/\n/g);
if (lines) {
line += lines.length;
last = str.lastIndexOf('\n');
column = str.length - last;
} else {
column += str.length;
}
if (node && type !== 'start') {
if (node.source && node.source.end) {
_this3.map.addMapping({
source: _this3.sourcePath(node),
generated: { line: line, column: column - 1 },
original: {
line: node.source.end.line,
column: node.source.end.column
}
});
} else {
_this3.map.addMapping({
source: '<no source>',
original: { line: 1, column: 0 },
generated: { line: line, column: column - 1 }
});
}
}
});
};
MapGenerator.prototype.generate = function generate() {
this.clearAnnotation();
if (this.isMap()) {
return this.generateMap();
} else {
var result = '';
this.stringify(this.root, function (i) {
result += i;
});
return [result];
}
};
return MapGenerator;
}();
exports.default = MapGenerator;
module.exports = exports['default'];
}).call(this,require("buffer").Buffer)
},{"buffer":66,"path":523,"source-map":568}],538:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var _cssSyntaxError = require('./css-syntax-error');
var _cssSyntaxError2 = _interopRequireDefault(_cssSyntaxError);
var _stringifier = require('./stringifier');
var _stringifier2 = _interopRequireDefault(_stringifier);
var _stringify = require('./stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _warnOnce = require('./warn-once');
var _warnOnce2 = _interopRequireDefault(_warnOnce);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var cloneNode = function cloneNode(obj, parent) {
var cloned = new obj.constructor();
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
var value = obj[i];
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent;
} else if (i === 'source') {
cloned[i] = value;
} else if (value instanceof Array) {
cloned[i] = value.map(function (j) {
return cloneNode(j, cloned);
});
} else {
if (type === 'object' && value !== null) value = cloneNode(value);
cloned[i] = value;
}
}
return cloned;
};
/**
* All node classes inherit the following common methods.
*
* @abstract
*/
var Node = function () {
/**
* @param {object} [defaults] - value for node properties
*/
function Node() {
var defaults = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Node);
this.raws = {};
if ((typeof defaults === 'undefined' ? 'undefined' : _typeof(defaults)) !== 'object' && typeof defaults !== 'undefined') {
throw new Error('PostCSS nodes constructor accepts object, not ' + JSON.stringify(defaults));
}
for (var name in defaults) {
this[name] = defaults[name];
}
}
/**
* Returns a CssSyntaxError instance containing the original position
* of the node in the source, showing line and column numbers and also
* a small excerpt to facilitate debugging.
*
* If present, an input source map will be used to get the original position
* of the source, even from a previous compilation step
* (e.g., from Sass compilation).
*
* This method produces very useful error messages.
*
* @param {string} message - error description
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this error.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the error
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the error
*
* @return {CssSyntaxError} error object to throw it
*
* @example
* if ( !variables[name] ) {
* throw decl.error('Unknown variable ' + name, { word: name });
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
* // color: $black
* // a
* // ^
* // background: white
* }
*/
Node.prototype.error = function error(message) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (this.source) {
var pos = this.positionBy(opts);
return this.source.input.error(message, pos.line, pos.column, opts);
} else {
return new _cssSyntaxError2.default(message);
}
};
/**
* This method is provided as a convenience wrapper for {@link Result#warn}.
*
* @param {Result} result - the {@link Result} instance
* that will receive the warning
* @param {string} text - warning message
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this warning.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the warning
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the warning
*
* @return {Warning} created warning object
*
* @example
* const plugin = postcss.plugin('postcss-deprecated', () => {
* return (root, result) => {
* root.walkDecls('bad', decl => {
* decl.warn(result, 'Deprecated property bad');
* });
* };
* });
*/
Node.prototype.warn = function warn(result, text, opts) {
var data = { node: this };
for (var i in opts) {
data[i] = opts[i];
}return result.warn(text, data);
};
/**
* Removes the node from its parent and cleans the parent properties
* from the node and its children.
*
* @example
* if ( decl.prop.match(/^-webkit-/) ) {
* decl.remove();
* }
*
* @return {Node} node to make calls chain
*/
Node.prototype.remove = function remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this;
};
/**
* Returns a CSS string representing the node.
*
* @param {stringifier|syntax} [stringifier] - a syntax to use
* in string generation
*
* @return {string} CSS string of this node
*
* @example
* postcss.rule({ selector: 'a' }).toString() //=> "a {}"
*/
Node.prototype.toString = function toString() {
var stringifier = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _stringify2.default;
if (stringifier.stringify) stringifier = stringifier.stringify;
var result = '';
stringifier(this, function (i) {
result += i;
});
return result;
};
/**
* Returns a clone of the node.
*
* The resulting cloned node and its (cloned) children will have
* a clean parent and code style properties.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* const cloned = decl.clone({ prop: '-moz-' + decl.prop });
* cloned.raws.before //=> undefined
* cloned.parent //=> undefined
* cloned.toString() //=> -moz-transform: scale(0)
*
* @return {Node} clone of the node
*/
Node.prototype.clone = function clone() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = cloneNode(this);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
};
/**
* Shortcut to clone the node and insert the resulting cloned node
* before the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* decl.cloneBefore({ prop: '-moz-' + decl.prop });
*
* @return {Node} - new node
*/
Node.prototype.cloneBefore = function cloneBefore() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = this.clone(overrides);
this.parent.insertBefore(this, cloned);
return cloned;
};
/**
* Shortcut to clone the node and insert the resulting cloned node
* after the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @return {Node} - new node
*/
Node.prototype.cloneAfter = function cloneAfter() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = this.clone(overrides);
this.parent.insertAfter(this, cloned);
return cloned;
};
/**
* Inserts node(s) before the current node and removes the current node.
*
* @param {...Node} nodes - node(s) to replace current one
*
* @example
* if ( atrule.name == 'mixin' ) {
* atrule.replaceWith(mixinRules[atrule.params]);
* }
*
* @return {Node} current node to methods chain
*/
Node.prototype.replaceWith = function replaceWith() {
if (this.parent) {
for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) {
nodes[_key] = arguments[_key];
}
for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
this.parent.insertBefore(this, node);
}
this.remove();
}
return this;
};
Node.prototype.moveTo = function moveTo(newParent) {
(0, _warnOnce2.default)('Node#moveTo was deprecated. Use Container#append.');
this.cleanRaws(this.root() === newParent.root());
this.remove();
newParent.append(this);
return this;
};
Node.prototype.moveBefore = function moveBefore(otherNode) {
(0, _warnOnce2.default)('Node#moveBefore was deprecated. Use Node#before.');
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertBefore(otherNode, this);
return this;
};
Node.prototype.moveAfter = function moveAfter(otherNode) {
(0, _warnOnce2.default)('Node#moveAfter was deprecated. Use Node#after.');
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertAfter(otherNode, this);
return this;
};
/**
* Returns the next child of the node’s parent.
* Returns `undefined` if the current node is the last child.
*
* @return {Node|undefined} next node
*
* @example
* if ( comment.text === 'delete next' ) {
* const next = comment.next();
* if ( next ) {
* next.remove();
* }
* }
*/
Node.prototype.next = function next() {
var index = this.parent.index(this);
return this.parent.nodes[index + 1];
};
/**
* Returns the previous child of the node’s parent.
* Returns `undefined` if the current node is the first child.
*
* @return {Node|undefined} previous node
*
* @example
* const annotation = decl.prev();
* if ( annotation.type == 'comment' ) {
* readAnnotation(annotation.text);
* }
*/
Node.prototype.prev = function prev() {
var index = this.parent.index(this);
return this.parent.nodes[index - 1];
};
/**
* Insert new node before current node to current node’s parent.
*
* Just alias for `node.parent.insertBefore(node, add)`.
*
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain.
*
* @example
* decl.before('content: ""');
*/
Node.prototype.before = function before(add) {
this.parent.insertBefore(this, add);
return this;
};
/**
* Insert new node after current node to current node’s parent.
*
* Just alias for `node.parent.insertAfter(node, add)`.
*
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain.
*
* @example
* decl.after('color: black');
*/
Node.prototype.after = function after(add) {
this.parent.insertAfter(this, add);
return this;
};
Node.prototype.toJSON = function toJSON() {
var fixed = {};
for (var name in this) {
if (!this.hasOwnProperty(name)) continue;
if (name === 'parent') continue;
var value = this[name];
if (value instanceof Array) {
fixed[name] = value.map(function (i) {
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && i.toJSON) {
return i.toJSON();
} else {
return i;
}
});
} else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.toJSON) {
fixed[name] = value.toJSON();
} else {
fixed[name] = value;
}
}
return fixed;
};
/**
* Returns a {@link Node#raws} value. If the node is missing
* the code style property (because the node was manually built or cloned),
* PostCSS will try to autodetect the code style property by looking
* at other nodes in the tree.
*
* @param {string} prop - name of code style property
* @param {string} [defaultType] - name of default value, it can be missed
* if the value is the same as prop
*
* @example
* const root = postcss.parse('a { background: white }');
* root.nodes[0].append({ prop: 'color', value: 'black' });
* root.nodes[0].nodes[1].raws.before //=> undefined
* root.nodes[0].nodes[1].raw('before') //=> ' '
*
* @return {string} code style value
*/
Node.prototype.raw = function raw(prop, defaultType) {
var str = new _stringifier2.default();
return str.raw(this, prop, defaultType);
};
/**
* Finds the Root instance of the node’s tree.
*
* @example
* root.nodes[0].nodes[0].root() === root
*
* @return {Root} root parent
*/
Node.prototype.root = function root() {
var result = this;
while (result.parent) {
result = result.parent;
}return result;
};
Node.prototype.cleanRaws = function cleanRaws(keepBetween) {
delete this.raws.before;
delete this.raws.after;
if (!keepBetween) delete this.raws.between;
};
Node.prototype.positionInside = function positionInside(index) {
var string = this.toString();
var column = this.source.start.column;
var line = this.source.start.line;
for (var i = 0; i < index; i++) {
if (string[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return { line: line, column: column };
};
Node.prototype.positionBy = function positionBy(opts) {
var pos = this.source.start;
if (opts.index) {
pos = this.positionInside(opts.index);
} else if (opts.word) {
var index = this.toString().indexOf(opts.word);
if (index !== -1) pos = this.positionInside(index);
}
return pos;
};
/**
* @memberof Node#
* @member {string} type - String representing the node’s type.
* Possible values are `root`, `atrule`, `rule`,
* `decl`, or `comment`.
*
* @example
* postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
*/
/**
* @memberof Node#
* @member {Container} parent - the node’s parent node.
*
* @example
* root.nodes[0].parent == root;
*/
/**
* @memberof Node#
* @member {source} source - the input source of the node
*
* The property is used in source map generation.
*
* If you create a node manually (e.g., with `postcss.decl()`),
* that node will not have a `source` property and will be absent
* from the source map. For this reason, the plugin developer should
* consider cloning nodes to create new ones (in which case the new node’s
* source will reference the original, cloned node) or setting
* the `source` property manually.
*
* ```js
* // Bad
* const prefixed = postcss.decl({
* prop: '-moz-' + decl.prop,
* value: decl.value
* });
*
* // Good
* const prefixed = decl.clone({ prop: '-moz-' + decl.prop });
* ```
*
* ```js
* if ( atrule.name == 'add-link' ) {
* const rule = postcss.rule({ selector: 'a', source: atrule.source });
* atrule.parent.insertBefore(atrule, rule);
* }
* ```
*
* @example
* decl.source.input.from //=> '/home/ai/a.sass'
* decl.source.start //=> { line: 10, column: 2 }
* decl.source.end //=> { line: 10, column: 12 }
*/
/**
* @memberof Node#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text
* and <code>*/</code>.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans selectors, declaration values and at-rule parameters
* from comments and extra spaces, but it stores origin content in raws
* properties. As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
return Node;
}();
exports.default = Node;
/**
* @typedef {object} position
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
/**
* @typedef {object} source
* @property {Input} input - {@link Input} with input file
* @property {position} start - The starting position of the node’s source
* @property {position} end - The ending position of the node’s source
*/
module.exports = exports['default'];
},{"./css-syntax-error":532,"./stringifier":547,"./stringify":548,"./warn-once":552}],539:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.default = parse;
var _parser = require('./parser');
var _parser2 = _interopRequireDefault(_parser);
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function parse(css, opts) {
if (opts && opts.safe) {
throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
}
var input = new _input2.default(css, opts);
var parser = new _parser2.default(input);
try {
parser.parse();
} catch (e) {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
} else if (/\.sass/i.test(opts.from)) {
e.message += '\nYou tried to parse Sass with ' + 'the standard CSS parser; ' + 'try again with the postcss-sass parser';
} else if (/\.less$/i.test(opts.from)) {
e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
}
}
throw e;
}
return parser.root;
}
module.exports = exports['default'];
},{"./input":534,"./parser":540}],540:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _tokenize = require('./tokenize');
var _tokenize2 = _interopRequireDefault(_tokenize);
var _comment = require('./comment');
var _comment2 = _interopRequireDefault(_comment);
var _atRule = require('./at-rule');
var _atRule2 = _interopRequireDefault(_atRule);
var _root = require('./root');
var _root2 = _interopRequireDefault(_root);
var _rule = require('./rule');
var _rule2 = _interopRequireDefault(_rule);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Parser = function () {
function Parser(input) {
_classCallCheck(this, Parser);
this.input = input;
this.root = new _root2.default();
this.current = this.root;
this.spaces = '';
this.semicolon = false;
this.createTokenizer();
this.root.source = { input: input, start: { line: 1, column: 1 } };
}
Parser.prototype.createTokenizer = function createTokenizer() {
this.tokenizer = (0, _tokenize2.default)(this.input);
};
Parser.prototype.parse = function parse() {
var token = void 0;
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken();
switch (token[0]) {
case 'space':
this.spaces += token[1];
break;
case ';':
this.freeSemicolon(token);
break;
case '}':
this.end(token);
break;
case 'comment':
this.comment(token);
break;
case 'at-word':
this.atrule(token);
break;
case '{':
this.emptyRule(token);
break;
default:
this.other(token);
break;
}
}
this.endFile();
};
Parser.prototype.comment = function comment(token) {
var node = new _comment2.default();
this.init(node, token[2], token[3]);
node.source.end = { line: token[4], column: token[5] };
var text = token[1].slice(2, -2);
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
node.raws.left = match[1];
node.raws.right = match[3];
}
};
Parser.prototype.emptyRule = function emptyRule(token) {
var node = new _rule2.default();
this.init(node, token[2], token[3]);
node.selector = '';
node.raws.between = '';
this.current = node;
};
Parser.prototype.other = function other(start) {
var end = false;
var type = null;
var colon = false;
var bracket = null;
var brackets = [];
var tokens = [];
var token = start;
while (token) {
type = token[0];
tokens.push(token);
if (type === '(' || type === '[') {
if (!bracket) bracket = token;
brackets.push(type === '(' ? ')' : ']');
} else if (brackets.length === 0) {
if (type === ';') {
if (colon) {
this.decl(tokens);
return;
} else {
break;
}
} else if (type === '{') {
this.rule(tokens);
return;
} else if (type === '}') {
this.tokenizer.back(tokens.pop());
end = true;
break;
} else if (type === ':') {
colon = true;
}
} else if (type === brackets[brackets.length - 1]) {
brackets.pop();
if (brackets.length === 0) bracket = null;
}
token = this.tokenizer.nextToken();
}
if (this.tokenizer.endOfFile()) end = true;
if (brackets.length > 0) this.unclosedBracket(bracket);
if (end && colon) {
while (tokens.length) {
token = tokens[tokens.length - 1][0];
if (token !== 'space' && token !== 'comment') break;
this.tokenizer.back(tokens.pop());
}
this.decl(tokens);
return;
} else {
this.unknownWord(tokens);
}
};
Parser.prototype.rule = function rule(tokens) {
tokens.pop();
var node = new _rule2.default();
this.init(node, tokens[0][2], tokens[0][3]);
node.raws.between = this.spacesAndCommentsFromEnd(tokens);
this.raw(node, 'selector', tokens);
this.current = node;
};
Parser.prototype.decl = function decl(tokens) {
var node = new _declaration2.default();
this.init(node);
var last = tokens[tokens.length - 1];
if (last[0] === ';') {
this.semicolon = true;
tokens.pop();
}
if (last[4]) {
node.source.end = { line: last[4], column: last[5] };
} else {
node.source.end = { line: last[2], column: last[3] };
}
while (tokens[0][0] !== 'word') {
if (tokens.length === 1) this.unknownWord(tokens);
node.raws.before += tokens.shift()[1];
}
node.source.start = { line: tokens[0][2], column: tokens[0][3] };
node.prop = '';
while (tokens.length) {
var type = tokens[0][0];
if (type === ':' || type === 'space' || type === 'comment') {
break;
}
node.prop += tokens.shift()[1];
}
node.raws.between = '';
var token = void 0;
while (tokens.length) {
token = tokens.shift();
if (token[0] === ':') {
node.raws.between += token[1];
break;
} else {
node.raws.between += token[1];
}
}
if (node.prop[0] === '_' || node.prop[0] === '*') {
node.raws.before += node.prop[0];
node.prop = node.prop.slice(1);
}
node.raws.between += this.spacesAndCommentsFromStart(tokens);
this.precheckMissedSemicolon(tokens);
for (var i = tokens.length - 1; i > 0; i--) {
token = tokens[i];
if (token[1] === '!important') {
node.important = true;
var string = this.stringFrom(tokens, i);
string = this.spacesFromEnd(tokens) + string;
if (string !== ' !important') node.raws.important = string;
break;
} else if (token[1] === 'important') {
var cache = tokens.slice(0);
var str = '';
for (var j = i; j > 0; j--) {
var _type = cache[j][0];
if (str.trim().indexOf('!') === 0 && _type !== 'space') {
break;
}
str = cache.pop()[1] + str;
}
if (str.trim().indexOf('!') === 0) {
node.important = true;
node.raws.important = str;
tokens = cache;
}
}
if (token[0] !== 'space' && token[0] !== 'comment') {
break;
}
}
this.raw(node, 'value', tokens);
if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens);
};
Parser.prototype.atrule = function atrule(token) {
var node = new _atRule2.default();
node.name = token[1].slice(1);
if (node.name === '') {
this.unnamedAtrule(node, token);
}
this.init(node, token[2], token[3]);
var prev = void 0;
var shift = void 0;
var last = false;
var open = false;
var params = [];
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken();
if (token[0] === ';') {
node.source.end = { line: token[2], column: token[3] };
this.semicolon = true;
break;
} else if (token[0] === '{') {
open = true;
break;
} else if (token[0] === '}') {
if (params.length > 0) {
shift = params.length - 1;
prev = params[shift];
while (prev && prev[0] === 'space') {
prev = params[--shift];
}
if (prev) {
node.source.end = { line: prev[4], column: prev[5] };
}
}
this.end(token);
break;
} else {
params.push(token);
}
if (this.tokenizer.endOfFile()) {
last = true;
break;
}
}
node.raws.between = this.spacesAndCommentsFromEnd(params);
if (params.length) {
node.raws.afterName = this.spacesAndCommentsFromStart(params);
this.raw(node, 'params', params);
if (last) {
token = params[params.length - 1];
node.source.end = { line: token[4], column: token[5] };
this.spaces = node.raws.between;
node.raws.between = '';
}
} else {
node.raws.afterName = '';
node.params = '';
}
if (open) {
node.nodes = [];
this.current = node;
}
};
Parser.prototype.end = function end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.semicolon = false;
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
this.spaces = '';
if (this.current.parent) {
this.current.source.end = { line: token[2], column: token[3] };
this.current = this.current.parent;
} else {
this.unexpectedClose(token);
}
};
Parser.prototype.endFile = function endFile() {
if (this.current.parent) this.unclosedBlock();
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
};
Parser.prototype.freeSemicolon = function freeSemicolon(token) {
this.spaces += token[1];
if (this.current.nodes) {
var prev = this.current.nodes[this.current.nodes.length - 1];
if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
prev.raws.ownSemicolon = this.spaces;
this.spaces = '';
}
}
};
// Helpers
Parser.prototype.init = function init(node, line, column) {
this.current.push(node);
node.source = { start: { line: line, column: column }, input: this.input };
node.raws.before = this.spaces;
this.spaces = '';
if (node.type !== 'comment') this.semicolon = false;
};
Parser.prototype.raw = function raw(node, prop, tokens) {
var token = void 0,
type = void 0;
var length = tokens.length;
var value = '';
var clean = true;
for (var i = 0; i < length; i += 1) {
token = tokens[i];
type = token[0];
if (type === 'comment' || type === 'space' && i === length - 1) {
clean = false;
} else {
value += token[1];
}
}
if (!clean) {
var raw = tokens.reduce(function (all, i) {
return all + i[1];
}, '');
node.raws[prop] = { value: value, raw: raw };
}
node[prop] = value;
};
Parser.prototype.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
var lastTokenType = void 0;
var spaces = '';
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== 'space' && lastTokenType !== 'comment') break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
};
Parser.prototype.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
var next = void 0;
var spaces = '';
while (tokens.length) {
next = tokens[0][0];
if (next !== 'space' && next !== 'comment') break;
spaces += tokens.shift()[1];
}
return spaces;
};
Parser.prototype.spacesFromEnd = function spacesFromEnd(tokens) {
var lastTokenType = void 0;
var spaces = '';
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== 'space') break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
};
Parser.prototype.stringFrom = function stringFrom(tokens, from) {
var result = '';
for (var i = from; i < tokens.length; i++) {
result += tokens[i][1];
}
tokens.splice(from, tokens.length - from);
return result;
};
Parser.prototype.colon = function colon(tokens) {
var brackets = 0;
var token = void 0,
type = void 0,
prev = void 0;
for (var i = 0; i < tokens.length; i++) {
token = tokens[i];
type = token[0];
if (type === '(') {
brackets += 1;
} else if (type === ')') {
brackets -= 1;
} else if (brackets === 0 && type === ':') {
if (!prev) {
this.doubleColon(token);
} else if (prev[0] === 'word' && prev[1] === 'progid') {
continue;
} else {
return i;
}
}
prev = token;
}
return false;
};
// Errors
Parser.prototype.unclosedBracket = function unclosedBracket(bracket) {
throw this.input.error('Unclosed bracket', bracket[2], bracket[3]);
};
Parser.prototype.unknownWord = function unknownWord(tokens) {
throw this.input.error('Unknown word', tokens[0][2], tokens[0][3]);
};
Parser.prototype.unexpectedClose = function unexpectedClose(token) {
throw this.input.error('Unexpected }', token[2], token[3]);
};
Parser.prototype.unclosedBlock = function unclosedBlock() {
var pos = this.current.source.start;
throw this.input.error('Unclosed block', pos.line, pos.column);
};
Parser.prototype.doubleColon = function doubleColon(token) {
throw this.input.error('Double colon', token[2], token[3]);
};
Parser.prototype.unnamedAtrule = function unnamedAtrule(node, token) {
throw this.input.error('At-rule without name', token[2], token[3]);
};
Parser.prototype.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
// Hook for Safe Parser
tokens;
};
Parser.prototype.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
var colon = this.colon(tokens);
if (colon === false) return;
var founded = 0;
var token = void 0;
for (var j = colon - 1; j >= 0; j--) {
token = tokens[j];
if (token[0] !== 'space') {
founded += 1;
if (founded === 2) break;
}
}
throw this.input.error('Missed semicolon', token[2], token[3]);
};
return Parser;
}();
exports.default = Parser;
module.exports = exports['default'];
},{"./at-rule":529,"./comment":530,"./declaration":533,"./root":545,"./rule":546,"./tokenize":550}],541:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _processor = require('./processor');
var _processor2 = _interopRequireDefault(_processor);
var _stringify = require('./stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _comment = require('./comment');
var _comment2 = _interopRequireDefault(_comment);
var _atRule = require('./at-rule');
var _atRule2 = _interopRequireDefault(_atRule);
var _vendor = require('./vendor');
var _vendor2 = _interopRequireDefault(_vendor);
var _parse = require('./parse');
var _parse2 = _interopRequireDefault(_parse);
var _list = require('./list');
var _list2 = _interopRequireDefault(_list);
var _rule = require('./rule');
var _rule2 = _interopRequireDefault(_rule);
var _root = require('./root');
var _root2 = _interopRequireDefault(_root);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Create a new {@link Processor} instance that will apply `plugins`
* as CSS processors.
*
* @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
* plugins. See {@link Processor#use} for plugin format.
*
* @return {Processor} Processor to process multiple CSS
*
* @example
* import postcss from 'postcss';
*
* postcss(plugins).process(css, { from, to }).then(result => {
* console.log(result.css);
* });
*
* @namespace postcss
*/
function postcss() {
for (var _len = arguments.length, plugins = Array(_len), _key = 0; _key < _len; _key++) {
plugins[_key] = arguments[_key];
}
if (plugins.length === 1 && Array.isArray(plugins[0])) {
plugins = plugins[0];
}
return new _processor2.default(plugins);
}
/**
* Creates a PostCSS plugin with a standard API.
*
* The newly-wrapped function will provide both the name and PostCSS
* version of the plugin.
*
* ```js
* const processor = postcss([replace]);
* processor.plugins[0].postcssPlugin //=> 'postcss-replace'
* processor.plugins[0].postcssVersion //=> '5.1.0'
* ```
*
* The plugin function receives 2 arguments: {@link Root}
* and {@link Result} instance. The function should mutate the provided
* `Root` node. Alternatively, you can create a new `Root` node
* and override the `result.root` property.
*
* ```js
* const cleaner = postcss.plugin('postcss-cleaner', () => {
* return (root, result) => {
* result.root = postcss.root();
* };
* });
* ```
*
* As a convenience, plugins also expose a `process` method so that you can use
* them as standalone tools.
*
* ```js
* cleaner.process(css, processOpts, pluginOpts);
* // This is equivalent to:
* postcss([ cleaner(pluginOpts) ]).process(css, processOpts);
* ```
*
* Asynchronous plugins should return a `Promise` instance.
*
* ```js
* postcss.plugin('postcss-import', () => {
* return (root, result) => {
* return new Promise( (resolve, reject) => {
* fs.readFile('base.css', (base) => {
* root.prepend(base);
* resolve();
* });
* });
* };
* });
* ```
*
* Add warnings using the {@link Node#warn} method.
* Send data to other plugins using the {@link Result#messages} array.
*
* ```js
* postcss.plugin('postcss-caniuse-test', () => {
* return (root, result) => {
* css.walkDecls(decl => {
* if ( !caniuse.support(decl.prop) ) {
* decl.warn(result, 'Some browsers do not support ' + decl.prop);
* }
* });
* };
* });
* ```
*
* @param {string} name - PostCSS plugin name. Same as in `name`
* property in `package.json`. It will be saved
* in `plugin.postcssPlugin` property.
* @param {function} initializer - will receive plugin options
* and should return {@link pluginFunction}
*
* @return {Plugin} PostCSS plugin
*/
postcss.plugin = function plugin(name, initializer) {
var creator = function creator() {
var transformer = initializer.apply(undefined, arguments);
transformer.postcssPlugin = name;
transformer.postcssVersion = new _processor2.default().version;
return transformer;
};
var cache = void 0;
Object.defineProperty(creator, 'postcss', {
get: function get() {
if (!cache) cache = creator();
return cache;
}
});
creator.process = function (css, processOpts, pluginOpts) {
return postcss([creator(pluginOpts)]).process(css, processOpts);
};
return creator;
};
/**
* Default function to convert a node tree into a CSS string.
*
* @param {Node} node - start node for stringifing. Usually {@link Root}.
* @param {builder} builder - function to concatenate CSS from node’s parts
* or generate string and source map
*
* @return {void}
*
* @function
*/
postcss.stringify = _stringify2.default;
/**
* Parses source css and returns a new {@link Root} node,
* which contains the source CSS nodes.
*
* @param {string|toString} css - string with input CSS or any object
* with toString() method, like a Buffer
* @param {processOptions} [opts] - options with only `from` and `map` keys
*
* @return {Root} PostCSS AST
*
* @example
* // Simple CSS concatenation with source map support
* const root1 = postcss.parse(css1, { from: file1 });
* const root2 = postcss.parse(css2, { from: file2 });
* root1.append(root2).toResult().css;
*
* @function
*/
postcss.parse = _parse2.default;
/**
* @member {vendor} - Contains the {@link vendor} module.
*
* @example
* postcss.vendor.unprefixed('-moz-tab') //=> ['tab']
*/
postcss.vendor = _vendor2.default;
/**
* @member {list} - Contains the {@link list} module.
*
* @example
* postcss.list.space('5px calc(10% + 5px)') //=> ['5px', 'calc(10% + 5px)']
*/
postcss.list = _list2.default;
/**
* Creates a new {@link Comment} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {Comment} new Comment node
*
* @example
* postcss.comment({ text: 'test' })
*/
postcss.comment = function (defaults) {
return new _comment2.default(defaults);
};
/**
* Creates a new {@link AtRule} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {AtRule} new AtRule node
*
* @example
* postcss.atRule({ name: 'charset' }).toString() //=> "@charset"
*/
postcss.atRule = function (defaults) {
return new _atRule2.default(defaults);
};
/**
* Creates a new {@link Declaration} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {Declaration} new Declaration node
*
* @example
* postcss.decl({ prop: 'color', value: 'red' }).toString() //=> "color: red"
*/
postcss.decl = function (defaults) {
return new _declaration2.default(defaults);
};
/**
* Creates a new {@link Rule} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {Rule} new Rule node
*
* @example
* postcss.rule({ selector: 'a' }).toString() //=> "a {\n}"
*/
postcss.rule = function (defaults) {
return new _rule2.default(defaults);
};
/**
* Creates a new {@link Root} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {Root} new Root node
*
* @example
* postcss.root({ after: '\n' }).toString() //=> "\n"
*/
postcss.root = function (defaults) {
return new _root2.default(defaults);
};
exports.default = postcss;
module.exports = exports['default'];
},{"./at-rule":529,"./comment":530,"./declaration":533,"./list":536,"./parse":539,"./processor":543,"./root":545,"./rule":546,"./stringify":548,"./vendor":551}],542:[function(require,module,exports){
(function (Buffer){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var _sourceMap = require('source-map');
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Source map information from input CSS.
* For example, source map after Sass compiler.
*
* This class will automatically find source map in input CSS or in file system
* near input file (according `from` option).
*
* @example
* const root = postcss.parse(css, { from: 'a.sass.css' });
* root.input.map //=> PreviousMap
*/
var PreviousMap = function () {
/**
* @param {string} css - input CSS source
* @param {processOptions} [opts] - {@link Processor#process} options
*/
function PreviousMap(css, opts) {
_classCallCheck(this, PreviousMap);
this.loadAnnotation(css);
/**
* @member {boolean} - Was source map inlined by data-uri to input CSS.
*/
this.inline = this.startWith(this.annotation, 'data:');
var prev = opts.map ? opts.map.prev : undefined;
var text = this.loadMap(opts.from, prev);
if (text) this.text = text;
}
/**
* Create a instance of `SourceMapGenerator` class
* from the `source-map` library to work with source map information.
*
* It is lazy method, so it will create object only on first call
* and then it will use cache.
*
* @return {SourceMapGenerator} object with source map information
*/
PreviousMap.prototype.consumer = function consumer() {
if (!this.consumerCache) {
this.consumerCache = new _sourceMap2.default.SourceMapConsumer(this.text);
}
return this.consumerCache;
};
/**
* Does source map contains `sourcesContent` with input source text.
*
* @return {boolean} Is `sourcesContent` present
*/
PreviousMap.prototype.withContent = function withContent() {
return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
};
PreviousMap.prototype.startWith = function startWith(string, start) {
if (!string) return false;
return string.substr(0, start.length) === start;
};
PreviousMap.prototype.loadAnnotation = function loadAnnotation(css) {
var match = css.match(/\/\*\s*# sourceMappingURL=(.*)\s*\*\//);
if (match) this.annotation = match[1].trim();
};
PreviousMap.prototype.decodeInline = function decodeInline(text) {
// data:application/json;charset=utf-8;base64,
// data:application/json;charset=utf8;base64,
// data:application/json;base64,
var baseUri = /^data:application\/json;(?:charset=utf-?8;)?base64,/;
var uri = 'data:application/json,';
if (this.startWith(text, uri)) {
return decodeURIComponent(text.substr(uri.length));
} else if (baseUri.test(text)) {
return new Buffer(text.substr(RegExp.lastMatch.length), 'base64').toString();
} else {
var encoding = text.match(/data:application\/json;([^,]+),/)[1];
throw new Error('Unsupported source map encoding ' + encoding);
}
};
PreviousMap.prototype.loadMap = function loadMap(file, prev) {
if (prev === false) return false;
if (prev) {
if (typeof prev === 'string') {
return prev;
} else if (typeof prev === 'function') {
var prevPath = prev(file);
if (prevPath && _fs2.default.existsSync && _fs2.default.existsSync(prevPath)) {
return _fs2.default.readFileSync(prevPath, 'utf-8').toString().trim();
} else {
throw new Error('Unable to load previous source map: ' + prevPath.toString());
}
} else if (prev instanceof _sourceMap2.default.SourceMapConsumer) {
return _sourceMap2.default.SourceMapGenerator.fromSourceMap(prev).toString();
} else if (prev instanceof _sourceMap2.default.SourceMapGenerator) {
return prev.toString();
} else if (this.isMap(prev)) {
return JSON.stringify(prev);
} else {
throw new Error('Unsupported previous source map format: ' + prev.toString());
}
} else if (this.inline) {
return this.decodeInline(this.annotation);
} else if (this.annotation) {
var map = this.annotation;
if (file) map = _path2.default.join(_path2.default.dirname(file), map);
this.root = _path2.default.dirname(map);
if (_fs2.default.existsSync && _fs2.default.existsSync(map)) {
return _fs2.default.readFileSync(map, 'utf-8').toString().trim();
} else {
return false;
}
}
};
PreviousMap.prototype.isMap = function isMap(map) {
if ((typeof map === 'undefined' ? 'undefined' : _typeof(map)) !== 'object') return false;
return typeof map.mappings === 'string' || typeof map._mappings === 'string';
};
return PreviousMap;
}();
exports.default = PreviousMap;
module.exports = exports['default'];
}).call(this,require("buffer").Buffer)
},{"buffer":66,"fs":64,"path":523,"source-map":568}],543:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var _lazyResult = require('./lazy-result');
var _lazyResult2 = _interopRequireDefault(_lazyResult);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Contains plugins to process CSS. Create one `Processor` instance,
* initialize its plugins, and then use that instance on numerous CSS files.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.process(css1).then(result => console.log(result.css));
* processor.process(css2).then(result => console.log(result.css));
*/
var Processor = function () {
/**
* @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
* plugins. See {@link Processor#use} for plugin format.
*/
function Processor() {
var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
_classCallCheck(this, Processor);
/**
* @member {string} - Current PostCSS version.
*
* @example
* if ( result.processor.version.split('.')[0] !== '6' ) {
* throw new Error('This plugin works only with PostCSS 6');
* }
*/
this.version = '6.0.6';
/**
* @member {pluginFunction[]} - Plugins added to this processor.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.plugins.length //=> 2
*/
this.plugins = this.normalize(plugins);
}
/**
* Adds a plugin to be used as a CSS processor.
*
* PostCSS plugin can be in 4 formats:
* * A plugin created by {@link postcss.plugin} method.
* * A function. PostCSS will pass the function a @{link Root}
* as the first argument and current {@link Result} instance
* as the second.
* * An object with a `postcss` method. PostCSS will use that method
* as described in #2.
* * Another {@link Processor} instance. PostCSS will copy plugins
* from that instance into this one.
*
* Plugins can also be added by passing them as arguments when creating
* a `postcss` instance (see [`postcss(plugins)`]).
*
* Asynchronous plugins should return a `Promise` instance.
*
* @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin
* or {@link Processor}
* with plugins
*
* @example
* const processor = postcss()
* .use(autoprefixer)
* .use(precss);
*
* @return {Processes} current processor to make methods chain
*/
Processor.prototype.use = function use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]));
return this;
};
/**
* Parses source CSS and returns a {@link LazyResult} Promise proxy.
* Because some plugins can be asynchronous it doesn’t make
* any transformations. Transformations will be applied
* in the {@link LazyResult} methods.
*
* @param {string|toString|Result} css - String with input CSS or
* any object with a `toString()`
* method, like a Buffer.
* Optionally, send a {@link Result}
* instance and the processor will
* take the {@link Root} from it.
* @param {processOptions} [opts] - options
*
* @return {LazyResult} Promise proxy
*
* @example
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css);
* });
*/
Processor.prototype.process = function process(css) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return new _lazyResult2.default(this, css, opts);
};
Processor.prototype.normalize = function normalize(plugins) {
var normalized = [];
for (var _iterator = plugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
if (i.postcss) i = i.postcss;
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && Array.isArray(i.plugins)) {
normalized = normalized.concat(i.plugins);
} else if (typeof i === 'function') {
normalized.push(i);
} else if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && (i.parse || i.stringify)) {
throw new Error('PostCSS syntaxes cannot be used as plugins. ' + 'Instead, please use one of the ' + 'syntax/parser/stringifier options as ' + 'outlined in your PostCSS ' + 'runner documentation.');
} else {
throw new Error(i + ' is not a PostCSS plugin');
}
}
return normalized;
};
return Processor;
}();
exports.default = Processor;
/**
* @callback builder
* @param {string} part - part of generated CSS connected to this node
* @param {Node} node - AST node
* @param {"start"|"end"} [type] - node’s part type
*/
/**
* @callback parser
*
* @param {string|toString} css - string with input CSS or any object
* with toString() method, like a Buffer
* @param {processOptions} [opts] - options with only `from` and `map` keys
*
* @return {Root} PostCSS AST
*/
/**
* @callback stringifier
*
* @param {Node} node - start node for stringifing. Usually {@link Root}.
* @param {builder} builder - function to concatenate CSS from node’s parts
* or generate string and source map
*
* @return {void}
*/
/**
* @typedef {object} syntax
* @property {parser} parse - function to generate AST by string
* @property {stringifier} stringify - function to generate string by AST
*/
/**
* @typedef {object} toString
* @property {function} toString
*/
/**
* @callback pluginFunction
* @param {Root} root - parsed input CSS
* @param {Result} result - result to set warnings or check other plugins
*/
/**
* @typedef {object} Plugin
* @property {function} postcss - PostCSS plugin function
*/
/**
* @typedef {object} processOptions
* @property {string} from - the path of the CSS source file.
* You should always set `from`,
* because it is used in source map
* generation and syntax error messages.
* @property {string} to - the path where you’ll put the output
* CSS file. You should always set `to`
* to generate correct source maps.
* @property {parser} parser - function to generate AST by string
* @property {stringifier} stringifier - class to generate string by AST
* @property {syntax} syntax - object with `parse` and `stringify`
* @property {object} map - source map options
* @property {boolean} map.inline - does source map should
* be embedded in the output
* CSS as a base64-encoded
* comment
* @property {string|object|false|function} map.prev - source map content
* from a previous
* processing step
* (for example, Sass).
* PostCSS will try to find
* previous map
* automatically, so you
* could disable it by
* `false` value.
* @property {boolean} map.sourcesContent - does PostCSS should set
* the origin content to map
* @property {string|false} map.annotation - does PostCSS should set
* annotation comment to map
* @property {string} map.from - override `from` in map’s
* `sources`
*/
module.exports = exports['default'];
},{"./lazy-result":535}],544:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _warning = require('./warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Provides the result of the PostCSS transformations.
*
* A Result instance is returned by {@link LazyResult#then}
* or {@link Root#toResult} methods.
*
* @example
* postcss([cssnext]).process(css).then(function (result) {
* console.log(result.css);
* });
*
* @example
* var result2 = postcss.parse(css).toResult();
*/
var Result = function () {
/**
* @param {Processor} processor - processor used for this transformation.
* @param {Root} root - Root node after all transformations.
* @param {processOptions} opts - options from the {@link Processor#process}
* or {@link Root#toResult}
*/
function Result(processor, root, opts) {
_classCallCheck(this, Result);
/**
* @member {Processor} - The Processor instance used
* for this transformation.
*
* @example
* for ( let plugin of result.processor.plugins) {
* if ( plugin.postcssPlugin === 'postcss-bad' ) {
* throw 'postcss-good is incompatible with postcss-bad';
* }
* });
*/
this.processor = processor;
/**
* @member {Message[]} - Contains messages from plugins
* (e.g., warnings or custom messages).
* Each message should have type
* and plugin properties.
*
* @example
* postcss.plugin('postcss-min-browser', () => {
* return (root, result) => {
* var browsers = detectMinBrowsersByCanIUse(root);
* result.messages.push({
* type: 'min-browser',
* plugin: 'postcss-min-browser',
* browsers: browsers
* });
* };
* });
*/
this.messages = [];
/**
* @member {Root} - Root node after all transformations.
*
* @example
* root.toResult().root == root;
*/
this.root = root;
/**
* @member {processOptions} - Options from the {@link Processor#process}
* or {@link Root#toResult} call
* that produced this Result instance.
*
* @example
* root.toResult(opts).opts == opts;
*/
this.opts = opts;
/**
* @member {string} - A CSS string representing of {@link Result#root}.
*
* @example
* postcss.parse('a{}').toResult().css //=> "a{}"
*/
this.css = undefined;
/**
* @member {SourceMapGenerator} - An instance of `SourceMapGenerator`
* class from the `source-map` library,
* representing changes
* to the {@link Result#root} instance.
*
* @example
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
*
* @example
* if ( result.map ) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString());
* }
*/
this.map = undefined;
}
/**
* Returns for @{link Result#css} content.
*
* @example
* result + '' === result.css
*
* @return {string} string representing of {@link Result#root}
*/
Result.prototype.toString = function toString() {
return this.css;
};
/**
* Creates an instance of {@link Warning} and adds it
* to {@link Result#messages}.
*
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*
* @return {Warning} created warning
*/
Result.prototype.warn = function warn(text) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!opts.plugin) {
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
opts.plugin = this.lastPlugin.postcssPlugin;
}
}
var warning = new _warning2.default(text, opts);
this.messages.push(warning);
return warning;
};
/**
* Returns warnings from plugins. Filters {@link Warning} instances
* from {@link Result#messages}.
*
* @example
* result.warnings().forEach(warn => {
* console.warn(warn.toString());
* });
*
* @return {Warning[]} warnings from plugins
*/
Result.prototype.warnings = function warnings() {
return this.messages.filter(function (i) {
return i.type === 'warning';
});
};
/**
* An alias for the {@link Result#css} property.
* Use it with syntaxes that generate non-CSS output.
* @type {string}
*
* @example
* result.css === result.content;
*/
_createClass(Result, [{
key: 'content',
get: function get() {
return this.css;
}
}]);
return Result;
}();
exports.default = Result;
/**
* @typedef {object} Message
* @property {string} type - message type
* @property {string} plugin - source PostCSS plugin name
*/
module.exports = exports['default'];
},{"./warning":553}],545:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents a CSS file and contains all its parsed nodes.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{color:black} b{z-index:2}');
* root.type //=> 'root'
* root.nodes.length //=> 2
*/
var Root = function (_Container) {
_inherits(Root, _Container);
function Root(defaults) {
_classCallCheck(this, Root);
var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));
_this.type = 'root';
if (!_this.nodes) _this.nodes = [];
return _this;
}
Root.prototype.removeChild = function removeChild(child, ignore) {
var index = this.index(child);
if (!ignore && index === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[index].raws.before;
}
return _Container.prototype.removeChild.call(this, child);
};
Root.prototype.normalize = function normalize(child, sample, type) {
var nodes = _Container.prototype.normalize.call(this, child);
if (sample) {
if (type === 'prepend') {
if (this.nodes.length > 1) {
sample.raws.before = this.nodes[1].raws.before;
} else {
delete sample.raws.before;
}
} else if (this.first !== sample) {
for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
node.raws.before = sample.raws.before;
}
}
}
return nodes;
};
/**
* Returns a {@link Result} instance representing the root’s CSS.
*
* @param {processOptions} [opts] - options with only `to` and `map` keys
*
* @return {Result} result with current root’s CSS
*
* @example
* const root1 = postcss.parse(css1, { from: 'a.css' });
* const root2 = postcss.parse(css2, { from: 'b.css' });
* root1.append(root2);
* const result = root1.toResult({ to: 'all.css', map: true });
*/
Root.prototype.toResult = function toResult() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var LazyResult = require('./lazy-result');
var Processor = require('./processor');
var lazy = new LazyResult(new Processor(), this, opts);
return lazy.stringify();
};
/**
* @memberof Root#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `after`: the space symbols after the last child to the end of file.
* * `semicolon`: is the last child has an (optional) semicolon.
*
* @example
* postcss.parse('a {}\n').raws //=> { after: '\n' }
* postcss.parse('a {}').raws //=> { after: '' }
*/
return Root;
}(_container2.default);
exports.default = Root;
module.exports = exports['default'];
},{"./container":531,"./lazy-result":535,"./processor":543}],546:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
var _list = require('./list');
var _list2 = _interopRequireDefault(_list);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents a CSS rule: a selector followed by a declaration block.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{}');
* const rule = root.first;
* rule.type //=> 'rule'
* rule.toString() //=> 'a{}'
*/
var Rule = function (_Container) {
_inherits(Rule, _Container);
function Rule(defaults) {
_classCallCheck(this, Rule);
var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));
_this.type = 'rule';
if (!_this.nodes) _this.nodes = [];
return _this;
}
/**
* An array containing the rule’s individual selectors.
* Groups of selectors are split at commas.
*
* @type {string[]}
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
*
* rule.selector //=> 'a, b'
* rule.selectors //=> ['a', 'b']
*
* rule.selectors = ['a', 'strong'];
* rule.selector //=> 'a, strong'
*/
_createClass(Rule, [{
key: 'selectors',
get: function get() {
return _list2.default.comma(this.selector);
},
set: function set(values) {
var match = this.selector ? this.selector.match(/,\s*/) : null;
var sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
this.selector = values.join(sep);
}
/**
* @memberof Rule#
* @member {string} selector - the rule’s full selector represented
* as a string
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
* rule.selector //=> 'a, b'
*/
/**
* @memberof Rule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains `true` if the last child has
* an (optional) semicolon.
* * `ownSemicolon`: contains `true` if there is semicolon after rule.
*
* PostCSS cleans selectors from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
*/
}]);
return Rule;
}(_container2.default);
exports.default = Rule;
module.exports = exports['default'];
},{"./container":531,"./list":536}],547:[function(require,module,exports){
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var defaultRaw = {
colon: ': ',
indent: ' ',
beforeDecl: '\n',
beforeRule: '\n',
beforeOpen: ' ',
beforeClose: '\n',
beforeComment: '\n',
after: '\n',
emptyBody: '',
commentLeft: ' ',
commentRight: ' '
};
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
var Stringifier = function () {
function Stringifier(builder) {
_classCallCheck(this, Stringifier);
this.builder = builder;
}
Stringifier.prototype.stringify = function stringify(node, semicolon) {
this[node.type](node, semicolon);
};
Stringifier.prototype.root = function root(node) {
this.body(node);
if (node.raws.after) this.builder(node.raws.after);
};
Stringifier.prototype.comment = function comment(node) {
var left = this.raw(node, 'left', 'commentLeft');
var right = this.raw(node, 'right', 'commentRight');
this.builder('/*' + left + node.text + right + '*/', node);
};
Stringifier.prototype.decl = function decl(node, semicolon) {
var between = this.raw(node, 'between', 'colon');
var string = node.prop + between + this.rawValue(node, 'value');
if (node.important) {
string += node.raws.important || ' !important';
}
if (semicolon) string += ';';
this.builder(string, node);
};
Stringifier.prototype.rule = function rule(node) {
this.block(node, this.rawValue(node, 'selector'));
if (node.raws.ownSemicolon) {
this.builder(node.raws.ownSemicolon, node, 'end');
}
};
Stringifier.prototype.atrule = function atrule(node, semicolon) {
var name = '@' + node.name;
var params = node.params ? this.rawValue(node, 'params') : '';
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName;
} else if (params) {
name += ' ';
}
if (node.nodes) {
this.block(node, name + params);
} else {
var end = (node.raws.between || '') + (semicolon ? ';' : '');
this.builder(name + params + end, node);
}
};
Stringifier.prototype.body = function body(node) {
var last = node.nodes.length - 1;
while (last > 0) {
if (node.nodes[last].type !== 'comment') break;
last -= 1;
}
var semicolon = this.raw(node, 'semicolon');
for (var i = 0; i < node.nodes.length; i++) {
var child = node.nodes[i];
var before = this.raw(child, 'before');
if (before) this.builder(before);
this.stringify(child, last !== i || semicolon);
}
};
Stringifier.prototype.block = function block(node, start) {
var between = this.raw(node, 'between', 'beforeOpen');
this.builder(start + between + '{', node, 'start');
var after = void 0;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) this.builder(after);
this.builder('}', node, 'end');
};
Stringifier.prototype.raw = function raw(node, own, detect) {
var value = void 0;
if (!detect) detect = own;
// Already had
if (own) {
value = node.raws[own];
if (typeof value !== 'undefined') return value;
}
var parent = node.parent;
// Hack for first rule in CSS
if (detect === 'before') {
if (!parent || parent.type === 'root' && parent.first === node) {
return '';
}
}
// Floating child without parent
if (!parent) return defaultRaw[detect];
// Detect style by other nodes
var root = node.root();
if (!root.rawCache) root.rawCache = {};
if (typeof root.rawCache[detect] !== 'undefined') {
return root.rawCache[detect];
}
if (detect === 'before' || detect === 'after') {
return this.beforeAfter(node, detect);
} else {
var method = 'raw' + capitalize(detect);
if (this[method]) {
value = this[method](root, node);
} else {
root.walk(function (i) {
value = i.raws[own];
if (typeof value !== 'undefined') return false;
});
}
}
if (typeof value === 'undefined') value = defaultRaw[detect];
root.rawCache[detect] = value;
return value;
};
Stringifier.prototype.rawSemicolon = function rawSemicolon(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawEmptyBody = function rawEmptyBody(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawIndent = function rawIndent(root) {
if (root.raws.indent) return root.raws.indent;
var value = void 0;
root.walk(function (i) {
var p = i.parent;
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
var parts = i.raws.before.split('\n');
value = parts[parts.length - 1];
value = value.replace(/[^\s]/g, '');
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeComment = function rawBeforeComment(root, node) {
var value = void 0;
root.walkComments(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeDecl');
}
return value;
};
Stringifier.prototype.rawBeforeDecl = function rawBeforeDecl(root, node) {
var value = void 0;
root.walkDecls(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeRule');
}
return value;
};
Stringifier.prototype.rawBeforeRule = function rawBeforeRule(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && (i.parent !== root || root.first !== i)) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeClose = function rawBeforeClose(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeOpen = function rawBeforeOpen(root) {
var value = void 0;
root.walk(function (i) {
if (i.type !== 'decl') {
value = i.raws.between;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawColon = function rawColon(root) {
var value = void 0;
root.walkDecls(function (i) {
if (typeof i.raws.between !== 'undefined') {
value = i.raws.between.replace(/[^\s:]/g, '');
return false;
}
});
return value;
};
Stringifier.prototype.beforeAfter = function beforeAfter(node, detect) {
var value = void 0;
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl');
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment');
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule');
} else {
value = this.raw(node, null, 'beforeClose');
}
var buf = node.parent;
var depth = 0;
while (buf && buf.type !== 'root') {
depth += 1;
buf = buf.parent;
}
if (value.indexOf('\n') !== -1) {
var indent = this.raw(node, null, 'indent');
if (indent.length) {
for (var step = 0; step < depth; step++) {
value += indent;
}
}
}
return value;
};
Stringifier.prototype.rawValue = function rawValue(node, prop) {
var value = node[prop];
var raw = node.raws[prop];
if (raw && raw.value === value) {
return raw.raw;
} else {
return value;
}
};
return Stringifier;
}();
exports.default = Stringifier;
module.exports = exports['default'];
},{}],548:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.default = stringify;
var _stringifier = require('./stringifier');
var _stringifier2 = _interopRequireDefault(_stringifier);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function stringify(node, builder) {
var str = new _stringifier2.default(builder);
str.stringify(node);
}
module.exports = exports['default'];
},{"./stringifier":547}],549:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _chalk = require('chalk');
var _chalk2 = _interopRequireDefault(_chalk);
var _tokenize = require('./tokenize');
var _tokenize2 = _interopRequireDefault(_tokenize);
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var HIGHLIGHT_THEME = {
'brackets': _chalk2.default.cyan,
'at-word': _chalk2.default.cyan,
'call': _chalk2.default.cyan,
'comment': _chalk2.default.gray,
'string': _chalk2.default.green,
'class': _chalk2.default.yellow,
'hash': _chalk2.default.magenta,
'(': _chalk2.default.cyan,
')': _chalk2.default.cyan,
'{': _chalk2.default.yellow,
'}': _chalk2.default.yellow,
'[': _chalk2.default.yellow,
']': _chalk2.default.yellow,
':': _chalk2.default.yellow,
';': _chalk2.default.yellow
};
function getTokenType(_ref, processor) {
var type = _ref[0],
value = _ref[1];
if (type === 'word') {
if (value[0] === '.') {
return 'class';
}
if (value[0] === '#') {
return 'hash';
}
}
if (!processor.endOfFile()) {
var next = processor.nextToken();
processor.back(next);
if (next[0] === 'brackets' || next[0] === '(') return 'call';
}
return type;
}
function terminalHighlight(css) {
var processor = (0, _tokenize2.default)(new _input2.default(css), { ignoreErrors: true });
var result = '';
var _loop = function _loop() {
var token = processor.nextToken();
var color = HIGHLIGHT_THEME[getTokenType(token, processor)];
if (color) {
result += token[1].split(/\r?\n/).map(function (i) {
return color(i);
}).join('\n');
} else {
result += token[1];
}
};
while (!processor.endOfFile()) {
_loop();
}
return result;
}
exports.default = terminalHighlight;
module.exports = exports['default'];
},{"./input":534,"./tokenize":550,"chalk":554}],550:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.default = tokenizer;
var SINGLE_QUOTE = 39;
var DOUBLE_QUOTE = 34;
var BACKSLASH = 92;
var SLASH = 47;
var NEWLINE = 10;
var SPACE = 32;
var FEED = 12;
var TAB = 9;
var CR = 13;
var OPEN_SQUARE = 91;
var CLOSE_SQUARE = 93;
var OPEN_PARENTHESES = 40;
var CLOSE_PARENTHESES = 41;
var OPEN_CURLY = 123;
var CLOSE_CURLY = 125;
var SEMICOLON = 59;
var ASTERISK = 42;
var COLON = 58;
var AT = 64;
var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g;
var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
var RE_HEX_ESCAPE = /[a-f0-9]/i;
function tokenizer(input) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var css = input.css.valueOf();
var ignore = options.ignoreErrors;
var code = void 0,
next = void 0,
quote = void 0,
lines = void 0,
last = void 0,
content = void 0,
escape = void 0,
nextLine = void 0,
nextOffset = void 0,
escaped = void 0,
escapePos = void 0,
prev = void 0,
n = void 0,
currentToken = void 0;
var length = css.length;
var offset = -1;
var line = 1;
var pos = 0;
var buffer = [];
var returned = [];
function unclosed(what) {
throw input.error('Unclosed ' + what, line, pos - offset);
}
function endOfFile() {
return returned.length === 0 && pos >= length;
}
function nextToken() {
if (returned.length) return returned.pop();
if (pos >= length) return;
code = css.charCodeAt(pos);
if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) {
offset = pos;
line += 1;
}
switch (code) {
case NEWLINE:
case SPACE:
case TAB:
case CR:
case FEED:
next = pos;
do {
next += 1;
code = css.charCodeAt(next);
if (code === NEWLINE) {
offset = next;
line += 1;
}
} while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
currentToken = ['space', css.slice(pos, next)];
pos = next - 1;
break;
case OPEN_SQUARE:
currentToken = ['[', '[', line, pos - offset];
break;
case CLOSE_SQUARE:
currentToken = [']', ']', line, pos - offset];
break;
case OPEN_CURLY:
currentToken = ['{', '{', line, pos - offset];
break;
case CLOSE_CURLY:
currentToken = ['}', '}', line, pos - offset];
break;
case COLON:
currentToken = [':', ':', line, pos - offset];
break;
case SEMICOLON:
currentToken = [';', ';', line, pos - offset];
break;
case OPEN_PARENTHESES:
prev = buffer.length ? buffer.pop()[1] : '';
n = css.charCodeAt(pos + 1);
if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) {
next = pos;
do {
escaped = false;
next = css.indexOf(')', next + 1);
if (next === -1) {
if (ignore) {
next = pos;
break;
} else {
unclosed('bracket');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
currentToken = ['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset];
pos = next;
} else {
next = css.indexOf(')', pos + 1);
content = css.slice(pos, next + 1);
if (next === -1 || RE_BAD_BRACKET.test(content)) {
currentToken = ['(', '(', line, pos - offset];
} else {
currentToken = ['brackets', content, line, pos - offset, line, next - offset];
pos = next;
}
}
break;
case CLOSE_PARENTHESES:
currentToken = [')', ')', line, pos - offset];
break;
case SINGLE_QUOTE:
case DOUBLE_QUOTE:
quote = code === SINGLE_QUOTE ? '\'' : '"';
next = pos;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
if (ignore) {
next = pos + 1;
break;
} else {
unclosed('string');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
currentToken = ['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset];
offset = nextOffset;
line = nextLine;
pos = next;
break;
case AT:
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css);
if (RE_AT_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
currentToken = ['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];
pos = next;
break;
case BACKSLASH:
next = pos;
escape = true;
while (css.charCodeAt(next + 1) === BACKSLASH) {
next += 1;
escape = !escape;
}
code = css.charCodeAt(next + 1);
if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
next += 1;
if (RE_HEX_ESCAPE.test(css.charAt(next))) {
while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
next += 1;
}
if (css.charCodeAt(next + 1) === SPACE) {
next += 1;
}
}
}
currentToken = ['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];
pos = next;
break;
default:
if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
next = css.indexOf('*/', pos + 2) + 1;
if (next === 0) {
if (ignore) {
next = css.length;
} else {
unclosed('comment');
}
}
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
currentToken = ['comment', content, line, pos - offset, nextLine, next - nextOffset];
offset = nextOffset;
line = nextLine;
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css);
if (RE_WORD_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
currentToken = ['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];
buffer.push(currentToken);
pos = next;
}
break;
}
pos++;
return currentToken;
}
function back(token) {
returned.push(token);
}
return {
back: back,
nextToken: nextToken,
endOfFile: endOfFile
};
}
module.exports = exports['default'];
},{}],551:[function(require,module,exports){
'use strict';
exports.__esModule = true;
/**
* Contains helpers for working with vendor prefixes.
*
* @example
* const vendor = postcss.vendor;
*
* @namespace vendor
*/
var vendor = {
/**
* Returns the vendor prefix extracted from an input string.
*
* @param {string} prop - string with or without vendor prefix
*
* @return {string} vendor prefix or empty string
*
* @example
* postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
* postcss.vendor.prefix('tab-size') //=> ''
*/
prefix: function prefix(prop) {
var match = prop.match(/^(-\w+-)/);
if (match) {
return match[0];
} else {
return '';
}
},
/**
* Returns the input string stripped of its vendor prefix.
*
* @param {string} prop - string with or without vendor prefix
*
* @return {string} string name without vendor prefixes
*
* @example
* postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
*/
unprefixed: function unprefixed(prop) {
return prop.replace(/^-\w+-/, '');
}
};
exports.default = vendor;
module.exports = exports['default'];
},{}],552:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.default = warnOnce;
var printed = {};
function warnOnce(message) {
if (printed[message]) return;
printed[message] = true;
if (typeof console !== 'undefined' && console.warn) console.warn(message);
}
module.exports = exports['default'];
},{}],553:[function(require,module,exports){
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Represents a plugin’s warning. It can be created using {@link Node#warn}.
*
* @example
* if ( decl.important ) {
* decl.warn(result, 'Avoid !important', { word: '!important' });
* }
*/
var Warning = function () {
/**
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*/
function Warning(text) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Warning);
/**
* @member {string} - Type to filter warnings from
* {@link Result#messages}. Always equal
* to `"warning"`.
*
* @example
* const nonWarning = result.messages.filter(i => i.type !== 'warning')
*/
this.type = 'warning';
/**
* @member {string} - The warning message.
*
* @example
* warning.text //=> 'Try to avoid !important'
*/
this.text = text;
if (opts.node && opts.node.source) {
var pos = opts.node.positionBy(opts);
/**
* @member {number} - Line in the input file
* with this warning’s source
*
* @example
* warning.line //=> 5
*/
this.line = pos.line;
/**
* @member {number} - Column in the input file
* with this warning’s source.
*
* @example
* warning.column //=> 6
*/
this.column = pos.column;
}
for (var opt in opts) {
this[opt] = opts[opt];
}
}
/**
* Returns a warning position and message.
*
* @example
* warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
*
* @return {string} warning position and message
*/
Warning.prototype.toString = function toString() {
if (this.node) {
return this.node.error(this.text, {
plugin: this.plugin,
index: this.index,
word: this.word
}).message;
} else if (this.plugin) {
return this.plugin + ': ' + this.text;
} else {
return this.text;
}
};
/**
* @memberof Warning#
* @member {string} plugin - The name of the plugin that created
* it will fill this property automatically.
* this warning. When you call {@link Node#warn}
*
* @example
* warning.plugin //=> 'postcss-important'
*/
/**
* @memberof Warning#
* @member {Node} node - Contains the CSS node that caused the warning.
*
* @example
* warning.node.toString() //=> 'color: white !important'
*/
return Warning;
}();
exports.default = Warning;
module.exports = exports['default'];
},{}],554:[function(require,module,exports){
(function (process){
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
var ansiStyles = require('ansi-styles');
var supportsColor = require('supports-color');
var template = require('./templates.js');
var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
// `color-convert` models to exclude from the Chalk API due to conflicts and such
var skipModels = new Set(['gray']);
var styles = Object.create(null);
function applyOptions(obj, options) {
options = options || {};
// Detect level if not set manually
obj.level = options.level === undefined ? supportsColor.level : options.level;
obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
}
function Chalk(options) {
// We check for this.template here since calling chalk.constructor()
// by itself will have a `this` of a previously constructed chalk object.
if (!this || !(this instanceof Chalk) || this.template) {
var chalk = {};
applyOptions(chalk, options);
chalk.template = function () {
var args = [].slice.call(arguments);
return chalkTag.apply(null, [chalk.template].concat(args));
};
Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
chalk.template.constructor = Chalk;
return chalk.template;
}
applyOptions(this, options);
}
// Use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\x1B[94m';
}
var _loop = function _loop(key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
styles[key] = {
get: function get() {
var codes = ansiStyles[key];
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], key);
}
};
};
for (var _iterator = Object.keys(ansiStyles), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var key = _ref;
_loop(key);
}
ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
var _loop2 = function _loop2(model) {
if (skipModels.has(model)) {
return 'continue';
}
styles[model] = {
get: function get() {
var level = this.level;
return function () {
var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
var codes = {
open: open,
close: ansiStyles.color.close,
closeRe: ansiStyles.color.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
};
}
};
};
for (var _iterator2 = Object.keys(ansiStyles.color.ansi), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var model = _ref2;
var _ret2 = _loop2(model);
if (_ret2 === 'continue') continue;
}
ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
var _loop3 = function _loop3(model) {
if (skipModels.has(model)) {
return 'continue';
}
var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get: function get() {
var level = this.level;
return function () {
var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
var codes = {
open: open,
close: ansiStyles.bgColor.close,
closeRe: ansiStyles.bgColor.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
};
}
};
};
for (var _iterator3 = Object.keys(ansiStyles.bgColor.ansi), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var model = _ref3;
var _ret3 = _loop3(model);
if (_ret3 === 'continue') continue;
}
var proto = Object.defineProperties(function () {}, styles);
function build(_styles, key) {
var builder = function builder() {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
var self = this;
Object.defineProperty(builder, 'level', {
enumerable: true,
get: function get() {
return self.level;
},
set: function set(level) {
self.level = level;
}
});
Object.defineProperty(builder, 'enabled', {
enumerable: true,
get: function get() {
return self.enabled;
},
set: function set(enabled) {
self.enabled = enabled;
}
});
// See below for fix regarding invisible grey/dim combination on Windows
builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
// `__proto__` is used because we must return a function, but there is
// no way to create a function with a different prototype.
builder.__proto__ = proto; // eslint-disable-line no-proto
return builder;
}
function applyStyle() {
// Support varags, but simply cast to string in case there's only one arg
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
// Don't slice `arguments`, it prevents V8 optimizations
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || this.level <= 0 || !str) {
return str;
}
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
var originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && this.hasGrey) {
ansiStyles.dim.open = '';
}
for (var _iterator4 = this._styles.slice().reverse(), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var code = _ref4;
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
// Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS
// https://github.com/chalk/chalk/pull/92
str = str.replace(/\r?\n/g, code.close + '$&' + code.open);
}
// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
ansiStyles.dim.open = originalDim;
return str;
}
function chalkTag(chalk, strings) {
var args = [].slice.call(arguments, 2);
if (!Array.isArray(strings)) {
return strings.toString();
}
var parts = [strings.raw[0]];
for (var i = 1; i < strings.length; i++) {
parts.push(args[i - 1].toString().replace(/[{}]/g, '\\$&'));
parts.push(strings.raw[i]);
}
return template(chalk, parts.join(''));
}
Object.defineProperties(Chalk.prototype, styles);
module.exports = Chalk(); // eslint-disable-line new-cap
module.exports.supportsColor = supportsColor;
}).call(this,require('_process'))
},{"./templates.js":555,"_process":557,"ansi-styles":62,"escape-string-regexp":519,"supports-color":556}],555:[function(require,module,exports){
'use strict';
function data(parent) {
return {
styles: [],
parent: parent,
contents: []
};
}
var zeroBound = function zeroBound(n) {
return n < 0 ? 0 : n;
};
var lastIndex = function lastIndex(a) {
return zeroBound(a.length - 1);
};
var last = function last(a) {
return a[lastIndex(a)];
};
var takeWhileReverse = function takeWhileReverse(array, predicate, start) {
var out = [];
for (var i = start; i >= 0 && i <= start; i--) {
if (predicate(array[i])) {
out.unshift(array[i]);
} else {
break;
}
}
return out;
};
/**
* Checks if the character at position i in string is a normal character a.k.a a non control character.
* */
var isNormalCharacter = function isNormalCharacter(string, i) {
var char = string[i];
var backslash = '\\';
if (!(char === backslash || char === '{' || char === '}')) {
return true;
}
var n = i === 0 ? 0 : takeWhileReverse(string, function (x) {
return x === '\\';
}, zeroBound(i - 1)).length;
return n % 2 === 1;
};
var collectStyles = function collectStyles(data) {
return data ? collectStyles(data.parent).concat(data.styles) : ['reset'];
};
/**
* Computes the style for a given data based on it's style and the style of it's parent. Also accounts for !style styles
* which remove a style from the list if present.
* */
var sumStyles = function sumStyles(data) {
var negateRegex = /^~.+/;
var out = [];
for (var _iterator = collectStyles(data), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _style = _ref;
if (negateRegex.test(_style)) {
(function () {
var exclude = _style.slice(1);
out = out.filter(function (x) {
return x !== exclude;
});
})();
} else {
out.push(_style);
}
}
return out;
};
/**
* Takes a string and parses it into a tree of data objects which inherit styles from their parent.
* */
function parse(string) {
var root = data(null);
var pushingStyle = false;
var current = root;
var _loop = function _loop(i) {
var char = string[i];
var addNormalCharacter = function addNormalCharacter() {
var lastChunk = last(current.contents);
if (typeof lastChunk === 'string') {
current.contents[lastIndex(current.contents)] = lastChunk + char;
} else {
current.contents.push(char);
}
};
if (pushingStyle) {
if (' \t'.indexOf(char) > -1) {
pushingStyle = false;
} else if (char === '\n') {
pushingStyle = false;
addNormalCharacter();
} else if (char === '.') {
current.styles.push('');
} else {
current.styles[lastIndex(current.styles)] = (last(current.styles) || '') + char;
}
} else if (isNormalCharacter(string, i)) {
addNormalCharacter();
} else if (char === '{') {
pushingStyle = true;
var nCurrent = data(current);
current.contents.push(nCurrent);
current = nCurrent;
} else if (char === '}') {
current = current.parent;
}
};
for (var i = 0; i < string.length; i++) {
_loop(i);
}
if (current !== root) {
throw new Error('literal template has an unclosed block');
}
return root;
}
/**
* Takes a tree of data objects and flattens it to a list of data objects with the inherited and negations styles
* accounted for.
* */
function flatten(data) {
var flat = [];
for (var _iterator2 = data.contents, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var content = _ref2;
if (typeof content === 'string') {
flat.push({
styles: sumStyles(data),
content: content
});
} else {
flat = flat.concat(flatten(content));
}
}
return flat;
}
function assertStyle(chalk, style) {
if (!chalk[style]) {
throw new Error('invalid Chalk style: ' + style);
}
}
/**
* Checks if a given style is valid and parses style functions.
* */
function parseStyle(chalk, style) {
var fnMatch = style.match(/^\s*(\w+)\s*\(\s*([^)]*)\s*\)\s*/);
if (!fnMatch) {
assertStyle(chalk, style);
return chalk[style];
}
var name = fnMatch[1].trim();
var args = fnMatch[2].split(/,/g).map(function (s) {
return s.trim();
});
assertStyle(chalk, name);
return chalk[name].apply(chalk, args);
}
/**
* Performs the actual styling of the string, essentially lifted from cli.js.
* */
function style(chalk, flat) {
return flat.map(function (data) {
var fn = data.styles.reduce(parseStyle, chalk);
return fn(data.content.replace(/\n$/, ''));
}).join('');
}
module.exports = function (chalk, string) {
return style(chalk, flatten(parse(string)));
};
},{}],556:[function(require,module,exports){
'use strict';
module.exports = false;
},{}],557:[function(require,module,exports){
'use strict';
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) {
return [];
};
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () {
return '/';
};
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function () {
return 0;
};
},{}],558:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
var has = Object.prototype.hasOwnProperty;
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = Object.create(null);
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
ArraySet.prototype.size = function ArraySet_size() {
return Object.getOwnPropertyNames(this._set).length;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var sStr = util.toSetString(aStr);
var isDuplicate = has.call(this._set, sStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[sStr] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
var sStr = util.toSetString(aStr);
return has.call(this._set, sStr);
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
var sStr = util.toSetString(aStr);
if (has.call(this._set, sStr)) {
return this._set[sStr];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
},{"./util":567}],559:[function(require,module,exports){
"use strict";
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var base64 = require('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative ? -shifted : shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string via the out parameter.
*/
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};
},{"./base64":560}],560:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function (number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
};
/**
* Decode a single base 64 character code digit to an integer. Returns -1 on
* failure.
*/
exports.decode = function (charCode) {
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var littleA = 97; // 'a'
var littleZ = 122; // 'z'
var zero = 48; // '0'
var nine = 57; // '9'
var plus = 43; // '+'
var slash = 47; // '/'
var littleOffset = 26;
var numberOffset = 52;
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
if (bigA <= charCode && charCode <= bigZ) {
return charCode - bigA;
}
// 26 - 51: abcdefghijklmnopqrstuvwxyz
if (littleA <= charCode && charCode <= littleZ) {
return charCode - littleA + littleOffset;
}
// 52 - 61: 0123456789
if (zero <= charCode && charCode <= nine) {
return charCode - zero + numberOffset;
}
// 62: +
if (charCode == plus) {
return 62;
}
// 63: /
if (charCode == slash) {
return 63;
}
// Invalid base64 digit.
return -1;
};
},{}],561:[function(require,module,exports){
"use strict";
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
} else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
} else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};
},{}],562:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = { generatedLine: -1, generatedColumn: 0 };
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;
},{"./util":567}],563:[function(require,module,exports){
"use strict";
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
// It turns out that some (most?) JavaScript engines don't self-host
// `Array.prototype.sort`. This makes sense because C++ will likely remain
// faster than JS when doing raw CPU-intensive sorting. However, when using a
// custom comparator function, calling back and forth between the VM's C++ and
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
// worse generated code for the comparator function than would be optimal. In
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.
/**
* Swap the elements indexed by `x` and `y` in the array `ary`.
*
* @param {Array} ary
* The array.
* @param {Number} x
* The index of the first item.
* @param {Number} y
* The index of the second item.
*/
function swap(ary, x, y) {
var temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
/**
* Returns a random integer within the range `low .. high` inclusive.
*
* @param {Number} low
* The lower bound on the range.
* @param {Number} high
* The upper bound on the range.
*/
function randomIntInRange(low, high) {
return Math.round(low + Math.random() * (high - low));
}
/**
* The Quick Sort algorithm.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
* @param {Number} p
* Start index of the array
* @param {Number} r
* End index of the array
*/
function doQuickSort(ary, comparator, p, r) {
// If our lower bound is less than our upper bound, we (1) partition the
// array into two pieces and (2) recurse on each half. If it is not, this is
// the empty array and our base case.
if (p < r) {
// (1) Partitioning.
//
// The partitioning chooses a pivot between `p` and `r` and moves all
// elements that are less than or equal to the pivot to the before it, and
// all the elements that are greater than it after it. The effect is that
// once partition is done, the pivot is in the exact place it will be when
// the array is put in sorted order, and it will not need to be moved
// again. This runs in O(n) time.
// Always choose a random pivot so that an input array which is reverse
// sorted does not cause O(n^2) running time.
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
// Immediately after `j` is incremented in this loop, the following hold
// true:
//
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
//
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
// (2) Recurse on each half.
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r);
}
}
/**
* Sort the given array in-place with the given comparator function.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
*/
exports.quickSort = function (ary, comparator) {
doQuickSort(ary, comparator, 0, ary.length - 1);
};
},{}],564:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
var binarySearch = require('./binary-search');
var ArraySet = require('./array-set').ArraySet;
var base64VLQ = require('./base64-vlq');
var quickSort = require('./quick-sort').quickSort;
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap);
}
SourceMapConsumer.fromSourceMap = function (aSourceMap) {
return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function get() {
if (!this.__generatedMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function get() {
if (!this.__originalMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
var c = aStr.charAt(index);
return c === ";" || c === ",";
};
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
throw new Error("Subclasses must implement _parseMappings");
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer.LEAST_UPPER_BOUND = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source === null ? null : this._sources.at(mapping.source);
if (source != null && sourceRoot != null) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name === null ? null : this._names.at(mapping.name)
};
}, this).forEach(aCallback, context);
};
/**
* Returns all generated line and column information for the original source,
* line, and column provided. If no column is provided, returns all mappings
* corresponding to a either the line we are searching for or the next
* closest line that has any mappings. Otherwise, returns all mappings
* corresponding to the given line and either the column we are searching for
* or the next closest column that has any offsets.
*
* The only argument is an object with the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: Optional. the column number in the original source.
*
* and an array of objects is returned, each with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
var line = util.getArg(aArgs, 'line');
// When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
// returns the index of the closest mapping less than the needle. By
// setting needle.originalColumn to 0, we thus find the last mapping for
// the given line, provided such a mapping exists.
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: line,
originalColumn: util.getArg(aArgs, 'column', 0)
};
if (this.sourceRoot != null) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
if (!this._sources.has(needle.source)) {
return [];
}
needle.source = this._sources.indexOf(needle.source);
var mappings = [];
var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND);
if (index >= 0) {
var mapping = this._originalMappings[index];
if (aArgs.column === undefined) {
var originalLine = mapping.originalLine;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we found. Since
// mappings are sorted, this is guaranteed to find all mappings for
// the line we found.
while (mapping && mapping.originalLine === originalLine) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
});
mapping = this._originalMappings[++index];
}
} else {
var originalColumn = mapping.originalColumn;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we were searching for.
// Since mappings are sorted, this is guaranteed to find all mappings for
// the line we are searching for.
while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
});
mapping = this._originalMappings[++index];
}
}
}
return mappings;
};
exports.SourceMapConsumer = SourceMapConsumer;
/**
* A BasicSourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: Optional. The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function BasicSourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
sources = sources.map(String)
// Some source maps produce relative source paths like "./foo.js" instead of
// "foo.js". Normalize these first so that future comparisons will succeed.
// See bugzil.la/1090768.
.map(util.normalize)
// Always ensure that absolute sources are internally stored relative to
// the source root, if the source root is absolute. Not doing this would
// be particularly problematic when the source root is a prefix of the
// source (valid, but why??). See github issue #199 and bugzil.la/1188982.
.map(function (source) {
return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source;
});
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names.map(String), true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns BasicSourceMapConsumer
*/
BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(BasicSourceMapConsumer.prototype);
var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
smc.file = aSourceMap._file;
// Because we are modifying the entries (by converting string sources and
// names to indices into the sources and names ArraySets), we have to make
// a copy of the entry or else bad things happen. Shared mutable state
// strikes again! See github issue #191.
var generatedMappings = aSourceMap._mappings.toArray().slice();
var destGeneratedMappings = smc.__generatedMappings = [];
var destOriginalMappings = smc.__originalMappings = [];
for (var i = 0, length = generatedMappings.length; i < length; i++) {
var srcMapping = generatedMappings[i];
var destMapping = new Mapping();
destMapping.generatedLine = srcMapping.generatedLine;
destMapping.generatedColumn = srcMapping.generatedColumn;
if (srcMapping.source) {
destMapping.source = sources.indexOf(srcMapping.source);
destMapping.originalLine = srcMapping.originalLine;
destMapping.originalColumn = srcMapping.originalColumn;
if (srcMapping.name) {
destMapping.name = names.indexOf(srcMapping.name);
}
destOriginalMappings.push(destMapping);
}
destGeneratedMappings.push(destMapping);
}
quickSort(smc.__originalMappings, util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
BasicSourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
get: function get() {
return this._sources.toArray().map(function (s) {
return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
/**
* Provide the JIT with a nice shape / hidden class.
*/
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var length = aStr.length;
var index = 0;
var cachedSegments = {};
var temp = {};
var originalMappings = [];
var generatedMappings = [];
var mapping, str, segment, end, value;
while (index < length) {
if (aStr.charAt(index) === ';') {
generatedLine++;
index++;
previousGeneratedColumn = 0;
} else if (aStr.charAt(index) === ',') {
index++;
} else {
mapping = new Mapping();
mapping.generatedLine = generatedLine;
// Because each offset is encoded relative to the previous one,
// many segments often have the same encoding. We can exploit this
// fact by caching the parsed variable length fields of each segment,
// allowing us to avoid a second parse if we encounter the same
// segment again.
for (end = index; end < length; end++) {
if (this._charIsMappingSeparator(aStr, end)) {
break;
}
}
str = aStr.slice(index, end);
segment = cachedSegments[str];
if (segment) {
index += str.length;
} else {
segment = [];
while (index < end) {
base64VLQ.decode(aStr, index, temp);
value = temp.value;
index = temp.rest;
segment.push(value);
}
if (segment.length === 2) {
throw new Error('Found a source, but no line and column');
}
if (segment.length === 3) {
throw new Error('Found a source and line, but no column');
}
cachedSegments[str] = segment;
}
// Generated column.
mapping.generatedColumn = previousGeneratedColumn + segment[0];
previousGeneratedColumn = mapping.generatedColumn;
if (segment.length > 1) {
// Original source.
mapping.source = previousSource + segment[1];
previousSource += segment[1];
// Original line.
mapping.originalLine = previousOriginalLine + segment[2];
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
// Original column.
mapping.originalColumn = previousOriginalColumn + segment[3];
previousOriginalColumn = mapping.originalColumn;
if (segment.length > 4) {
// Original name.
mapping.name = previousName + segment[4];
previousName += segment[4];
}
}
generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
originalMappings.push(mapping);
}
}
}
quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
this.__generatedMappings = generatedMappings;
quickSort(originalMappings, util.compareByOriginalPositions);
this.__originalMappings = originalMappings;
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
};
/**
* Compute the last column for each generated mapping. The last column is
* inclusive.
*/
BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
for (var index = 0; index < this._generatedMappings.length; ++index) {
var mapping = this._generatedMappings[index];
// Mappings do not contain a field for the last generated columnt. We
// can come up with an optimistic estimate, however, by assuming that
// mappings are contiguous (i.e. given two consecutive mappings, the
// first mapping ends where the second one starts).
if (index + 1 < this._generatedMappings.length) {
var nextMapping = this._generatedMappings[index + 1];
if (mapping.generatedLine === nextMapping.generatedLine) {
mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
continue;
}
}
// The last mapping for each line spans the entire line.
mapping.lastGeneratedColumn = Infinity;
}
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var index = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND));
if (index >= 0) {
var mapping = this._generatedMappings[index];
if (mapping.generatedLine === needle.generatedLine) {
var source = util.getArg(mapping, 'source', null);
if (source !== null) {
source = this._sources.at(source);
if (this.sourceRoot != null) {
source = util.join(this.sourceRoot, source);
}
}
var name = util.getArg(mapping, 'name', null);
if (name !== null) {
name = this._names.at(name);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: name
};
}
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
if (!this.sourcesContent) {
return false;
}
return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) {
return sc == null;
});
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot != null) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
}
if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
// This function is used recursively from
// IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
// don't want to throw if we can't find the source - we just want to
// return null, so we provide a flag to exit gracefully.
if (nullOnMissing) {
return null;
} else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
var source = util.getArg(aArgs, 'source');
if (this.sourceRoot != null) {
source = util.relative(this.sourceRoot, source);
}
if (!this._sources.has(source)) {
return {
line: null,
column: null,
lastColumn: null
};
}
source = this._sources.indexOf(source);
var needle = {
source: source,
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND));
if (index >= 0) {
var mapping = this._originalMappings[index];
if (mapping.source === needle.source) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
};
}
}
return {
line: null,
column: null,
lastColumn: null
};
};
exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
/**
* An IndexedSourceMapConsumer instance represents a parsed source map which
* we can query for information. It differs from BasicSourceMapConsumer in
* that it takes "indexed" source maps (i.e. ones with a "sections" field) as
* input.
*
* The only parameter is a raw source map (either as a JSON string, or already
* parsed to an object). According to the spec for indexed source maps, they
* have the following attributes:
*
* - version: Which version of the source map spec this map is following.
* - file: Optional. The generated file this source map is associated with.
* - sections: A list of section definitions.
*
* Each value under the "sections" field has two fields:
* - offset: The offset into the original specified at which this section
* begins to apply, defined as an object with a "line" and "column"
* field.
* - map: A source map definition. This source map could also be indexed,
* but doesn't have to be.
*
* Instead of the "map" field, it's also possible to have a "url" field
* specifying a URL to retrieve a source map from, but that's currently
* unsupported.
*
* Here's an example source map, taken from the source map spec[0], but
* modified to omit a section which uses the "url" field.
*
* {
* version : 3,
* file: "app.js",
* sections: [{
* offset: {line:100, column:10},
* map: {
* version : 3,
* file: "section.js",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AAAA,E;;ABCDE;"
* }
* }],
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
*/
function IndexedSourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sections = util.getArg(sourceMap, 'sections');
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
this._sources = new ArraySet();
this._names = new ArraySet();
var lastOffset = {
line: -1,
column: 0
};
this._sections = sections.map(function (s) {
if (s.url) {
// The url field will require support for asynchronicity.
// See https://github.com/mozilla/source-map/issues/16
throw new Error('Support for url field in sections not implemented.');
}
var offset = util.getArg(s, 'offset');
var offsetLine = util.getArg(offset, 'line');
var offsetColumn = util.getArg(offset, 'column');
if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
throw new Error('Section offsets must be ordered and non-overlapping.');
}
lastOffset = offset;
return {
generatedOffset: {
// The offset fields are 0-based, but we use 1-based indices when
// encoding/decoding from VLQ.
generatedLine: offsetLine + 1,
generatedColumn: offsetColumn + 1
},
consumer: new SourceMapConsumer(util.getArg(s, 'map'))
};
});
}
IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
/**
* The version of the source mapping spec that we are consuming.
*/
IndexedSourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
get: function get() {
var sources = [];
for (var i = 0; i < this._sections.length; i++) {
for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
sources.push(this._sections[i].consumer.sources[j]);
}
}
return sources;
}
});
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
// Find the section containing the generated position we're trying to map
// to an original position.
var sectionIndex = binarySearch.search(needle, this._sections, function (needle, section) {
var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
if (cmp) {
return cmp;
}
return needle.generatedColumn - section.generatedOffset.generatedColumn;
});
var section = this._sections[sectionIndex];
if (!section) {
return {
source: null,
line: null,
column: null,
name: null
};
}
return section.consumer.originalPositionFor({
line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
bias: aArgs.bias
});
};
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
return this._sections.every(function (s) {
return s.consumer.hasContentsOfAllSources();
});
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
var content = section.consumer.sourceContentFor(aSource, true);
if (content) {
return content;
}
}
if (nullOnMissing) {
return null;
} else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
// Only consider this section if the requested source is in the list of
// sources of the consumer.
if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
continue;
}
var generatedPosition = section.consumer.generatedPositionFor(aArgs);
if (generatedPosition) {
var ret = {
line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
};
return ret;
}
}
return {
line: null,
column: null
};
};
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
this.__generatedMappings = [];
this.__originalMappings = [];
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
var sectionMappings = section.consumer._generatedMappings;
for (var j = 0; j < sectionMappings.length; j++) {
var mapping = sectionMappings[j];
var source = section.consumer._sources.at(mapping.source);
if (section.consumer.sourceRoot !== null) {
source = util.join(section.consumer.sourceRoot, source);
}
this._sources.add(source);
source = this._sources.indexOf(source);
var name = section.consumer._names.at(mapping.name);
this._names.add(name);
name = this._names.indexOf(name);
// The mappings coming from the consumer for the section have
// generated positions relative to the start of the section, so we
// need to offset them to be relative to the start of the concatenated
// generated file.
var adjustedMapping = {
source: source,
generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: name
};
this.__generatedMappings.push(adjustedMapping);
if (typeof adjustedMapping.originalLine === 'number') {
this.__originalMappings.push(adjustedMapping);
}
}
}
quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
quickSort(this.__originalMappings, util.compareByOriginalPositions);
};
exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
},{"./array-set":558,"./base64-vlq":559,"./binary-search":561,"./quick-sort":563,"./util":567}],565:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
var MappingList = require('./mapping-list').MappingList;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. You may pass an object with the following
* properties:
*
* - file: The filename of the generated source.
* - sourceRoot: A root for all relative URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param aSourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
var sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.');
}
sourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "sourceFile" relative if an absolute Url is passed.
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "sourceFile"
this._mappings.unsortedForEach(function (mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source);
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aSourceMapPath != null) {
sourceFile = util.join(aSourceMapPath, sourceFile);
}
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
// Case 1.
return;
} else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
// Cases 2 and 3.
return;
} else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var next;
var mapping;
var nameIdx;
var sourceIdx;
var mappings = this._mappings.toArray();
for (var i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = '';
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ';';
previousGeneratedLine++;
}
} else {
if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ',';
}
}
next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports.SourceMapGenerator = SourceMapGenerator;
},{"./array-set":558,"./base64-vlq":559,"./mapping-list":562,"./util":567}],566:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
var util = require('./util');
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
var REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
var NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
* @param aRelativePath Optional. The path that relative sources in the
* SourceMapConsumer should be relative to.
*/
SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are removed from this array, by calling `shiftNextLine`.
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var shiftNextLine = function shiftNextLine() {
var lineContents = remainingLines.shift();
// The last line of a file might not have a newline.
var newLine = remainingLines.shift() || "";
return lineContents + newLine;
};
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1,
lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLines.length > 0) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source;
node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
} else {
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length - 1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
} else {
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
} else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len - 1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
} else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
} else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null && original.line !== null && original.column !== null) {
if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
},{"./source-map-generator":565,"./util":567}],567:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port;
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = exports.isAbsolute(path);
var parts = path.split(/\/+/);
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function (aPath) {
return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
var supportsNullProto = function () {
var obj = Object.create(null);
return !('__proto__' in obj);
}();
function identity(s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return '$' + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
var length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
for (var i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
},{}],568:[function(require,module,exports){
'use strict';
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;
},{"./lib/source-map-consumer":564,"./lib/source-map-generator":565,"./lib/source-node":566}]},{},[3])(3)
}); | vendor/autoprefixer.js | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.autoprefixer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(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 s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var unpack = require('caniuse-lite').feature;
var browsersSort = function browsersSort(a, b) {
a = a.split(' ');
b = b.split(' ');
if (a[0] > b[0]) {
return 1;
} else if (a[0] < b[0]) {
return -1;
} else {
return Math.sign(parseFloat(a[1]) - parseFloat(b[1]));
}
};
// Convert Can I Use data
function f(data, opts, callback) {
data = unpack(data);
if (!callback) {
var _ref = [opts, {}];
callback = _ref[0];
opts = _ref[1];
}
var match = opts.match || /\sx($|\s)/;
var need = [];
for (var browser in data.stats) {
var versions = data.stats[browser];
for (var version in versions) {
var support = versions[version];
if (support.match(match)) {
need.push(browser + ' ' + version);
}
}
}
callback(need.sort(browsersSort));
}
// Add data for all properties
var result = {};
var prefix = function prefix(names, data) {
for (var _iterator = names, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref2;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
}
var name = _ref2;
result[name] = Object.assign({}, data);
}
};
var add = function add(names, data) {
for (var _iterator2 = names, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref3;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref3 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref3 = _i2.value;
}
var name = _ref3;
result[name].browsers = result[name].browsers.concat(data.browsers).sort(browsersSort);
}
};
module.exports = result;
// Border Radius
f(require('caniuse-lite/data/features/border-radius.js'), function (browsers) {
return prefix(['border-radius', 'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'], {
mistakes: ['-khtml-', '-ms-', '-o-'],
feature: 'border-radius',
browsers: browsers
});
});
// Box Shadow
f(require('caniuse-lite/data/features/css-boxshadow.js'), function (browsers) {
return prefix(['box-shadow'], {
mistakes: ['-khtml-'],
feature: 'css-boxshadow',
browsers: browsers
});
});
// Animation
f(require('caniuse-lite/data/features/css-animation.js'), function (browsers) {
return prefix(['animation', 'animation-name', 'animation-duration', 'animation-delay', 'animation-direction', 'animation-fill-mode', 'animation-iteration-count', 'animation-play-state', 'animation-timing-function', '@keyframes'], {
mistakes: ['-khtml-', '-ms-'],
feature: 'css-animation',
browsers: browsers
});
});
// Transition
f(require('caniuse-lite/data/features/css-transitions.js'), function (browsers) {
return prefix(['transition', 'transition-property', 'transition-duration', 'transition-delay', 'transition-timing-function'], {
mistakes: ['-khtml-', '-ms-'],
browsers: browsers,
feature: 'css-transitions'
});
});
// Transform 2D
f(require('caniuse-lite/data/features/transforms2d.js'), function (browsers) {
return prefix(['transform', 'transform-origin'], {
feature: 'transforms2d',
browsers: browsers
});
});
// Transform 3D
var transforms3d = require('caniuse-lite/data/features/transforms3d.js');
f(transforms3d, function (browsers) {
prefix(['perspective', 'perspective-origin'], {
feature: 'transforms3d',
browsers: browsers
});
return prefix(['transform-style'], {
mistakes: ['-ms-', '-o-'],
browsers: browsers,
feature: 'transforms3d'
});
});
f(transforms3d, { match: /y\sx|y\s#2/ }, function (browsers) {
return prefix(['backface-visibility'], {
mistakes: ['-ms-', '-o-'],
feature: 'transforms3d',
browsers: browsers
});
});
// Gradients
var gradients = require('caniuse-lite/data/features/css-gradients.js');
f(gradients, { match: /y\sx/ }, function (browsers) {
return prefix(['linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
mistakes: ['-ms-'],
feature: 'css-gradients',
browsers: browsers
});
});
f(gradients, { match: /a\sx/ }, function (browsers) {
browsers = browsers.map(function (i) {
if (/op/.test(i)) {
return i;
} else {
return i + ' old';
}
});
return add(['linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient'], {
feature: 'css-gradients',
browsers: browsers
});
});
// Box sizing
f(require('caniuse-lite/data/features/css3-boxsizing.js'), function (browsers) {
return prefix(['box-sizing'], {
feature: 'css3-boxsizing',
browsers: browsers
});
});
// Filter Effects
f(require('caniuse-lite/data/features/css-filters.js'), function (browsers) {
return prefix(['filter'], {
feature: 'css-filters',
browsers: browsers
});
});
// filter() function
f(require('caniuse-lite/data/features/css-filter-function.js'), function (browsers) {
return prefix(['filter-function'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
feature: 'css-filter-function',
browsers: browsers
});
});
// Backdrop-filter
f(require('caniuse-lite/data/features/css-backdrop-filter.js'), function (browsers) {
return prefix(['backdrop-filter'], {
feature: 'css-backdrop-filter',
browsers: browsers
});
});
// element() function
f(require('caniuse-lite/data/features/css-element-function.js'), function (browsers) {
return prefix(['element'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
feature: 'css-element-function',
browsers: browsers
});
});
// Multicolumns
f(require('caniuse-lite/data/features/multicolumn.js'), function (browsers) {
prefix(['columns', 'column-width', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-width'], {
feature: 'multicolumn',
browsers: browsers
});
prefix(['column-count', 'column-rule-style', 'column-span', 'column-fill', 'break-before', 'break-after', 'break-inside'], {
feature: 'multicolumn',
browsers: browsers
});
});
// User select
f(require('caniuse-lite/data/features/user-select-none.js'), function (browsers) {
return prefix(['user-select'], {
mistakes: ['-khtml-'],
feature: 'user-select-none',
browsers: browsers
});
});
// Flexible Box Layout
var flexbox = require('caniuse-lite/data/features/flexbox.js');
f(flexbox, { match: /a\sx/ }, function (browsers) {
browsers = browsers.map(function (i) {
if (/ie|firefox/.test(i)) {
return i;
} else {
return i + ' 2009';
}
});
prefix(['display-flex', 'inline-flex'], {
props: ['display'],
feature: 'flexbox',
browsers: browsers
});
prefix(['flex', 'flex-grow', 'flex-shrink', 'flex-basis'], {
feature: 'flexbox',
browsers: browsers
});
prefix(['flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content'], {
feature: 'flexbox',
browsers: browsers
});
});
f(flexbox, { match: /y\sx/ }, function (browsers) {
add(['display-flex', 'inline-flex'], {
feature: 'flexbox',
browsers: browsers
});
add(['flex', 'flex-grow', 'flex-shrink', 'flex-basis'], {
feature: 'flexbox',
browsers: browsers
});
add(['flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'order', 'align-items', 'align-self', 'align-content'], {
feature: 'flexbox',
browsers: browsers
});
});
// calc() unit
f(require('caniuse-lite/data/features/calc.js'), function (browsers) {
return prefix(['calc'], {
props: ['*'],
feature: 'calc',
browsers: browsers
});
});
// Background options
f(require('caniuse-lite/data/features/background-img-opts.js'), function (browsers) {
return prefix(['background-clip', 'background-origin', 'background-size'], {
feature: 'background-img-opts',
browsers: browsers
});
});
// Font feature settings
f(require('caniuse-lite/data/features/font-feature.js'), function (browsers) {
return prefix(['font-feature-settings', 'font-variant-ligatures', 'font-language-override'], {
feature: 'font-feature',
browsers: browsers
});
});
// CSS font-kerning property
f(require('caniuse-lite/data/features/font-kerning.js'), function (browsers) {
return prefix(['font-kerning'], {
feature: 'font-kerning',
browsers: browsers
});
});
// Border image
f(require('caniuse-lite/data/features/border-image.js'), function (browsers) {
return prefix(['border-image'], {
feature: 'border-image',
browsers: browsers
});
});
// Selection selector
f(require('caniuse-lite/data/features/css-selection.js'), function (browsers) {
return prefix(['::selection'], {
selector: true,
feature: 'css-selection',
browsers: browsers
});
});
// Placeholder selector
f(require('caniuse-lite/data/features/css-placeholder.js'), function (browsers) {
browsers = browsers.map(function (i) {
var _i$split = i.split(' '),
name = _i$split[0],
version = _i$split[1];
if (name === 'firefox' && parseFloat(version) <= 18) {
return i + ' old';
} else {
return i;
}
});
prefix(['::placeholder'], {
selector: true,
feature: 'css-placeholder',
browsers: browsers
});
});
// Hyphenation
f(require('caniuse-lite/data/features/css-hyphens.js'), function (browsers) {
return prefix(['hyphens'], {
feature: 'css-hyphens',
browsers: browsers
});
});
// Fullscreen selector
var fullscreen = require('caniuse-lite/data/features/fullscreen.js');
f(fullscreen, function (browsers) {
return prefix([':fullscreen'], {
selector: true,
feature: 'fullscreen',
browsers: browsers
});
});
f(fullscreen, { match: /x(\s#2|$)/ }, function (browsers) {
return prefix(['::backdrop'], {
selector: true,
feature: 'fullscreen',
browsers: browsers
});
});
// Tab size
f(require('caniuse-lite/data/features/css3-tabsize.js'), function (browsers) {
return prefix(['tab-size'], {
feature: 'css3-tabsize',
browsers: browsers
});
});
// Intrinsic & extrinsic sizing
f(require('caniuse-lite/data/features/intrinsic-width.js'), function (browsers) {
return prefix(['max-content', 'min-content', 'fit-content', 'fill', 'fill-available', 'stretch'], {
props: ['width', 'min-width', 'max-width', 'height', 'min-height', 'max-height', 'inline-size', 'min-inline-size', 'max-inline-size', 'block-size', 'min-block-size', 'max-block-size', 'grid', 'grid-template', 'grid-template-rows', 'grid-template-columns', 'grid-auto-columns', 'grid-auto-rows'],
feature: 'intrinsic-width',
browsers: browsers
});
});
// Zoom cursors
f(require('caniuse-lite/data/features/css3-cursors-newer.js'), function (browsers) {
return prefix(['zoom-in', 'zoom-out'], {
props: ['cursor'],
feature: 'css3-cursors-newer',
browsers: browsers
});
});
// Grab cursors
f(require('caniuse-lite/data/features/css3-cursors-grab.js'), function (browsers) {
return prefix(['grab', 'grabbing'], {
props: ['cursor'],
feature: 'css3-cursors-grab',
browsers: browsers
});
});
// Sticky position
f(require('caniuse-lite/data/features/css-sticky.js'), function (browsers) {
return prefix(['sticky'], {
props: ['position'],
feature: 'css-sticky',
browsers: browsers
});
});
// Pointer Events
f(require('caniuse-lite/data/features/pointer.js'), function (browsers) {
return prefix(['touch-action'], {
feature: 'pointer',
browsers: browsers
});
});
// Text decoration
var decoration = require('caniuse-lite/data/features/text-decoration.js');
f(decoration, function (browsers) {
return prefix(['text-decoration-style', 'text-decoration-color', 'text-decoration-line', 'text-decoration'], {
feature: 'text-decoration',
browsers: browsers
});
});
f(decoration, { match: /x.*#[23]/ }, function (browsers) {
return prefix(['text-decoration-skip'], {
feature: 'text-decoration',
browsers: browsers
});
});
// Text Size Adjust
f(require('caniuse-lite/data/features/text-size-adjust.js'), function (browsers) {
return prefix(['text-size-adjust'], {
feature: 'text-size-adjust',
browsers: browsers
});
});
// CSS Masks
f(require('caniuse-lite/data/features/css-masks.js'), function (browsers) {
prefix(['mask-clip', 'mask-composite', 'mask-image', 'mask-origin', 'mask-repeat', 'mask-border-repeat', 'mask-border-source'], {
feature: 'css-masks',
browsers: browsers
});
prefix(['mask', 'mask-position', 'mask-size', 'mask-border', 'mask-border-outset', 'mask-border-width', 'mask-border-slice'], {
feature: 'css-masks',
browsers: browsers
});
});
// CSS clip-path property
f(require('caniuse-lite/data/features/css-clip-path.js'), function (browsers) {
return prefix(['clip-path'], {
feature: 'css-clip-path',
browsers: browsers
});
});
// Fragmented Borders and Backgrounds
f(require('caniuse-lite/data/features/css-boxdecorationbreak.js'), function (browsers) {
return prefix(['box-decoration-break'], {
feature: 'css-boxdecorationbreak',
browsers: browsers
});
});
// CSS3 object-fit/object-position
f(require('caniuse-lite/data/features/object-fit.js'), function (browsers) {
return prefix(['object-fit', 'object-position'], {
feature: 'object-fit',
browsers: browsers
});
});
// CSS Shapes
f(require('caniuse-lite/data/features/css-shapes.js'), function (browsers) {
return prefix(['shape-margin', 'shape-outside', 'shape-image-threshold'], {
feature: 'css-shapes',
browsers: browsers
});
});
// CSS3 text-overflow
f(require('caniuse-lite/data/features/text-overflow.js'), function (browsers) {
return prefix(['text-overflow'], {
feature: 'text-overflow',
browsers: browsers
});
});
// Viewport at-rule
f(require('caniuse-lite/data/features/css-deviceadaptation.js'), function (browsers) {
return prefix(['@viewport'], {
feature: 'css-deviceadaptation',
browsers: browsers
});
});
// Resolution Media Queries
var resolut = require('caniuse-lite/data/features/css-media-resolution.js');
f(resolut, { match: /( x($| )|a #3)/ }, function (browsers) {
return prefix(['@resolution'], {
feature: 'css-media-resolution',
browsers: browsers
});
});
// CSS text-align-last
f(require('caniuse-lite/data/features/css-text-align-last.js'), function (browsers) {
return prefix(['text-align-last'], {
feature: 'css-text-align-last',
browsers: browsers
});
});
// Crisp Edges Image Rendering Algorithm
var crispedges = require('caniuse-lite/data/features/css-crisp-edges.js');
f(crispedges, { match: /y x|a x #1/ }, function (browsers) {
return prefix(['pixelated'], {
props: ['image-rendering'],
feature: 'css-crisp-edges',
browsers: browsers
});
});
f(crispedges, { match: /a x #2/ }, function (browsers) {
return prefix(['image-rendering'], {
feature: 'css-crisp-edges',
browsers: browsers
});
});
// Logical Properties
var logicalProps = require('caniuse-lite/data/features/css-logical-props.js');
f(logicalProps, function (browsers) {
return prefix(['border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', 'padding-inline-start', 'padding-inline-end'], {
feature: 'css-logical-props',
browsers: browsers
});
});
f(logicalProps, { match: /x\s#2/ }, function (browsers) {
return prefix(['border-block-start', 'border-block-end', 'margin-block-start', 'margin-block-end', 'padding-block-start', 'padding-block-end'], {
feature: 'css-logical-props',
browsers: browsers
});
});
// CSS appearance
var appearance = require('caniuse-lite/data/features/css-appearance.js');
f(appearance, { match: /#2|x/ }, function (browsers) {
return prefix(['appearance'], {
feature: 'css-appearance',
browsers: browsers
});
});
// CSS Scroll snap points
f(require('caniuse-lite/data/features/css-snappoints.js'), function (browsers) {
return prefix(['scroll-snap-type', 'scroll-snap-coordinate', 'scroll-snap-destination', 'scroll-snap-points-x', 'scroll-snap-points-y'], {
feature: 'css-snappoints',
browsers: browsers
});
});
// CSS Regions
f(require('caniuse-lite/data/features/css-regions.js'), function (browsers) {
return prefix(['flow-into', 'flow-from', 'region-fragment'], {
feature: 'css-regions',
browsers: browsers
});
});
// CSS image-set
f(require('caniuse-lite/data/features/css-image-set.js'), function (browsers) {
return prefix(['image-set'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
feature: 'css-image-set',
browsers: browsers
});
});
// Writing Mode
var writingMode = require('caniuse-lite/data/features/css-writing-mode.js');
f(writingMode, { match: /a|x/ }, function (browsers) {
return prefix(['writing-mode'], {
feature: 'css-writing-mode',
browsers: browsers
});
});
// Cross-Fade Function
f(require('caniuse-lite/data/features/css-cross-fade.js'), function (browsers) {
return prefix(['cross-fade'], {
props: ['background', 'background-image', 'border-image', 'mask', 'list-style', 'list-style-image', 'content', 'mask-image'],
feature: 'css-cross-fade',
browsers: browsers
});
});
// Read Only selector
f(require('caniuse-lite/data/features/css-read-only-write.js'), function (browsers) {
return prefix([':read-only', ':read-write'], {
selector: true,
feature: 'css-read-only-write',
browsers: browsers
});
});
// Text Emphasize
f(require('caniuse-lite/data/features/text-emphasis.js'), function (browsers) {
return prefix(['text-emphasis', 'text-emphasis-position', 'text-emphasis-style', 'text-emphasis-color'], {
feature: 'text-emphasis',
browsers: browsers
});
});
// CSS Grid Layout
var grid = require('caniuse-lite/data/features/css-grid.js');
f(grid, function (browsers) {
prefix(['display-grid', 'inline-grid'], {
props: ['display'],
feature: 'css-grid',
browsers: browsers
});
prefix(['grid-template-columns', 'grid-template-rows', 'grid-row-start', 'grid-column-start', 'grid-row-end', 'grid-column-end', 'grid-row', 'grid-column'], {
feature: 'css-grid',
browsers: browsers
});
});
f(grid, { match: /a x/ }, function (browsers) {
return prefix(['grid-column-align', 'grid-row-align'], {
feature: 'css-grid',
browsers: browsers
});
});
// CSS text-spacing
f(require('caniuse-lite/data/features/css-text-spacing.js'), function (browsers) {
return prefix(['text-spacing'], {
feature: 'css-text-spacing',
browsers: browsers
});
});
// :any-link selector
f(require('caniuse-lite/data/features/css-any-link.js'), function (browsers) {
return prefix([':any-link'], {
selector: true,
feature: 'css-any-link',
browsers: browsers
});
});
// unicode-bidi
var bidi = require('caniuse-lite/data/features/css-unicode-bidi.js');
f(bidi, function (browsers) {
return prefix(['isolate'], {
props: ['unicode-bidi'],
feature: 'css-unicode-bidi',
browsers: browsers
});
});
f(bidi, { match: /y x|a x #2/ }, function (browsers) {
return prefix(['plaintext'], {
props: ['unicode-bidi'],
feature: 'css-unicode-bidi',
browsers: browsers
});
});
f(bidi, { match: /y x/ }, function (browsers) {
return prefix(['isolate-override'], {
props: ['unicode-bidi'],
feature: 'css-unicode-bidi',
browsers: browsers
});
});
},{"caniuse-lite":513,"caniuse-lite/data/features/background-img-opts.js":87,"caniuse-lite/data/features/border-image.js":95,"caniuse-lite/data/features/border-radius.js":96,"caniuse-lite/data/features/calc.js":99,"caniuse-lite/data/features/css-animation.js":120,"caniuse-lite/data/features/css-any-link.js":121,"caniuse-lite/data/features/css-appearance.js":122,"caniuse-lite/data/features/css-backdrop-filter.js":125,"caniuse-lite/data/features/css-boxdecorationbreak.js":128,"caniuse-lite/data/features/css-boxshadow.js":129,"caniuse-lite/data/features/css-clip-path.js":132,"caniuse-lite/data/features/css-crisp-edges.js":135,"caniuse-lite/data/features/css-cross-fade.js":136,"caniuse-lite/data/features/css-deviceadaptation.js":139,"caniuse-lite/data/features/css-element-function.js":142,"caniuse-lite/data/features/css-filter-function.js":145,"caniuse-lite/data/features/css-filters.js":146,"caniuse-lite/data/features/css-gradients.js":154,"caniuse-lite/data/features/css-grid.js":155,"caniuse-lite/data/features/css-hyphens.js":159,"caniuse-lite/data/features/css-image-set.js":161,"caniuse-lite/data/features/css-logical-props.js":168,"caniuse-lite/data/features/css-masks.js":170,"caniuse-lite/data/features/css-media-resolution.js":173,"caniuse-lite/data/features/css-placeholder.js":187,"caniuse-lite/data/features/css-read-only-write.js":188,"caniuse-lite/data/features/css-regions.js":191,"caniuse-lite/data/features/css-selection.js":200,"caniuse-lite/data/features/css-shapes.js":201,"caniuse-lite/data/features/css-snappoints.js":202,"caniuse-lite/data/features/css-sticky.js":203,"caniuse-lite/data/features/css-text-align-last.js":206,"caniuse-lite/data/features/css-text-spacing.js":210,"caniuse-lite/data/features/css-transitions.js":214,"caniuse-lite/data/features/css-unicode-bidi.js":215,"caniuse-lite/data/features/css-writing-mode.js":219,"caniuse-lite/data/features/css3-boxsizing.js":222,"caniuse-lite/data/features/css3-cursors-grab.js":224,"caniuse-lite/data/features/css3-cursors-newer.js":225,"caniuse-lite/data/features/css3-tabsize.js":227,"caniuse-lite/data/features/flexbox.js":267,"caniuse-lite/data/features/font-feature.js":270,"caniuse-lite/data/features/font-kerning.js":271,"caniuse-lite/data/features/fullscreen.js":282,"caniuse-lite/data/features/intrinsic-width.js":330,"caniuse-lite/data/features/multicolumn.js":367,"caniuse-lite/data/features/object-fit.js":376,"caniuse-lite/data/features/pointer.js":397,"caniuse-lite/data/features/text-decoration.js":459,"caniuse-lite/data/features/text-emphasis.js":460,"caniuse-lite/data/features/text-overflow.js":461,"caniuse-lite/data/features/text-size-adjust.js":462,"caniuse-lite/data/features/transforms2d.js":471,"caniuse-lite/data/features/transforms3d.js":472,"caniuse-lite/data/features/user-select-none.js":480}],2:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Prefixer = require('./prefixer');
var AtRule = function (_Prefixer) {
_inherits(AtRule, _Prefixer);
function AtRule() {
_classCallCheck(this, AtRule);
return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments));
}
/**
* Clone and add prefixes for at-rule
*/
AtRule.prototype.add = function add(rule, prefix) {
var prefixed = prefix + rule.name;
var already = rule.parent.some(function (i) {
return i.name === prefixed && i.params === rule.params;
});
if (already) {
return undefined;
}
var cloned = this.clone(rule, { name: prefixed });
return rule.parent.insertBefore(rule, cloned);
};
/**
* Clone node with prefixes
*/
AtRule.prototype.process = function process(node) {
var parent = this.parentPrefix(node);
for (var _iterator = this.prefixes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prefix = _ref;
if (!parent || parent === prefix) {
this.add(node, prefix);
}
}
};
return AtRule;
}(Prefixer);
module.exports = AtRule;
},{"./prefixer":53}],3:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var browserslist = require('browserslist');
var postcss = require('postcss');
var Browsers = require('./browsers');
var Prefixes = require('./prefixes');
function isPlainObject(obj) {
return Object.prototype.toString.apply(obj) === '[object Object]';
}
var cache = {};
function timeCapsule(result, prefixes) {
if (prefixes.browsers.selected.length === 0) {
return;
}
if (prefixes.add.selectors.length > 0) {
return;
}
if (Object.keys(prefixes.add).length > 2) {
return;
}
result.warn('Greetings, time traveller. ' + 'We are in the golden age of prefix-less CSS, ' + 'where Autoprefixer is no longer needed for your stylesheet.');
}
module.exports = postcss.plugin('autoprefixer', function () {
for (var _len = arguments.length, reqs = Array(_len), _key = 0; _key < _len; _key++) {
reqs[_key] = arguments[_key];
}
var options = void 0;
if (reqs.length === 1 && isPlainObject(reqs[0])) {
options = reqs[0];
reqs = undefined;
} else if (reqs.length === 0 || reqs.length === 1 && !reqs[0]) {
reqs = undefined;
} else if (reqs.length <= 2 && (reqs[0] instanceof Array || !reqs[0])) {
options = reqs[1];
reqs = reqs[0];
} else if (_typeof(reqs[reqs.length - 1]) === 'object') {
options = reqs.pop();
}
if (!options) {
options = {};
}
if (options.browser) {
throw new Error('Change `browser` option to `browsers` in Autoprefixer');
}
if (options.browsers) {
reqs = options.browsers;
}
if (typeof options.grid === 'undefined') {
options.grid = false;
}
var loadPrefixes = function loadPrefixes(opts) {
var data = module.exports.data;
var browsers = new Browsers(data.browsers, reqs, opts, options.stats);
var key = browsers.selected.join(', ') + JSON.stringify(options);
if (!cache[key]) {
cache[key] = new Prefixes(data.prefixes, browsers, options);
}
return cache[key];
};
var plugin = function plugin(css, result) {
var prefixes = loadPrefixes({
from: css.source && css.source.input.file,
env: options.env
});
timeCapsule(result, prefixes);
if (options.remove !== false) {
prefixes.processor.remove(css);
}
if (options.add !== false) {
prefixes.processor.add(css, result);
}
};
plugin.options = options;
plugin.info = function (opts) {
return require('./info')(loadPrefixes(opts));
};
return plugin;
});
/**
* Autoprefixer data
*/
module.exports.data = {
browsers: require('caniuse-lite').agents,
prefixes: require('../data/prefixes')
};
/**
* Autoprefixer default browsers
*/
module.exports.defaults = browserslist.defaults;
/**
* Inspect with default Autoprefixer
*/
module.exports.info = function () {
return module.exports().info();
};
},{"../data/prefixes":1,"./browsers":5,"./info":50,"./prefixes":54,"browserslist":65,"caniuse-lite":513,"postcss":541}],4:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var last = function last(array) {
return array[array.length - 1];
};
var brackets = {
/**
* Parse string to nodes tree
*/
parse: function parse(str) {
var current = [''];
var stack = [current];
for (var i = 0; i < str.length; i++) {
var sym = str[i];
if (sym === '(') {
current = [''];
last(stack).push(current);
stack.push(current);
} else if (sym === ')') {
stack.pop();
current = last(stack);
current.push('');
} else {
current[current.length - 1] += sym;
}
}
return stack[0];
},
/**
* Generate output string by nodes tree
*/
stringify: function stringify(ast) {
var result = '';
for (var _iterator = ast, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object') {
result += '(' + brackets.stringify(i) + ')';
} else {
result += i;
}
}
return result;
}
};
module.exports = brackets;
},{}],5:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var browserslist = require('browserslist');
var utils = require('./utils');
var Browsers = function () {
/**
* Return all prefixes for default browser data
*/
Browsers.prefixes = function prefixes() {
if (this.prefixesCache) {
return this.prefixesCache;
}
var data = require('caniuse-lite').agents;
this.prefixesCache = [];
for (var name in data) {
this.prefixesCache.push('-' + data[name].prefix + '-');
}
this.prefixesCache = utils.uniq(this.prefixesCache).sort(function (a, b) {
return b.length - a.length;
});
return this.prefixesCache;
};
/**
* Check is value contain any possibe prefix
*/
Browsers.withPrefix = function withPrefix(value) {
if (!this.prefixesRegexp) {
this.prefixesRegexp = new RegExp(this.prefixes().join('|'));
}
return this.prefixesRegexp.test(value);
};
function Browsers(data, requirements, options, stats) {
_classCallCheck(this, Browsers);
this.data = data;
this.options = options || {};
this.stats = stats;
this.selected = this.parse(requirements);
}
/**
* Return browsers selected by requirements
*/
Browsers.prototype.parse = function parse(requirements) {
return browserslist(requirements, {
stats: this.stats,
path: this.options.from,
env: this.options.env
});
};
/**
* Select major browsers versions by criteria
*/
Browsers.prototype.browsers = function browsers(criteria) {
var _this = this;
var selected = [];
var _loop = function _loop(browser) {
var data = _this.data[browser];
var versions = criteria(data).map(function (version) {
return browser + ' ' + version;
});
selected = selected.concat(versions);
};
for (var browser in this.data) {
_loop(browser);
}
return selected;
};
/**
* Return prefix for selected browser
*/
Browsers.prototype.prefix = function prefix(browser) {
var _browser$split = browser.split(' '),
name = _browser$split[0],
version = _browser$split[1];
var data = this.data[name];
var prefix = data.prefix_exceptions && data.prefix_exceptions[version];
if (!prefix) {
prefix = data.prefix;
}
return '-' + prefix + '-';
};
/**
* Is browser is selected by requirements
*/
Browsers.prototype.isSelected = function isSelected(browser) {
return this.selected.indexOf(browser) !== -1;
};
return Browsers;
}();
module.exports = Browsers;
},{"./utils":60,"browserslist":65,"caniuse-lite":513}],6:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Prefixer = require('./prefixer');
var Browsers = require('./browsers');
var utils = require('./utils');
var Declaration = function (_Prefixer) {
_inherits(Declaration, _Prefixer);
function Declaration() {
_classCallCheck(this, Declaration);
return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments));
}
/**
* Always true, because we already get prefixer by property name
*/
Declaration.prototype.check = function check() /* decl */{
return true;
};
/**
* Return prefixed version of property
*/
Declaration.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + prop;
};
/**
* Return unprefixed version of property
*/
Declaration.prototype.normalize = function normalize(prop) {
return prop;
};
/**
* Check `value`, that it contain other prefixes, rather than `prefix`
*/
Declaration.prototype.otherPrefixes = function otherPrefixes(value, prefix) {
for (var _iterator = Browsers.prefixes(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var other = _ref;
if (other === prefix) {
continue;
}
if (value.indexOf(other) !== -1) {
return true;
}
}
return false;
};
/**
* Set prefix to declaration
*/
Declaration.prototype.set = function set(decl, prefix) {
decl.prop = this.prefixed(decl.prop, prefix);
return decl;
};
/**
* Should we use visual cascade for prefixes
*/
Declaration.prototype.needCascade = function needCascade(decl) {
if (!decl._autoprefixerCascade) {
decl._autoprefixerCascade = this.all.options.cascade !== false && decl.raw('before').indexOf('\n') !== -1;
}
return decl._autoprefixerCascade;
};
/**
* Return maximum length of possible prefixed property
*/
Declaration.prototype.maxPrefixed = function maxPrefixed(prefixes, decl) {
if (decl._autoprefixerMax) {
return decl._autoprefixerMax;
}
var max = 0;
for (var _iterator2 = prefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var prefix = _ref2;
prefix = utils.removeNote(prefix);
if (prefix.length > max) {
max = prefix.length;
}
}
decl._autoprefixerMax = max;
return decl._autoprefixerMax;
};
/**
* Calculate indentation to create visual cascade
*/
Declaration.prototype.calcBefore = function calcBefore(prefixes, decl) {
var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
var max = this.maxPrefixed(prefixes, decl);
var diff = max - utils.removeNote(prefix).length;
var before = decl.raw('before');
before += Array(diff).fill(' ').join('');
return before;
};
/**
* Remove visual cascade
*/
Declaration.prototype.restoreBefore = function restoreBefore(decl) {
var lines = decl.raw('before').split('\n');
var min = lines[lines.length - 1];
this.all.group(decl).up(function (prefixed) {
var array = prefixed.raw('before').split('\n');
var last = array[array.length - 1];
if (last.length < min.length) {
min = last;
}
});
lines[lines.length - 1] = min;
decl.raws.before = lines.join('\n');
};
/**
* Clone and insert new declaration
*/
Declaration.prototype.insert = function insert(decl, prefix, prefixes) {
var cloned = this.set(this.clone(decl), prefix);
if (!cloned) return undefined;
var already = decl.parent.some(function (i) {
return i.prop === cloned.prop && i.value === cloned.value;
});
if (already) {
return undefined;
}
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
return decl.parent.insertBefore(decl, cloned);
};
/**
* Did this declaration has this prefix above
*/
Declaration.prototype.isAlready = function isAlready(decl, prefixed) {
var already = this.all.group(decl).up(function (i) {
return i.prop === prefixed;
});
if (!already) {
already = this.all.group(decl).down(function (i) {
return i.prop === prefixed;
});
}
return already;
};
/**
* Clone and add prefixes for declaration
*/
Declaration.prototype.add = function add(decl, prefix, prefixes) {
var prefixed = this.prefixed(decl.prop, prefix);
if (this.isAlready(decl, prefixed) || this.otherPrefixes(decl.value, prefix)) {
return undefined;
}
return this.insert(decl, prefix, prefixes);
};
/**
* Add spaces for visual cascade
*/
Declaration.prototype.process = function process(decl) {
if (this.needCascade(decl)) {
var prefixes = _Prefixer.prototype.process.call(this, decl);
if (prefixes && prefixes.length) {
this.restoreBefore(decl);
decl.raws.before = this.calcBefore(prefixes, decl);
}
} else {
_Prefixer.prototype.process.call(this, decl);
}
};
/**
* Return list of prefixed properties to clean old prefixes
*/
Declaration.prototype.old = function old(prop, prefix) {
return [this.prefixed(prop, prefix)];
};
return Declaration;
}(Prefixer);
module.exports = Declaration;
},{"./browsers":5,"./prefixer":53,"./utils":60}],7:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var AlignContent = function (_Declaration) {
_inherits(AlignContent, _Declaration);
function AlignContent() {
_classCallCheck(this, AlignContent);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2012 spec
*/
AlignContent.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2012) {
return prefix + 'flex-line-pack';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
AlignContent.prototype.normalize = function normalize() {
return 'align-content';
};
/**
* Change value for 2012 spec and ignore prefix for 2009
*/
AlignContent.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2012) {
decl.value = AlignContent.oldValues[decl.value] || decl.value;
return _Declaration.prototype.set.call(this, decl, prefix);
} else if (spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return AlignContent;
}(Declaration);
Object.defineProperty(AlignContent, 'names', {
enumerable: true,
writable: true,
value: ['align-content', 'flex-line-pack']
});
Object.defineProperty(AlignContent, 'oldValues', {
enumerable: true,
writable: true,
value: {
'flex-end': 'end',
'flex-start': 'start',
'space-between': 'justify',
'space-around': 'distribute'
}
});
module.exports = AlignContent;
},{"../declaration":6,"./flex-spec":26}],8:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var AlignItems = function (_Declaration) {
_inherits(AlignItems, _Declaration);
function AlignItems() {
_classCallCheck(this, AlignItems);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 and 2012 specs
*/
AlignItems.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-align';
} else if (spec === 2012) {
return prefix + 'flex-align';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
AlignItems.prototype.normalize = function normalize() {
return 'align-items';
};
/**
* Change value for 2009 and 2012 specs
*/
AlignItems.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009 || spec === 2012) {
decl.value = AlignItems.oldValues[decl.value] || decl.value;
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return AlignItems;
}(Declaration);
Object.defineProperty(AlignItems, 'names', {
enumerable: true,
writable: true,
value: ['align-items', 'flex-align', 'box-align']
});
Object.defineProperty(AlignItems, 'oldValues', {
enumerable: true,
writable: true,
value: {
'flex-end': 'end',
'flex-start': 'start'
}
});
module.exports = AlignItems;
},{"../declaration":6,"./flex-spec":26}],9:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var AlignSelf = function (_Declaration) {
_inherits(AlignSelf, _Declaration);
function AlignSelf() {
_classCallCheck(this, AlignSelf);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2012 specs
*/
AlignSelf.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2012) {
return prefix + 'flex-item-align';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
AlignSelf.prototype.normalize = function normalize() {
return 'align-self';
};
/**
* Change value for 2012 spec and ignore prefix for 2009
*/
AlignSelf.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2012) {
decl.value = AlignSelf.oldValues[decl.value] || decl.value;
return _Declaration.prototype.set.call(this, decl, prefix);
} else if (spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return AlignSelf;
}(Declaration);
Object.defineProperty(AlignSelf, 'names', {
enumerable: true,
writable: true,
value: ['align-self', 'flex-item-align']
});
Object.defineProperty(AlignSelf, 'oldValues', {
enumerable: true,
writable: true,
value: {
'flex-end': 'end',
'flex-start': 'start'
}
});
module.exports = AlignSelf;
},{"../declaration":6,"./flex-spec":26}],10:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var utils = require('../utils');
var Appearance = function (_Declaration) {
_inherits(Appearance, _Declaration);
function Appearance(name, prefixes, all) {
_classCallCheck(this, Appearance);
var _this = _possibleConstructorReturn(this, _Declaration.call(this, name, prefixes, all));
if (_this.prefixes) {
_this.prefixes = utils.uniq(_this.prefixes.map(function (i) {
if (i === '-ms-') {
return '-webkit-';
} else {
return i;
}
}));
}
return _this;
}
return Appearance;
}(Declaration);
Object.defineProperty(Appearance, 'names', {
enumerable: true,
writable: true,
value: ['appearance']
});
module.exports = Appearance;
},{"../declaration":6,"../utils":60}],11:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BackgroundSize = function (_Declaration) {
_inherits(BackgroundSize, _Declaration);
function BackgroundSize() {
_classCallCheck(this, BackgroundSize);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Duplication parameter for -webkit- browsers
*/
BackgroundSize.prototype.set = function set(decl, prefix) {
var value = decl.value.toLowerCase();
if (prefix === '-webkit-' && value.indexOf(' ') === -1 && value !== 'contain' && value !== 'cover') {
decl.value = decl.value + ' ' + decl.value;
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return BackgroundSize;
}(Declaration);
Object.defineProperty(BackgroundSize, 'names', {
enumerable: true,
writable: true,
value: ['background-size']
});
module.exports = BackgroundSize;
},{"../declaration":6}],12:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BlockLogical = function (_Declaration) {
_inherits(BlockLogical, _Declaration);
function BlockLogical() {
_classCallCheck(this, BlockLogical);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Use old syntax for -moz- and -webkit-
*/
BlockLogical.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + (prop.indexOf('-start') !== -1 ? prop.replace('-block-start', '-before') : prop.replace('-block-end', '-after'));
};
/**
* Return property name by spec
*/
BlockLogical.prototype.normalize = function normalize(prop) {
if (prop.indexOf('-before') !== -1) {
return prop.replace('-before', '-block-start');
} else {
return prop.replace('-after', '-block-end');
}
};
return BlockLogical;
}(Declaration);
Object.defineProperty(BlockLogical, 'names', {
enumerable: true,
writable: true,
value: ['border-block-start', 'border-block-end', 'margin-block-start', 'margin-block-end', 'padding-block-start', 'padding-block-end', 'border-before', 'border-after', 'margin-before', 'margin-after', 'padding-before', 'padding-after']
});
module.exports = BlockLogical;
},{"../declaration":6}],13:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BorderImage = function (_Declaration) {
_inherits(BorderImage, _Declaration);
function BorderImage() {
_classCallCheck(this, BorderImage);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Remove fill parameter for prefixed declarations
*/
BorderImage.prototype.set = function set(decl, prefix) {
decl.value = decl.value.replace(/\s+fill(\s)/, '$1');
return _Declaration.prototype.set.call(this, decl, prefix);
};
return BorderImage;
}(Declaration);
Object.defineProperty(BorderImage, 'names', {
enumerable: true,
writable: true,
value: ['border-image']
});
module.exports = BorderImage;
},{"../declaration":6}],14:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BorderRadius = function (_Declaration) {
_inherits(BorderRadius, _Declaration);
function BorderRadius() {
_classCallCheck(this, BorderRadius);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change syntax, when add Mozilla prefix
*/
BorderRadius.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-moz-') {
return prefix + (BorderRadius.toMozilla[prop] || prop);
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return unprefixed version of property
*/
BorderRadius.prototype.normalize = function normalize(prop) {
return BorderRadius.toNormal[prop] || prop;
};
return BorderRadius;
}(Declaration);
Object.defineProperty(BorderRadius, 'names', {
enumerable: true,
writable: true,
value: ['border-radius']
});
Object.defineProperty(BorderRadius, 'toMozilla', {
enumerable: true,
writable: true,
value: {}
});
Object.defineProperty(BorderRadius, 'toNormal', {
enumerable: true,
writable: true,
value: {}
});
var _arr = ['top', 'bottom'];
for (var _i = 0; _i < _arr.length; _i++) {
var ver = _arr[_i];var _arr2 = ['left', 'right'];
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var hor = _arr2[_i2];
var normal = 'border-' + ver + '-' + hor + '-radius';
var mozilla = 'border-radius-' + ver + hor;
BorderRadius.names.push(normal);
BorderRadius.names.push(mozilla);
BorderRadius.toMozilla[normal] = mozilla;
BorderRadius.toNormal[mozilla] = normal;
}
}
module.exports = BorderRadius;
},{"../declaration":6}],15:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BreakProps = function (_Declaration) {
_inherits(BreakProps, _Declaration);
function BreakProps() {
_classCallCheck(this, BreakProps);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change name for -webkit- and -moz- prefix
*/
BreakProps.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-webkit-') {
return '-webkit-column-' + prop;
} else if (prefix === '-moz-') {
return 'page-' + prop;
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
BreakProps.prototype.normalize = function normalize(prop) {
if (prop.indexOf('inside') !== -1) {
return 'break-inside';
} else if (prop.indexOf('before') !== -1) {
return 'break-before';
} else if (prop.indexOf('after') !== -1) {
return 'break-after';
}
return undefined;
};
/**
* Change prefixed value for avoid-column and avoid-page
*/
BreakProps.prototype.set = function set(decl, prefix) {
var v = decl.value;
if (decl.prop === 'break-inside' && v === 'avoid-column' || v === 'avoid-page') {
decl.value = 'avoid';
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
/**
* Don’t prefix some values
*/
BreakProps.prototype.insert = function insert(decl, prefix, prefixes) {
if (decl.prop !== 'break-inside') {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
} else if (decl.value === 'avoid-region') {
return undefined;
} else if (decl.value === 'avoid-page' && prefix === '-webkit-') {
return undefined;
} else {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
}
};
return BreakProps;
}(Declaration);
Object.defineProperty(BreakProps, 'names', {
enumerable: true,
writable: true,
value: ['break-inside', 'page-break-inside', 'column-break-inside', 'break-before', 'page-break-before', 'column-break-before', 'break-after', 'page-break-after', 'column-break-after']
});
module.exports = BreakProps;
},{"../declaration":6}],16:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Value = require('../value');
var list = require('postcss/lib/list');
var CrossFade = function (_Value) {
_inherits(CrossFade, _Value);
function CrossFade() {
_classCallCheck(this, CrossFade);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
CrossFade.prototype.replace = function replace(string, prefix) {
var _this2 = this;
return list.space(string).map(function (value) {
if (value.slice(0, +_this2.name.length + 1) !== _this2.name + '(') {
return value;
}
var close = value.lastIndexOf(')');
var after = value.slice(close + 1);
var args = value.slice(_this2.name.length + 1, close);
if (prefix === '-webkit-') {
var match = args.match(/\d*.?\d+%?/);
if (match) {
args = args.slice(match[0].length).trim();
args += ', ' + match[0];
} else {
args += ', 0.5';
}
}
return prefix + _this2.name + '(' + args + ')' + after;
}).join(' ');
};
return CrossFade;
}(Value);
Object.defineProperty(CrossFade, 'names', {
enumerable: true,
writable: true,
value: ['cross-fade']
});
module.exports = CrossFade;
},{"../value":61,"postcss/lib/list":536}],17:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var OldValue = require('../old-value');
var Value = require('../value');
var DisplayFlex = function (_Value) {
_inherits(DisplayFlex, _Value);
function DisplayFlex(name, prefixes) {
_classCallCheck(this, DisplayFlex);
var _this = _possibleConstructorReturn(this, _Value.call(this, name, prefixes));
if (name === 'display-flex') {
_this.name = 'flex';
}
return _this;
}
/**
* Faster check for flex value
*/
DisplayFlex.prototype.check = function check(decl) {
return decl.prop === 'display' && decl.value === this.name;
};
/**
* Return value by spec
*/
DisplayFlex.prototype.prefixed = function prefixed(prefix) {
var spec = void 0,
value = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
if (this.name === 'flex') {
value = 'box';
} else {
value = 'inline-box';
}
} else if (spec === 2012) {
if (this.name === 'flex') {
value = 'flexbox';
} else {
value = 'inline-flexbox';
}
} else if (spec === 'final') {
value = this.name;
}
return prefix + value;
};
/**
* Add prefix to value depend on flebox spec version
*/
DisplayFlex.prototype.replace = function replace(string, prefix) {
return this.prefixed(prefix);
};
/**
* Change value for old specs
*/
DisplayFlex.prototype.old = function old(prefix) {
var prefixed = this.prefixed(prefix);
if (prefixed) {
return new OldValue(this.name, prefixed);
}
return undefined;
};
return DisplayFlex;
}(Value);
Object.defineProperty(DisplayFlex, 'names', {
enumerable: true,
writable: true,
value: ['display-flex', 'inline-flex']
});
module.exports = DisplayFlex;
},{"../old-value":52,"../value":61,"./flex-spec":26}],18:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Value = require('../value');
var DisplayGrid = function (_Value) {
_inherits(DisplayGrid, _Value);
function DisplayGrid(name, prefixes) {
_classCallCheck(this, DisplayGrid);
var _this = _possibleConstructorReturn(this, _Value.call(this, name, prefixes));
if (name === 'display-grid') {
_this.name = 'grid';
}
return _this;
}
/**
* Faster check for flex value
*/
DisplayGrid.prototype.check = function check(decl) {
return decl.prop === 'display' && decl.value === this.name;
};
return DisplayGrid;
}(Value);
Object.defineProperty(DisplayGrid, 'names', {
enumerable: true,
writable: true,
value: ['display-grid', 'inline-grid']
});
module.exports = DisplayGrid;
},{"../value":61}],19:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
var utils = require('../utils');
var OldFilterValue = function (_OldValue) {
_inherits(OldFilterValue, _OldValue);
function OldFilterValue() {
_classCallCheck(this, OldFilterValue);
return _possibleConstructorReturn(this, _OldValue.apply(this, arguments));
}
/**
* Clean -webkit-filter from properties list
*/
OldFilterValue.prototype.clean = function clean(decl) {
var _this2 = this;
decl.value = utils.editList(decl.value, function (props) {
if (props.every(function (i) {
return i.indexOf(_this2.unprefixed) !== 0;
})) {
return props;
}
return props.filter(function (i) {
return i.indexOf(_this2.prefixed) === -1;
});
});
};
return OldFilterValue;
}(OldValue);
var FilterValue = function (_Value) {
_inherits(FilterValue, _Value);
function FilterValue(name, prefixes) {
_classCallCheck(this, FilterValue);
var _this3 = _possibleConstructorReturn(this, _Value.call(this, name, prefixes));
if (name === 'filter-function') {
_this3.name = 'filter';
}
return _this3;
}
/**
* Use prefixed and unprefixed filter for WebKit
*/
FilterValue.prototype.replace = function replace(value, prefix) {
if (prefix === '-webkit-' && value.indexOf('filter(') === -1) {
if (value.indexOf('-webkit-filter') === -1) {
return _Value.prototype.replace.call(this, value, prefix) + ', ' + value;
} else {
return value;
}
} else {
return _Value.prototype.replace.call(this, value, prefix);
}
};
/**
* Clean -webkit-filter
*/
FilterValue.prototype.old = function old(prefix) {
return new OldFilterValue(this.name, prefix + this.name);
};
return FilterValue;
}(Value);
Object.defineProperty(FilterValue, 'names', {
enumerable: true,
writable: true,
value: ['filter', 'filter-function']
});
module.exports = FilterValue;
},{"../old-value":52,"../utils":60,"../value":61}],20:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var Filter = function (_Declaration) {
_inherits(Filter, _Declaration);
function Filter() {
_classCallCheck(this, Filter);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Check is it Internet Explorer filter
*/
Filter.prototype.check = function check(decl) {
var v = decl.value;
return v.toLowerCase().indexOf('alpha(') === -1 && v.indexOf('DXImageTransform.Microsoft') === -1 && v.indexOf('data:image/svg+xml') === -1;
};
return Filter;
}(Declaration);
Object.defineProperty(Filter, 'names', {
enumerable: true,
writable: true,
value: ['filter']
});
module.exports = Filter;
},{"../declaration":6}],21:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexBasis = function (_Declaration) {
_inherits(FlexBasis, _Declaration);
function FlexBasis() {
_classCallCheck(this, FlexBasis);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
FlexBasis.prototype.normalize = function normalize() {
return 'flex-basis';
};
/**
* Return flex property for 2012 spec
*/
FlexBasis.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2012) {
return prefix + 'flex-preferred-size';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Ignore 2009 spec and use flex property for 2012
*/
FlexBasis.prototype.set = function set(decl, prefix) {
var spec = void 0;
var _flexSpec2 = flexSpec(prefix);
spec = _flexSpec2[0];
prefix = _flexSpec2[1];
if (spec === 2012 || spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return FlexBasis;
}(Declaration);
Object.defineProperty(FlexBasis, 'names', {
enumerable: true,
writable: true,
value: ['flex-basis', 'flex-preferred-size']
});
module.exports = FlexBasis;
},{"../declaration":6,"./flex-spec":26}],22:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexDirection = function (_Declaration) {
_inherits(FlexDirection, _Declaration);
function FlexDirection() {
_classCallCheck(this, FlexDirection);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
FlexDirection.prototype.normalize = function normalize() {
return 'flex-direction';
};
/**
* Use two properties for 2009 spec
*/
FlexDirection.prototype.insert = function insert(decl, prefix, prefixes) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec !== 2009) {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
} else {
var already = decl.parent.some(function (i) {
return i.prop === prefix + 'box-orient' || i.prop === prefix + 'box-direction';
});
if (already) {
return undefined;
}
var value = decl.value;
var orient = value.indexOf('row') !== -1 ? 'horizontal' : 'vertical';
var dir = value.indexOf('reverse') !== -1 ? 'reverse' : 'normal';
var cloned = this.clone(decl);
cloned.prop = prefix + 'box-orient';
cloned.value = orient;
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
decl.parent.insertBefore(decl, cloned);
cloned = this.clone(decl);
cloned.prop = prefix + 'box-direction';
cloned.value = dir;
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
return decl.parent.insertBefore(decl, cloned);
}
};
/**
* Clean two properties for 2009 spec
*/
FlexDirection.prototype.old = function old(prop, prefix) {
var spec = void 0;
var _flexSpec2 = flexSpec(prefix);
spec = _flexSpec2[0];
prefix = _flexSpec2[1];
if (spec === 2009) {
return [prefix + 'box-orient', prefix + 'box-direction'];
} else {
return _Declaration.prototype.old.call(this, prop, prefix);
}
};
return FlexDirection;
}(Declaration);
Object.defineProperty(FlexDirection, 'names', {
enumerable: true,
writable: true,
value: ['flex-direction', 'box-direction', 'box-orient']
});
module.exports = FlexDirection;
},{"../declaration":6,"./flex-spec":26}],23:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexFlow = function (_Declaration) {
_inherits(FlexFlow, _Declaration);
function FlexFlow() {
_classCallCheck(this, FlexFlow);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Use two properties for 2009 spec
*/
FlexFlow.prototype.insert = function insert(decl, prefix, prefixes) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec !== 2009) {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
} else {
var values = decl.value.split(/\s+/).filter(function (i) {
return i !== 'wrap' && i !== 'nowrap' && 'wrap-reverse';
});
if (values.length === 0) {
return undefined;
}
var already = decl.parent.some(function (i) {
return i.prop === prefix + 'box-orient' || i.prop === prefix + 'box-direction';
});
if (already) {
return undefined;
}
var value = values[0];
var orient = value.indexOf('row') !== -1 ? 'horizontal' : 'vertical';
var dir = value.indexOf('reverse') !== -1 ? 'reverse' : 'normal';
var cloned = this.clone(decl);
cloned.prop = prefix + 'box-orient';
cloned.value = orient;
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
decl.parent.insertBefore(decl, cloned);
cloned = this.clone(decl);
cloned.prop = prefix + 'box-direction';
cloned.value = dir;
if (this.needCascade(decl)) {
cloned.raws.before = this.calcBefore(prefixes, decl, prefix);
}
return decl.parent.insertBefore(decl, cloned);
}
};
return FlexFlow;
}(Declaration);
Object.defineProperty(FlexFlow, 'names', {
enumerable: true,
writable: true,
value: ['flex-flow', 'box-direction', 'box-orient']
});
module.exports = FlexFlow;
},{"../declaration":6,"./flex-spec":26}],24:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var Flex = function (_Declaration) {
_inherits(Flex, _Declaration);
function Flex() {
_classCallCheck(this, Flex);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
Flex.prototype.normalize = function normalize() {
return 'flex';
};
/**
* Return flex property for 2009 and 2012 specs
*/
Flex.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-flex';
} else if (spec === 2012) {
return prefix + 'flex-positive';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
return Flex;
}(Declaration);
Object.defineProperty(Flex, 'names', {
enumerable: true,
writable: true,
value: ['flex-grow', 'flex-positive']
});
module.exports = Flex;
},{"../declaration":6,"./flex-spec":26}],25:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexShrink = function (_Declaration) {
_inherits(FlexShrink, _Declaration);
function FlexShrink() {
_classCallCheck(this, FlexShrink);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
FlexShrink.prototype.normalize = function normalize() {
return 'flex-shrink';
};
/**
* Return flex property for 2012 spec
*/
FlexShrink.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2012) {
return prefix + 'flex-negative';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Ignore 2009 spec and use flex property for 2012
*/
FlexShrink.prototype.set = function set(decl, prefix) {
var spec = void 0;
var _flexSpec2 = flexSpec(prefix);
spec = _flexSpec2[0];
prefix = _flexSpec2[1];
if (spec === 2012 || spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return FlexShrink;
}(Declaration);
Object.defineProperty(FlexShrink, 'names', {
enumerable: true,
writable: true,
value: ['flex-shrink', 'flex-negative']
});
module.exports = FlexShrink;
},{"../declaration":6,"./flex-spec":26}],26:[function(require,module,exports){
'use strict';
/**
* Return flexbox spec versions by prefix
*/
module.exports = function (prefix) {
var spec = void 0;
if (prefix === '-webkit- 2009' || prefix === '-moz-') {
spec = 2009;
} else if (prefix === '-ms-') {
spec = 2012;
} else if (prefix === '-webkit-') {
spec = 'final';
}
if (prefix === '-webkit- 2009') {
prefix = '-webkit-';
}
return [spec, prefix];
};
},{}],27:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
var FlexValues = function (_Value) {
_inherits(FlexValues, _Value);
function FlexValues() {
_classCallCheck(this, FlexValues);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
/**
* Return prefixed property name
*/
FlexValues.prototype.prefixed = function prefixed(prefix) {
return this.all.prefixed(this.name, prefix);
};
/**
* Change property name to prefixed property name
*/
FlexValues.prototype.replace = function replace(string, prefix) {
return string.replace(this.regexp(), '$1' + this.prefixed(prefix) + '$3');
};
/**
* Return function to fast prefixed property name
*/
FlexValues.prototype.old = function old(prefix) {
return new OldValue(this.name, this.prefixed(prefix));
};
return FlexValues;
}(Value);
Object.defineProperty(FlexValues, 'names', {
enumerable: true,
writable: true,
value: ['flex', 'flex-grow', 'flex-shrink', 'flex-basis']
});
module.exports = FlexValues;
},{"../old-value":52,"../value":61}],28:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var FlexWrap = function (_Declaration) {
_inherits(FlexWrap, _Declaration);
function FlexWrap() {
_classCallCheck(this, FlexWrap);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Don't add prefix for 2009 spec
*/
FlexWrap.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec !== 2009) {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return FlexWrap;
}(Declaration);
Object.defineProperty(FlexWrap, 'names', {
enumerable: true,
writable: true,
value: ['flex-wrap']
});
module.exports = FlexWrap;
},{"../declaration":6,"./flex-spec":26}],29:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var list = require('postcss/lib/list');
var Flex = function (_Declaration) {
_inherits(Flex, _Declaration);
function Flex() {
_classCallCheck(this, Flex);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 spec
*/
Flex.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-flex';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
Flex.prototype.normalize = function normalize() {
return 'flex';
};
/**
* Spec 2009 supports only first argument
* Spec 2012 disallows unitless basis
*/
Flex.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009) {
decl.value = list.space(decl.value)[0];
decl.value = Flex.oldValues[decl.value] || decl.value;
return _Declaration.prototype.set.call(this, decl, prefix);
} else if (spec === 2012) {
var components = list.space(decl.value);
if (components.length === 3 && components[2] === '0') {
decl.value = components.slice(0, 2).concat('0px').join(' ');
}
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return Flex;
}(Declaration);
Object.defineProperty(Flex, 'names', {
enumerable: true,
writable: true,
value: ['flex', 'box-flex']
});
Object.defineProperty(Flex, 'oldValues', {
enumerable: true,
writable: true,
value: {
auto: '1',
none: '0'
}
});
module.exports = Flex;
},{"../declaration":6,"./flex-spec":26,"postcss/lib/list":536}],30:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Selector = require('../selector');
var Fullscreen = function (_Selector) {
_inherits(Fullscreen, _Selector);
function Fullscreen() {
_classCallCheck(this, Fullscreen);
return _possibleConstructorReturn(this, _Selector.apply(this, arguments));
}
/**
* Return different selectors depend on prefix
*/
Fullscreen.prototype.prefixed = function prefixed(prefix) {
if (prefix === '-webkit-') {
return ':-webkit-full-screen';
} else if (prefix === '-moz-') {
return ':-moz-full-screen';
} else {
return ':' + prefix + 'fullscreen';
}
};
return Fullscreen;
}(Selector);
Object.defineProperty(Fullscreen, 'names', {
enumerable: true,
writable: true,
value: [':fullscreen']
});
module.exports = Fullscreen;
},{"../selector":57}],31:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
var utils = require('../utils');
var parser = require('postcss-value-parser');
var range = require('normalize-range');
var isDirection = /top|left|right|bottom/gi;
var Gradient = function (_Value) {
_inherits(Gradient, _Value);
function Gradient() {
var _temp, _this, _ret;
_classCallCheck(this, Gradient);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Value.call.apply(_Value, [this].concat(args))), _this), Object.defineProperty(_this, 'directions', {
enumerable: true,
writable: true,
value: {
top: 'bottom',
left: 'right',
bottom: 'top',
right: 'left'
}
}), Object.defineProperty(_this, 'oldDirections', {
enumerable: true,
writable: true,
value: {
'top': 'left bottom, left top',
'left': 'right top, left top',
'bottom': 'left top, left bottom',
'right': 'left top, right top',
'top right': 'left bottom, right top',
'top left': 'right bottom, left top',
'right top': 'left bottom, right top',
'right bottom': 'left top, right bottom',
'bottom right': 'left top, right bottom',
'bottom left': 'right top, left bottom',
'left top': 'right bottom, left top',
'left bottom': 'right top, left bottom'
}
}), _temp), _possibleConstructorReturn(_this, _ret);
}
// Direction to replace
// Direction to replace
/**
* Change degrees for webkit prefix
*/
Gradient.prototype.replace = function replace(string, prefix) {
var ast = parser(string);
for (var _iterator = ast.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
if (node.type === 'function' && node.value === this.name) {
node.nodes = this.newDirection(node.nodes);
node.nodes = this.normalize(node.nodes);
if (prefix === '-webkit- old') {
var changes = this.oldWebkit(node);
if (!changes) {
return undefined;
}
} else {
node.nodes = this.convertDirection(node.nodes);
node.value = prefix + node.value;
}
}
}
return ast.toString();
};
/**
* Replace first token
*/
Gradient.prototype.replaceFirst = function replaceFirst(params) {
for (var _len2 = arguments.length, words = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
words[_key2 - 1] = arguments[_key2];
}
var prefix = words.map(function (i) {
if (i === ' ') {
return { type: 'space', value: i };
} else {
return { type: 'word', value: i };
}
});
return prefix.concat(params.slice(1));
};
/**
* Convert angle unit to deg
*/
Gradient.prototype.normalizeUnit = function normalizeUnit(str, full) {
var num = parseFloat(str);
var deg = num / full * 360;
return deg + 'deg';
};
/**
* Normalize angle
*/
Gradient.prototype.normalize = function normalize(nodes) {
if (!nodes[0]) {
return nodes;
}
if (/-?\d+(.\d+)?grad/.test(nodes[0].value)) {
nodes[0].value = this.normalizeUnit(nodes[0].value, 400);
} else if (/-?\d+(.\d+)?rad/.test(nodes[0].value)) {
nodes[0].value = this.normalizeUnit(nodes[0].value, 2 * Math.PI);
} else if (/-?\d+(.\d+)?turn/.test(nodes[0].value)) {
nodes[0].value = this.normalizeUnit(nodes[0].value, 1);
} else if (nodes[0].value.indexOf('deg') !== -1) {
var num = parseFloat(nodes[0].value);
num = range.wrap(0, 360, num);
nodes[0].value = num + 'deg';
}
if (nodes[0].value === '0deg') {
nodes = this.replaceFirst(nodes, 'to', ' ', 'top');
} else if (nodes[0].value === '90deg') {
nodes = this.replaceFirst(nodes, 'to', ' ', 'right');
} else if (nodes[0].value === '180deg') {
nodes = this.replaceFirst(nodes, 'to', ' ', 'bottom');
} else if (nodes[0].value === '270deg') {
nodes = this.replaceFirst(nodes, 'to', ' ', 'left');
}
return nodes;
};
/**
* Replace old direction to new
*/
Gradient.prototype.newDirection = function newDirection(params) {
if (params[0].value === 'to') {
return params;
}
if (!isDirection.test(params[0].value)) {
return params;
}
params.unshift({
type: 'word',
value: 'to'
}, {
type: 'space',
value: ' '
});
for (var i = 2; i < params.length; i++) {
if (params[i].type === 'div') {
break;
}
if (params[i].type === 'word') {
params[i].value = this.revertDirection(params[i].value);
}
}
return params;
};
/**
* Change new direction to old
*/
Gradient.prototype.convertDirection = function convertDirection(params) {
if (params.length > 0) {
if (params[0].value === 'to') {
this.fixDirection(params);
} else if (params[0].value.indexOf('deg') !== -1) {
this.fixAngle(params);
} else if (params[2].value === 'at') {
this.fixRadial(params);
}
}
return params;
};
/**
* Replace `to top left` to `bottom right`
*/
Gradient.prototype.fixDirection = function fixDirection(params) {
params.splice(0, 2);
for (var _iterator2 = params, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var param = _ref2;
if (param.type === 'div') {
break;
}
if (param.type === 'word') {
param.value = this.revertDirection(param.value);
}
}
};
/**
* Add 90 degrees
*/
Gradient.prototype.fixAngle = function fixAngle(params) {
var first = params[0].value;
first = parseFloat(first);
first = Math.abs(450 - first) % 360;
first = this.roundFloat(first, 3);
params[0].value = first + 'deg';
};
/**
* Fix radial direction syntax
*/
Gradient.prototype.fixRadial = function fixRadial(params) {
var first = params[0];
var second = [];
var i = void 0;
for (i = 4; i < params.length; i++) {
if (params[i].type === 'div') {
break;
} else {
second.push(params[i]);
}
}
params.splice.apply(params, [0, i].concat(second, [params[i + 2], first]));
};
Gradient.prototype.revertDirection = function revertDirection(word) {
return this.directions[word.toLowerCase()] || word;
};
/**
* Round float and save digits under dot
*/
Gradient.prototype.roundFloat = function roundFloat(float, digits) {
return parseFloat(float.toFixed(digits));
};
/**
* Convert to old webkit syntax
*/
Gradient.prototype.oldWebkit = function oldWebkit(node) {
var nodes = node.nodes;
var string = parser.stringify(node.nodes);
if (this.name !== 'linear-gradient') {
return false;
}
if (nodes[0] && nodes[0].value.indexOf('deg') !== -1) {
return false;
}
if (string.indexOf('px') !== -1) {
return false;
}
if (string.indexOf('-corner') !== -1) {
return false;
}
if (string.indexOf('-side') !== -1) {
return false;
}
var params = [[]];
for (var _iterator3 = nodes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var i = _ref3;
params[params.length - 1].push(i);
if (i.type === 'div' && i.value === ',') {
params.push([]);
}
}
this.oldDirection(params);
this.colorStops(params);
node.nodes = [];
for (var _iterator4 = params, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var param = _ref4;
node.nodes = node.nodes.concat(param);
}
node.nodes.unshift({ type: 'word', value: 'linear' }, this.cloneDiv(node.nodes));
node.value = '-webkit-gradient';
return true;
};
/**
* Change direction syntax to old webkit
*/
Gradient.prototype.oldDirection = function oldDirection(params) {
var div = this.cloneDiv(params[0]);
if (params[0][0].value !== 'to') {
return params.unshift([{ type: 'word', value: this.oldDirections.bottom }, div]);
} else {
var _words = [];
for (var _iterator5 = params[0].slice(2), _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var node = _ref5;
if (node.type === 'word') {
_words.push(node.value.toLowerCase());
}
}
_words = _words.join(' ');
var old = this.oldDirections[_words] || _words;
params[0] = [{ type: 'word', value: old }, div];
return params[0];
}
};
/**
* Get div token from exists parameters
*/
Gradient.prototype.cloneDiv = function cloneDiv(params) {
for (var _iterator6 = params, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref6;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref6 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref6 = _i6.value;
}
var i = _ref6;
if (i.type === 'div' && i.value === ',') {
return i;
}
}
return { type: 'div', value: ',', after: ' ' };
};
/**
* Change colors syntax to old webkit
*/
Gradient.prototype.colorStops = function colorStops(params) {
var result = [];
for (var i = 0; i < params.length; i++) {
var pos = void 0;
var param = params[i];
var item = void 0;
if (i === 0) {
continue;
}
var color = parser.stringify(param[0]);
if (param[1] && param[1].type === 'word') {
pos = param[1].value;
} else if (param[2] && param[2].type === 'word') {
pos = param[2].value;
}
var stop = void 0;
if (i === 1 && (!pos || pos === '0%')) {
stop = 'from(' + color + ')';
} else if (i === params.length - 1 && (!pos || pos === '100%')) {
stop = 'to(' + color + ')';
} else if (pos) {
stop = 'color-stop(' + pos + ', ' + color + ')';
} else {
stop = 'color-stop(' + color + ')';
}
var div = param[param.length - 1];
params[i] = [{ type: 'word', value: stop }];
if (div.type === 'div' && div.value === ',') {
item = params[i].push(div);
}
result.push(item);
}
return result;
};
/**
* Remove old WebKit gradient too
*/
Gradient.prototype.old = function old(prefix) {
if (prefix === '-webkit-') {
var type = this.name === 'linear-gradient' ? 'linear' : 'radial';
var string = '-gradient';
var regexp = utils.regexp('-webkit-(' + type + '-gradient|gradient\\(\\s*' + type + ')', false);
return new OldValue(this.name, prefix + this.name, string, regexp);
} else {
return _Value.prototype.old.call(this, prefix);
}
};
/**
* Do not add non-webkit prefixes for list-style and object
*/
Gradient.prototype.add = function add(decl, prefix) {
var p = decl.prop;
if (p.indexOf('mask') !== -1) {
if (prefix === '-webkit-' || prefix === '-webkit- old') {
return _Value.prototype.add.call(this, decl, prefix);
}
} else if (p === 'list-style' || p === 'list-style-image' || p === 'content') {
if (prefix === '-webkit-' || prefix === '-webkit- old') {
return _Value.prototype.add.call(this, decl, prefix);
}
} else {
return _Value.prototype.add.call(this, decl, prefix);
}
return undefined;
};
return Gradient;
}(Value);
Object.defineProperty(Gradient, 'names', {
enumerable: true,
writable: true,
value: ['linear-gradient', 'repeating-linear-gradient', 'radial-gradient', 'repeating-radial-gradient']
});
module.exports = Gradient;
},{"../old-value":52,"../utils":60,"../value":61,"normalize-range":521,"postcss-value-parser":524}],32:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var GridColumnAlign = function (_Declaration) {
_inherits(GridColumnAlign, _Declaration);
function GridColumnAlign() {
_classCallCheck(this, GridColumnAlign);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not prefix flexbox values
*/
GridColumnAlign.prototype.check = function check(decl) {
return decl.value.indexOf('flex-') === -1 && decl.value !== 'baseline';
};
/**
* Change property name for IE
*/
GridColumnAlign.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + 'grid-column-align';
};
/**
* Change IE property back
*/
GridColumnAlign.prototype.normalize = function normalize() {
return 'justify-self';
};
return GridColumnAlign;
}(Declaration);
Object.defineProperty(GridColumnAlign, 'names', {
enumerable: true,
writable: true,
value: ['grid-column-align']
});
module.exports = GridColumnAlign;
},{"../declaration":6}],33:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var GridEnd = function (_Declaration) {
_inherits(GridEnd, _Declaration);
function GridEnd() {
_classCallCheck(this, GridEnd);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not add prefix for unsupported value in IE
*/
GridEnd.prototype.check = function check(decl) {
return decl.value.indexOf('span') !== -1;
};
/**
* Return a final spec property
*/
GridEnd.prototype.normalize = function normalize(prop) {
return prop.replace(/(-span|-end)/, '');
};
/**
* Change property name for IE
*/
GridEnd.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return prefix + prop.replace('-end', '-span');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Change repeating syntax for IE
*/
GridEnd.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-') {
decl.value = decl.value.replace(/span\s/i, '');
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return GridEnd;
}(Declaration);
Object.defineProperty(GridEnd, 'names', {
enumerable: true,
writable: true,
value: ['grid-row-end', 'grid-column-end', 'grid-row-span', 'grid-column-span']
});
module.exports = GridEnd;
},{"../declaration":6}],34:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var GridRowAlign = function (_Declaration) {
_inherits(GridRowAlign, _Declaration);
function GridRowAlign() {
_classCallCheck(this, GridRowAlign);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not prefix flexbox values
*/
GridRowAlign.prototype.check = function check(decl) {
return decl.value.indexOf('flex-') === -1 && decl.value !== 'baseline';
};
/**
* Change property name for IE
*/
GridRowAlign.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + 'grid-row-align';
};
/**
* Change IE property back
*/
GridRowAlign.prototype.normalize = function normalize() {
return 'align-self';
};
return GridRowAlign;
}(Declaration);
Object.defineProperty(GridRowAlign, 'names', {
enumerable: true,
writable: true,
value: ['grid-row-align']
});
module.exports = GridRowAlign;
},{"../declaration":6}],35:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var GridStart = function (_Declaration) {
_inherits(GridStart, _Declaration);
function GridStart() {
_classCallCheck(this, GridStart);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not add prefix for unsupported value in IE
*/
GridStart.prototype.check = function check(decl) {
return decl.value.indexOf('/') === -1 || decl.value.indexOf('span') !== -1;
};
/**
* Return a final spec property
*/
GridStart.prototype.normalize = function normalize(prop) {
return prop.replace('-start', '');
};
/**
* Change property name for IE
*/
GridStart.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return prefix + prop.replace('-start', '');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Split one value to two
*/
GridStart.prototype.insert = function insert(decl, prefix, prefixes) {
var parts = this.splitValue(decl, prefix);
if (parts.length === 2) {
decl.cloneBefore({
prop: '-ms-' + decl.prop + '-span',
value: parts[1]
});
}
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
};
/**
* Change value for combine property
*/
GridStart.prototype.set = function set(decl, prefix) {
var parts = this.splitValue(decl, prefix);
if (parts.length === 2) {
decl.value = parts[0];
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
/**
* If property contains start and end
*/
GridStart.prototype.splitValue = function splitValue(decl, prefix) {
if (prefix === '-ms-' && decl.prop.indexOf('-start') === -1) {
var parts = decl.value.split(/\s*\/\s*span\s+/);
if (parts.length === 2) {
return parts;
}
}
return false;
};
return GridStart;
}(Declaration);
Object.defineProperty(GridStart, 'names', {
enumerable: true,
writable: true,
value: ['grid-row-start', 'grid-column-start', 'grid-row', 'grid-column']
});
module.exports = GridStart;
},{"../declaration":6}],36:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var parser = require('postcss-value-parser');
var Declaration = require('../declaration');
var GridTemplate = function (_Declaration) {
_inherits(GridTemplate, _Declaration);
function GridTemplate() {
_classCallCheck(this, GridTemplate);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for IE
*/
GridTemplate.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return prefix + prop.replace('template-', '');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Change IE property back
*/
GridTemplate.prototype.normalize = function normalize(prop) {
return prop.replace(/^grid-(rows|columns)/, 'grid-template-$1');
};
/**
* Recursive part of changeRepeat
*/
GridTemplate.prototype.walkRepeat = function walkRepeat(node) {
var fixed = [];
for (var _iterator = node.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
if (i.nodes) {
this.walkRepeat(i);
}
fixed.push(i);
if (i.type === 'function' && i.value === 'repeat') {
var first = i.nodes.shift();
if (first) {
var count = first.value;
i.nodes.shift();
i.value = '';
fixed.push({ type: 'word', value: '[' + count + ']' });
}
}
}
node.nodes = fixed;
};
/**
* IE repeating syntax
*/
GridTemplate.prototype.changeRepeat = function changeRepeat(value) {
var ast = parser(value);
this.walkRepeat(ast);
return ast.toString();
};
/**
* Change repeating syntax for IE
*/
GridTemplate.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-' && decl.value.indexOf('repeat(') !== -1) {
decl.value = this.changeRepeat(decl.value);
}
return _Declaration.prototype.set.call(this, decl, prefix);
};
return GridTemplate;
}(Declaration);
Object.defineProperty(GridTemplate, 'names', {
enumerable: true,
writable: true,
value: ['grid-template-rows', 'grid-template-columns', 'grid-rows', 'grid-columns']
});
module.exports = GridTemplate;
},{"../declaration":6,"postcss-value-parser":524}],37:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var ImageRendering = function (_Declaration) {
_inherits(ImageRendering, _Declaration);
function ImageRendering() {
_classCallCheck(this, ImageRendering);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Add hack only for crisp-edges
*/
ImageRendering.prototype.check = function check(decl) {
return decl.value === 'pixelated';
};
/**
* Change property name for IE
*/
ImageRendering.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-ms-') {
return '-ms-interpolation-mode';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Change property and value for IE
*/
ImageRendering.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-') {
decl.prop = '-ms-interpolation-mode';
decl.value = 'nearest-neighbor';
return decl;
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
/**
* Return property name by spec
*/
ImageRendering.prototype.normalize = function normalize() {
return 'image-rendering';
};
/**
* Warn on old value
*/
ImageRendering.prototype.process = function process(node, result) {
return _Declaration.prototype.process.call(this, node, result);
};
return ImageRendering;
}(Declaration);
Object.defineProperty(ImageRendering, 'names', {
enumerable: true,
writable: true,
value: ['image-rendering', 'interpolation-mode']
});
module.exports = ImageRendering;
},{"../declaration":6}],38:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Value = require('../value');
var ImageSet = function (_Value) {
_inherits(ImageSet, _Value);
function ImageSet() {
_classCallCheck(this, ImageSet);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
/**
* Use non-standard name for WebKit and Firefox
*/
ImageSet.prototype.replace = function replace(string, prefix) {
if (prefix === '-webkit-') {
return _Value.prototype.replace.call(this, string, prefix).replace(/("[^"]+"|'[^']+')(\s+\d+\w)/gi, 'url($1)$2');
} else {
return _Value.prototype.replace.call(this, string, prefix);
}
};
return ImageSet;
}(Value);
Object.defineProperty(ImageSet, 'names', {
enumerable: true,
writable: true,
value: ['image-set']
});
module.exports = ImageSet;
},{"../value":61}],39:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var InlineLogical = function (_Declaration) {
_inherits(InlineLogical, _Declaration);
function InlineLogical() {
_classCallCheck(this, InlineLogical);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Use old syntax for -moz- and -webkit-
*/
InlineLogical.prototype.prefixed = function prefixed(prop, prefix) {
return prefix + prop.replace('-inline', '');
};
/**
* Return property name by spec
*/
InlineLogical.prototype.normalize = function normalize(prop) {
return prop.replace(/(margin|padding|border)-(start|end)/, '$1-inline-$2');
};
return InlineLogical;
}(Declaration);
Object.defineProperty(InlineLogical, 'names', {
enumerable: true,
writable: true,
value: ['border-inline-start', 'border-inline-end', 'margin-inline-start', 'margin-inline-end', 'padding-inline-start', 'padding-inline-end', 'border-start', 'border-end', 'margin-start', 'margin-end', 'padding-start', 'padding-end']
});
module.exports = InlineLogical;
},{"../declaration":6}],40:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
function _regexp(name) {
return new RegExp('(^|[\\s,(])(' + name + '($|[\\s),]))', 'gi');
}
var Intrinsic = function (_Value) {
_inherits(Intrinsic, _Value);
function Intrinsic() {
_classCallCheck(this, Intrinsic);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
Intrinsic.prototype.regexp = function regexp() {
if (!this.regexpCache) this.regexpCache = _regexp(this.name);
return this.regexpCache;
};
Intrinsic.prototype.isStretch = function isStretch() {
return this.name === 'stretch' || this.name === 'fill' || this.name === 'fill-available';
};
Intrinsic.prototype.replace = function replace(string, prefix) {
if (prefix === '-moz-' && this.isStretch()) {
return string.replace(this.regexp(), '$1-moz-available$3');
} else if (prefix === '-webkit-' && this.isStretch()) {
return string.replace(this.regexp(), '$1-webkit-fill-available$3');
} else {
return _Value.prototype.replace.call(this, string, prefix);
}
};
Intrinsic.prototype.old = function old(prefix) {
var prefixed = prefix + this.name;
if (this.isStretch()) {
if (prefix === '-moz-') {
prefixed = '-moz-available';
} else if (prefix === '-webkit-') {
prefixed = '-webkit-fill-available';
}
}
return new OldValue(this.name, prefixed, prefixed, _regexp(prefixed));
};
Intrinsic.prototype.add = function add(decl, prefix) {
if (decl.prop.indexOf('grid') !== -1 && prefix !== '-webkit-') {
return undefined;
}
return _Value.prototype.add.call(this, decl, prefix);
};
return Intrinsic;
}(Value);
Object.defineProperty(Intrinsic, 'names', {
enumerable: true,
writable: true,
value: ['max-content', 'min-content', 'fit-content', 'fill', 'fill-available', 'stretch']
});
module.exports = Intrinsic;
},{"../old-value":52,"../value":61}],41:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var JustifyContent = function (_Declaration) {
_inherits(JustifyContent, _Declaration);
function JustifyContent() {
_classCallCheck(this, JustifyContent);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 and 2012 specs
*/
JustifyContent.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-pack';
} else if (spec === 2012) {
return prefix + 'flex-pack';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
JustifyContent.prototype.normalize = function normalize() {
return 'justify-content';
};
/**
* Change value for 2009 and 2012 specs
*/
JustifyContent.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009 || spec === 2012) {
var value = JustifyContent.oldValues[decl.value] || decl.value;
decl.value = value;
if (spec !== 2009 || value !== 'distribute') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
} else if (spec === 'final') {
return _Declaration.prototype.set.call(this, decl, prefix);
}
return undefined;
};
return JustifyContent;
}(Declaration);
Object.defineProperty(JustifyContent, 'names', {
enumerable: true,
writable: true,
value: ['justify-content', 'flex-pack', 'box-pack']
});
Object.defineProperty(JustifyContent, 'oldValues', {
enumerable: true,
writable: true,
value: {
'flex-end': 'end',
'flex-start': 'start',
'space-between': 'justify',
'space-around': 'distribute'
}
});
module.exports = JustifyContent;
},{"../declaration":6,"./flex-spec":26}],42:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var MaskBorder = function (_Declaration) {
_inherits(MaskBorder, _Declaration);
function MaskBorder() {
_classCallCheck(this, MaskBorder);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Return property name by final spec
*/
MaskBorder.prototype.normalize = function normalize() {
return this.name.replace('box-image', 'border');
};
/**
* Return flex property for 2012 spec
*/
MaskBorder.prototype.prefixed = function prefixed(prop, prefix) {
if (prefix === '-webkit-') {
return _Declaration.prototype.prefixed.call(this, prop, prefix).replace('border', 'box-image');
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
return MaskBorder;
}(Declaration);
Object.defineProperty(MaskBorder, 'names', {
enumerable: true,
writable: true,
value: ['mask-border', 'mask-border-source', 'mask-border-slice', 'mask-border-width', 'mask-border-outset', 'mask-border-repeat', 'mask-box-image', 'mask-box-image-source', 'mask-box-image-slice', 'mask-box-image-width', 'mask-box-image-outset', 'mask-box-image-repeat']
});
module.exports = MaskBorder;
},{"../declaration":6}],43:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var flexSpec = require('./flex-spec');
var Declaration = require('../declaration');
var Order = function (_Declaration) {
_inherits(Order, _Declaration);
function Order() {
_classCallCheck(this, Order);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Change property name for 2009 and 2012 specs
*/
Order.prototype.prefixed = function prefixed(prop, prefix) {
var spec = void 0;
var _flexSpec = flexSpec(prefix);
spec = _flexSpec[0];
prefix = _flexSpec[1];
if (spec === 2009) {
return prefix + 'box-ordinal-group';
} else if (spec === 2012) {
return prefix + 'flex-order';
} else {
return _Declaration.prototype.prefixed.call(this, prop, prefix);
}
};
/**
* Return property name by final spec
*/
Order.prototype.normalize = function normalize() {
return 'order';
};
/**
* Fix value for 2009 spec
*/
Order.prototype.set = function set(decl, prefix) {
var spec = flexSpec(prefix)[0];
if (spec === 2009 && /\d/.test(decl.value)) {
decl.value = (parseInt(decl.value) + 1).toString();
return _Declaration.prototype.set.call(this, decl, prefix);
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
return Order;
}(Declaration);
Object.defineProperty(Order, 'names', {
enumerable: true,
writable: true,
value: ['order', 'flex-order', 'box-ordinal-group']
});
module.exports = Order;
},{"../declaration":6,"./flex-spec":26}],44:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldValue = require('../old-value');
var Value = require('../value');
var Pixelated = function (_Value) {
_inherits(Pixelated, _Value);
function Pixelated() {
_classCallCheck(this, Pixelated);
return _possibleConstructorReturn(this, _Value.apply(this, arguments));
}
/**
* Use non-standard name for WebKit and Firefox
*/
Pixelated.prototype.replace = function replace(string, prefix) {
if (prefix === '-webkit-') {
return string.replace(this.regexp(), '$1-webkit-optimize-contrast');
} else if (prefix === '-moz-') {
return string.replace(this.regexp(), '$1-moz-crisp-edges');
} else {
return _Value.prototype.replace.call(this, string, prefix);
}
};
/**
* Different name for WebKit and Firefox
*/
Pixelated.prototype.old = function old(prefix) {
if (prefix === '-webkit-') {
return new OldValue(this.name, '-webkit-optimize-contrast');
} else if (prefix === '-moz-') {
return new OldValue(this.name, '-moz-crisp-edges');
} else {
return _Value.prototype.old.call(this, prefix);
}
};
return Pixelated;
}(Value);
Object.defineProperty(Pixelated, 'names', {
enumerable: true,
writable: true,
value: ['pixelated']
});
module.exports = Pixelated;
},{"../old-value":52,"../value":61}],45:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Selector = require('../selector');
var Placeholder = function (_Selector) {
_inherits(Placeholder, _Selector);
function Placeholder() {
_classCallCheck(this, Placeholder);
return _possibleConstructorReturn(this, _Selector.apply(this, arguments));
}
/**
* Add old mozilla to possible prefixes
*/
Placeholder.prototype.possible = function possible() {
return _Selector.prototype.possible.call(this).concat('-moz- old');
};
/**
* Return different selectors depend on prefix
*/
Placeholder.prototype.prefixed = function prefixed(prefix) {
if (prefix === '-webkit-') {
return '::-webkit-input-placeholder';
} else if (prefix === '-ms-') {
return ':-ms-input-placeholder';
} else if (prefix === '-moz- old') {
return ':-moz-placeholder';
} else {
return '::' + prefix + 'placeholder';
}
};
return Placeholder;
}(Selector);
Object.defineProperty(Placeholder, 'names', {
enumerable: true,
writable: true,
value: [':placeholder-shown', '::placeholder']
});
module.exports = Placeholder;
},{"../selector":57}],46:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var BASIC = ['none', 'underline', 'overline', 'line-through', 'blink', 'inherit', 'initial', 'unset'];
var TextDecoration = function (_Declaration) {
_inherits(TextDecoration, _Declaration);
function TextDecoration() {
_classCallCheck(this, TextDecoration);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Do not add prefixes for basic values.
*/
TextDecoration.prototype.check = function check(decl) {
return decl.value.split(/\s+/).some(function (i) {
return BASIC.indexOf(i) === -1;
});
};
return TextDecoration;
}(Declaration);
Object.defineProperty(TextDecoration, 'names', {
enumerable: true,
writable: true,
value: ['text-decoration']
});
module.exports = TextDecoration;
},{"../declaration":6}],47:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var TextEmphasisPosition = function (_Declaration) {
_inherits(TextEmphasisPosition, _Declaration);
function TextEmphasisPosition() {
_classCallCheck(this, TextEmphasisPosition);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
TextEmphasisPosition.prototype.set = function set(decl, prefix) {
if (prefix === '-webkit-') {
decl.value = decl.value.replace(/\s*(right|left)\s*/i, '');
return _Declaration.prototype.set.call(this, decl, prefix);
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
return TextEmphasisPosition;
}(Declaration);
Object.defineProperty(TextEmphasisPosition, 'names', {
enumerable: true,
writable: true,
value: ['text-emphasis-position']
});
module.exports = TextEmphasisPosition;
},{"../declaration":6}],48:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var TransformDecl = function (_Declaration) {
_inherits(TransformDecl, _Declaration);
function TransformDecl() {
_classCallCheck(this, TransformDecl);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
/**
* Recursively check all parents for @keyframes
*/
TransformDecl.prototype.keyframeParents = function keyframeParents(decl) {
var parent = decl.parent;
while (parent) {
if (parent.type === 'atrule' && parent.name === 'keyframes') {
return true;
}
var _parent = parent;
parent = _parent.parent;
}
return false;
};
/**
* Is transform caontain 3D commands
*/
TransformDecl.prototype.contain3d = function contain3d(decl) {
if (decl.prop === 'transform-origin') {
return false;
}
for (var _iterator = TransformDecl.functions3d, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var func = _ref;
if (decl.value.indexOf(func + '(') !== -1) {
return true;
}
}
return false;
};
/**
* Replace rotateZ to rotate for IE 9
*/
TransformDecl.prototype.set = function set(decl, prefix) {
decl = _Declaration.prototype.set.call(this, decl, prefix);
if (prefix === '-ms-') {
decl.value = decl.value.replace(/rotateZ/gi, 'rotate');
}
return decl;
};
/**
* Don't add prefix for IE in keyframes
*/
TransformDecl.prototype.insert = function insert(decl, prefix, prefixes) {
if (prefix === '-ms-') {
if (!this.contain3d(decl) && !this.keyframeParents(decl)) {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
}
} else if (prefix === '-o-') {
if (!this.contain3d(decl)) {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
}
} else {
return _Declaration.prototype.insert.call(this, decl, prefix, prefixes);
}
return undefined;
};
return TransformDecl;
}(Declaration);
Object.defineProperty(TransformDecl, 'names', {
enumerable: true,
writable: true,
value: ['transform', 'transform-origin']
});
Object.defineProperty(TransformDecl, 'functions3d', {
enumerable: true,
writable: true,
value: ['matrix3d', 'translate3d', 'translateZ', 'scale3d', 'scaleZ', 'rotate3d', 'rotateX', 'rotateY', 'perspective']
});
module.exports = TransformDecl;
},{"../declaration":6}],49:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Declaration = require('../declaration');
var WritingMode = function (_Declaration) {
_inherits(WritingMode, _Declaration);
function WritingMode() {
_classCallCheck(this, WritingMode);
return _possibleConstructorReturn(this, _Declaration.apply(this, arguments));
}
WritingMode.prototype.set = function set(decl, prefix) {
if (prefix === '-ms-') {
decl.value = WritingMode.msValues[decl.value] || decl.value;
return _Declaration.prototype.set.call(this, decl, prefix);
} else {
return _Declaration.prototype.set.call(this, decl, prefix);
}
};
return WritingMode;
}(Declaration);
Object.defineProperty(WritingMode, 'names', {
enumerable: true,
writable: true,
value: ['writing-mode']
});
Object.defineProperty(WritingMode, 'msValues', {
enumerable: true,
writable: true,
value: {
'horizontal-tb': 'lr-tb',
'vertical-rl': 'tb-rl',
'vertical-lr': 'tb-lr'
}
});
module.exports = WritingMode;
},{"../declaration":6}],50:[function(require,module,exports){
'use strict';
var browserslist = require('browserslist');
function capitalize(str) {
return str.slice(0, 1).toUpperCase() + str.slice(1);
}
var names = {
ie: 'IE',
ie_mob: 'IE Mobile',
ios_saf: 'iOS',
op_mini: 'Opera Mini',
op_mob: 'Opera Mobile',
and_chr: 'Chrome for Android',
and_ff: 'Firefox for Android',
and_uc: 'UC for Android'
};
var prefix = function prefix(name, prefixes) {
var out = ' ' + name + ': ';
out += prefixes.map(function (i) {
return i.replace(/^-(.*)-$/g, '$1');
}).join(', ');
out += '\n';
return out;
};
module.exports = function (prefixes) {
if (prefixes.browsers.selected.length === 0) {
return 'No browsers selected';
}
var versions = {};
for (var _iterator = prefixes.browsers.selected, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var browser = _ref;
var _browser$split = browser.split(' '),
name = _browser$split[0],
version = _browser$split[1];
name = names[name] || capitalize(name);
if (versions[name]) {
versions[name].push(version);
} else {
versions[name] = [version];
}
}
var out = 'Browsers:\n';
for (var _browser in versions) {
var list = versions[_browser];
list = list.sort(function (a, b) {
return parseFloat(b) - parseFloat(a);
});
out += ' ' + _browser + ': ' + list.join(', ') + '\n';
}
var coverage = browserslist.coverage(prefixes.browsers.selected);
var round = Math.round(coverage * 100) / 100.0;
out += '\nThese browsers account for ' + round + '% of all users globally\n';
var atrules = '';
for (var name in prefixes.add) {
var data = prefixes.add[name];
if (name[0] === '@' && data.prefixes) {
atrules += prefix(name, data.prefixes);
}
}
if (atrules !== '') {
out += '\nAt-Rules:\n' + atrules;
}
var selectors = '';
for (var _iterator2 = prefixes.add.selectors, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var selector = _ref2;
if (selector.prefixes) {
selectors += prefix(selector.name, selector.prefixes);
}
}
if (selectors !== '') {
out += '\nSelectors:\n' + selectors;
}
var values = '';
var props = '';
for (var _name in prefixes.add) {
var _data = prefixes.add[_name];
if (_name[0] !== '@' && _data.prefixes) {
props += prefix(_name, _data.prefixes);
}
if (!_data.values) {
continue;
}
for (var _iterator3 = _data.values, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var value = _ref3;
var string = prefix(value.name, value.prefixes);
if (values.indexOf(string) === -1) {
values += string;
}
}
}
if (props !== '') {
out += '\nProperties:\n' + props;
}
if (values !== '') {
out += '\nValues:\n' + values;
}
if (atrules === '' && selectors === '' && props === '' && values === '') {
out += '\nAwesome! Your browsers don\'t require any vendor prefixes.' + '\nNow you can remove Autoprefixer from build steps.';
}
return out;
};
},{"browserslist":65}],51:[function(require,module,exports){
"use strict";
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var OldSelector = function () {
function OldSelector(selector, prefix) {
_classCallCheck(this, OldSelector);
this.prefix = prefix;
this.prefixed = selector.prefixed(this.prefix);
this.regexp = selector.regexp(this.prefix);
this.prefixeds = selector.possible().map(function (x) {
return [selector.prefixed(x), selector.regexp(x)];
});
this.unprefixed = selector.name;
this.nameRegexp = selector.regexp();
}
/**
* Is rule a hack without unprefixed version bottom
*/
OldSelector.prototype.isHack = function isHack(rule) {
var index = rule.parent.index(rule) + 1;
var rules = rule.parent.nodes;
while (index < rules.length) {
var before = rules[index].selector;
if (!before) {
return true;
}
if (before.indexOf(this.unprefixed) !== -1 && before.match(this.nameRegexp)) {
return false;
}
var some = false;
for (var _iterator = this.prefixeds, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref2;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref2 = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref2 = _i.value;
}
var _ref = _ref2;
var string = _ref[0];
var regexp = _ref[1];
if (before.indexOf(string) !== -1 && before.match(regexp)) {
some = true;
break;
}
}
if (!some) {
return true;
}
index += 1;
}
return true;
};
/**
* Does rule contain an unnecessary prefixed selector
*/
OldSelector.prototype.check = function check(rule) {
if (rule.selector.indexOf(this.prefixed) === -1) {
return false;
}
if (!rule.selector.match(this.regexp)) {
return false;
}
if (this.isHack(rule)) {
return false;
}
return true;
};
return OldSelector;
}();
module.exports = OldSelector;
},{}],52:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var utils = require('./utils');
var OldValue = function () {
function OldValue(unprefixed, prefixed, string, regexp) {
_classCallCheck(this, OldValue);
this.unprefixed = unprefixed;
this.prefixed = prefixed;
this.string = string || prefixed;
this.regexp = regexp || utils.regexp(prefixed);
}
/**
* Check, that value contain old value
*/
OldValue.prototype.check = function check(value) {
if (value.indexOf(this.string) !== -1) {
return !!value.match(this.regexp);
}
return false;
};
return OldValue;
}();
module.exports = OldValue;
},{"./utils":60}],53:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Browsers = require('./browsers');
var utils = require('./utils');
var vendor = require('postcss/lib/vendor');
/**
* Recursivly clone objects
*/
function _clone(obj, parent) {
var cloned = new obj.constructor();
for (var _iterator = Object.keys(obj || {}), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
var value = obj[i];
if (i === 'parent' && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
if (parent) {
cloned[i] = parent;
}
} else if (i === 'source') {
cloned[i] = value;
} else if (i === null) {
cloned[i] = value;
} else if (value instanceof Array) {
cloned[i] = value.map(function (x) {
return _clone(x, cloned);
});
} else if (i !== '_autoprefixerPrefix' && i !== '_autoprefixerValues') {
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null) {
value = _clone(value, cloned);
}
cloned[i] = value;
}
}
return cloned;
}
var Prefixer = function () {
/**
* Add hack to selected names
*/
Prefixer.hack = function hack(klass) {
var _this = this;
if (!this.hacks) {
this.hacks = {};
}
return klass.names.map(function (name) {
_this.hacks[name] = klass;
return _this.hacks[name];
});
};
/**
* Load hacks for some names
*/
Prefixer.load = function load(name, prefixes, all) {
var Klass = this.hacks && this.hacks[name];
if (Klass) {
return new Klass(name, prefixes, all);
} else {
return new this(name, prefixes, all);
}
};
/**
* Clone node and clean autprefixer custom caches
*/
Prefixer.clone = function clone(node, overrides) {
var cloned = _clone(node);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
};
function Prefixer(name, prefixes, all) {
_classCallCheck(this, Prefixer);
this.name = name;
this.prefixes = prefixes;
this.all = all;
}
/**
* Find prefix in node parents
*/
Prefixer.prototype.parentPrefix = function parentPrefix(node) {
var prefix = void 0;
if (typeof node._autoprefixerPrefix !== 'undefined') {
prefix = node._autoprefixerPrefix;
} else if (node.type === 'decl' && node.prop[0] === '-') {
prefix = vendor.prefix(node.prop);
} else if (node.type === 'root') {
prefix = false;
} else if (node.type === 'rule' && node.selector.indexOf(':-') !== -1 && /:(-\w+-)/.test(node.selector)) {
prefix = node.selector.match(/:(-\w+-)/)[1];
} else if (node.type === 'atrule' && node.name[0] === '-') {
prefix = vendor.prefix(node.name);
} else {
prefix = this.parentPrefix(node.parent);
}
if (Browsers.prefixes().indexOf(prefix) === -1) {
prefix = false;
}
node._autoprefixerPrefix = prefix;
return node._autoprefixerPrefix;
};
/**
* Clone node with prefixes
*/
Prefixer.prototype.process = function process(node) {
if (!this.check(node)) {
return undefined;
}
var parent = this.parentPrefix(node);
var prefixes = this.prefixes.filter(function (prefix) {
return !parent || parent === utils.removeNote(prefix);
});
var added = [];
for (var _iterator2 = prefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var prefix = _ref2;
if (this.add(node, prefix, added.concat([prefix]))) {
added.push(prefix);
}
}
return added;
};
/**
* Shortcut for Prefixer.clone
*/
Prefixer.prototype.clone = function clone(node, overrides) {
return Prefixer.clone(node, overrides);
};
return Prefixer;
}();
module.exports = Prefixer;
},{"./browsers":5,"./utils":60,"postcss/lib/vendor":551}],54:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Declaration = require('./declaration');
var Resolution = require('./resolution');
var Transition = require('./transition');
var Processor = require('./processor');
var Supports = require('./supports');
var Browsers = require('./browsers');
var Selector = require('./selector');
var AtRule = require('./at-rule');
var Value = require('./value');
var utils = require('./utils');
var vendor = require('postcss/lib/vendor');
Selector.hack(require('./hacks/fullscreen'));
Selector.hack(require('./hacks/placeholder'));
Declaration.hack(require('./hacks/flex'));
Declaration.hack(require('./hacks/order'));
Declaration.hack(require('./hacks/filter'));
Declaration.hack(require('./hacks/grid-end'));
Declaration.hack(require('./hacks/flex-flow'));
Declaration.hack(require('./hacks/flex-grow'));
Declaration.hack(require('./hacks/flex-wrap'));
Declaration.hack(require('./hacks/grid-start'));
Declaration.hack(require('./hacks/align-self'));
Declaration.hack(require('./hacks/appearance'));
Declaration.hack(require('./hacks/flex-basis'));
Declaration.hack(require('./hacks/mask-border'));
Declaration.hack(require('./hacks/align-items'));
Declaration.hack(require('./hacks/flex-shrink'));
Declaration.hack(require('./hacks/break-props'));
Declaration.hack(require('./hacks/writing-mode'));
Declaration.hack(require('./hacks/border-image'));
Declaration.hack(require('./hacks/align-content'));
Declaration.hack(require('./hacks/border-radius'));
Declaration.hack(require('./hacks/block-logical'));
Declaration.hack(require('./hacks/grid-template'));
Declaration.hack(require('./hacks/inline-logical'));
Declaration.hack(require('./hacks/grid-row-align'));
Declaration.hack(require('./hacks/transform-decl'));
Declaration.hack(require('./hacks/flex-direction'));
Declaration.hack(require('./hacks/image-rendering'));
Declaration.hack(require('./hacks/text-decoration'));
Declaration.hack(require('./hacks/justify-content'));
Declaration.hack(require('./hacks/background-size'));
Declaration.hack(require('./hacks/grid-column-align'));
Declaration.hack(require('./hacks/text-emphasis-position'));
Value.hack(require('./hacks/gradient'));
Value.hack(require('./hacks/intrinsic'));
Value.hack(require('./hacks/pixelated'));
Value.hack(require('./hacks/image-set'));
Value.hack(require('./hacks/cross-fade'));
Value.hack(require('./hacks/flex-values'));
Value.hack(require('./hacks/display-flex'));
Value.hack(require('./hacks/display-grid'));
Value.hack(require('./hacks/filter-value'));
var declsCache = {};
var Prefixes = function () {
function Prefixes(data, browsers) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
_classCallCheck(this, Prefixes);
this.data = data;
this.browsers = browsers;
this.options = options;
var _preprocess = this.preprocess(this.select(this.data));
this.add = _preprocess[0];
this.remove = _preprocess[1];
this.transition = new Transition(this);
this.processor = new Processor(this);
}
/**
* Return clone instance to remove all prefixes
*/
Prefixes.prototype.cleaner = function cleaner() {
if (this.cleanerCache) {
return this.cleanerCache;
}
if (this.browsers.selected.length) {
var empty = new Browsers(this.browsers.data, []);
this.cleanerCache = new Prefixes(this.data, empty, this.options);
} else {
return this;
}
return this.cleanerCache;
};
/**
* Select prefixes from data, which is necessary for selected browsers
*/
Prefixes.prototype.select = function select(list) {
var _this = this;
var selected = { add: {}, remove: {} };
var _loop = function _loop(name) {
var data = list[name];
var add = data.browsers.map(function (i) {
var params = i.split(' ');
return {
browser: params[0] + ' ' + params[1],
note: params[2]
};
});
var notes = add.filter(function (i) {
return i.note;
}).map(function (i) {
return _this.browsers.prefix(i.browser) + ' ' + i.note;
});
notes = utils.uniq(notes);
add = add.filter(function (i) {
return _this.browsers.isSelected(i.browser);
}).map(function (i) {
var prefix = _this.browsers.prefix(i.browser);
if (i.note) {
return prefix + ' ' + i.note;
} else {
return prefix;
}
});
add = _this.sort(utils.uniq(add));
if (_this.options.flexbox === 'no-2009') {
add = add.filter(function (i) {
return i.indexOf('2009') === -1;
});
}
var all = data.browsers.map(function (i) {
return _this.browsers.prefix(i);
});
if (data.mistakes) {
all = all.concat(data.mistakes);
}
all = all.concat(notes);
all = utils.uniq(all);
if (add.length) {
selected.add[name] = add;
if (add.length < all.length) {
selected.remove[name] = all.filter(function (i) {
return add.indexOf(i) === -1;
});
}
} else {
selected.remove[name] = all;
}
};
for (var name in list) {
_loop(name);
}
return selected;
};
/**
* Sort vendor prefixes
*/
Prefixes.prototype.sort = function sort(prefixes) {
return prefixes.sort(function (a, b) {
var aLength = utils.removeNote(a).length;
var bLength = utils.removeNote(b).length;
if (aLength === bLength) {
return b.length - a.length;
} else {
return bLength - aLength;
}
});
};
/**
* Cache prefixes data to fast CSS processing
*/
Prefixes.prototype.preprocess = function preprocess(selected) {
var add = {
'selectors': [],
'@supports': new Supports(Prefixes, this)
};
for (var name in selected.add) {
var prefixes = selected.add[name];
if (name === '@keyframes' || name === '@viewport') {
add[name] = new AtRule(name, prefixes, this);
} else if (name === '@resolution') {
add[name] = new Resolution(name, prefixes, this);
} else if (this.data[name].selector) {
add.selectors.push(Selector.load(name, prefixes, this));
} else {
var props = this.data[name].props;
if (props) {
var value = Value.load(name, prefixes, this);
for (var _iterator = props, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prop = _ref;
if (!add[prop]) {
add[prop] = { values: [] };
}
add[prop].values.push(value);
}
} else {
var values = add[name] && add[name].values || [];
add[name] = Declaration.load(name, prefixes, this);
add[name].values = values;
}
}
}
var remove = { selectors: [] };
for (var _name in selected.remove) {
var _prefixes = selected.remove[_name];
if (this.data[_name].selector) {
var selector = Selector.load(_name, _prefixes);
for (var _iterator2 = _prefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var prefix = _ref2;
remove.selectors.push(selector.old(prefix));
}
} else if (_name === '@keyframes' || _name === '@viewport') {
for (var _iterator3 = _prefixes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var _prefix = _ref3;
var prefixed = '@' + _prefix + _name.slice(1);
remove[prefixed] = { remove: true };
}
} else if (_name === '@resolution') {
remove[_name] = new Resolution(_name, _prefixes, this);
} else {
var _props = this.data[_name].props;
if (_props) {
var _value = Value.load(_name, [], this);
for (var _iterator4 = _prefixes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var _prefix2 = _ref4;
var old = _value.old(_prefix2);
if (old) {
for (var _iterator5 = _props, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var _prop = _ref5;
if (!remove[_prop]) {
remove[_prop] = {};
}
if (!remove[_prop].values) {
remove[_prop].values = [];
}
remove[_prop].values.push(old);
}
}
}
} else {
for (var _iterator6 = _prefixes, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref6;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref6 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref6 = _i6.value;
}
var _prefix3 = _ref6;
var olds = this.decl(_name).old(_name, _prefix3);
if (_name === 'align-self') {
var a = add[_name] && add[_name].prefixes;
if (a) {
if (_prefix3 === '-webkit- 2009' && a.indexOf('-webkit-') !== -1) {
continue;
} else if (_prefix3 === '-webkit-' && a.indexOf('-webkit- 2009') !== -1) {
continue;
}
}
}
for (var _iterator7 = olds, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
var _ref7;
if (_isArray7) {
if (_i7 >= _iterator7.length) break;
_ref7 = _iterator7[_i7++];
} else {
_i7 = _iterator7.next();
if (_i7.done) break;
_ref7 = _i7.value;
}
var _prefixed = _ref7;
if (!remove[_prefixed]) {
remove[_prefixed] = {};
}
remove[_prefixed].remove = true;
}
}
}
}
}
return [add, remove];
};
/**
* Declaration loader with caching
*/
Prefixes.prototype.decl = function decl(prop) {
var decl = declsCache[prop];
if (decl) {
return decl;
} else {
declsCache[prop] = Declaration.load(prop);
return declsCache[prop];
}
};
/**
* Return unprefixed version of property
*/
Prefixes.prototype.unprefixed = function unprefixed(prop) {
var value = this.normalize(vendor.unprefixed(prop));
if (value === 'flex-direction') {
value = 'flex-flow';
}
return value;
};
/**
* Normalize prefix for remover
*/
Prefixes.prototype.normalize = function normalize(prop) {
return this.decl(prop).normalize(prop);
};
/**
* Return prefixed version of property
*/
Prefixes.prototype.prefixed = function prefixed(prop, prefix) {
prop = vendor.unprefixed(prop);
return this.decl(prop).prefixed(prop, prefix);
};
/**
* Return values, which must be prefixed in selected property
*/
Prefixes.prototype.values = function values(type, prop) {
var data = this[type];
var global = data['*'] && data['*'].values;
var values = data[prop] && data[prop].values;
if (global && values) {
return utils.uniq(global.concat(values));
} else {
return global || values || [];
}
};
/**
* Group declaration by unprefixed property to check them
*/
Prefixes.prototype.group = function group(decl) {
var _this2 = this;
var rule = decl.parent;
var index = rule.index(decl);
var length = rule.nodes.length;
var unprefixed = this.unprefixed(decl.prop);
var checker = function checker(step, callback) {
index += step;
while (index >= 0 && index < length) {
var other = rule.nodes[index];
if (other.type === 'decl') {
if (step === -1 && other.prop === unprefixed) {
if (!Browsers.withPrefix(other.value)) {
break;
}
}
if (_this2.unprefixed(other.prop) !== unprefixed) {
break;
} else if (callback(other) === true) {
return true;
}
if (step === +1 && other.prop === unprefixed) {
if (!Browsers.withPrefix(other.value)) {
break;
}
}
}
index += step;
}
return false;
};
return {
up: function up(callback) {
return checker(-1, callback);
},
down: function down(callback) {
return checker(+1, callback);
}
};
};
return Prefixes;
}();
module.exports = Prefixes;
},{"./at-rule":2,"./browsers":5,"./declaration":6,"./hacks/align-content":7,"./hacks/align-items":8,"./hacks/align-self":9,"./hacks/appearance":10,"./hacks/background-size":11,"./hacks/block-logical":12,"./hacks/border-image":13,"./hacks/border-radius":14,"./hacks/break-props":15,"./hacks/cross-fade":16,"./hacks/display-flex":17,"./hacks/display-grid":18,"./hacks/filter":20,"./hacks/filter-value":19,"./hacks/flex":29,"./hacks/flex-basis":21,"./hacks/flex-direction":22,"./hacks/flex-flow":23,"./hacks/flex-grow":24,"./hacks/flex-shrink":25,"./hacks/flex-values":27,"./hacks/flex-wrap":28,"./hacks/fullscreen":30,"./hacks/gradient":31,"./hacks/grid-column-align":32,"./hacks/grid-end":33,"./hacks/grid-row-align":34,"./hacks/grid-start":35,"./hacks/grid-template":36,"./hacks/image-rendering":37,"./hacks/image-set":38,"./hacks/inline-logical":39,"./hacks/intrinsic":40,"./hacks/justify-content":41,"./hacks/mask-border":42,"./hacks/order":43,"./hacks/pixelated":44,"./hacks/placeholder":45,"./hacks/text-decoration":46,"./hacks/text-emphasis-position":47,"./hacks/transform-decl":48,"./hacks/writing-mode":49,"./processor":55,"./resolution":56,"./selector":57,"./supports":58,"./transition":59,"./utils":60,"./value":61,"postcss/lib/vendor":551}],55:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Value = require('./value');
var OLD_DIRECTION = /(^|[^-])(linear|radial)-gradient\(\s*(top|left|right|bottom)/i;
var SIZES = ['width', 'height', 'min-width', 'max-width', 'min-height', 'max-height', 'inline-size', 'min-inline-size', 'max-inline-size', 'block-size', 'min-block-size', 'max-block-size'];
var Processor = function () {
function Processor(prefixes) {
_classCallCheck(this, Processor);
this.prefixes = prefixes;
}
/**
* Add necessary prefixes
*/
Processor.prototype.add = function add(css, result) {
var _this = this;
// At-rules
var resolution = this.prefixes.add['@resolution'];
var keyframes = this.prefixes.add['@keyframes'];
var viewport = this.prefixes.add['@viewport'];
var supports = this.prefixes.add['@supports'];
css.walkAtRules(function (rule) {
if (rule.name === 'keyframes') {
if (!_this.disabled(rule)) {
return keyframes && keyframes.process(rule);
}
} else if (rule.name === 'viewport') {
if (!_this.disabled(rule)) {
return viewport && viewport.process(rule);
}
} else if (rule.name === 'supports') {
if (_this.prefixes.options.supports !== false && !_this.disabled(rule)) {
return supports.process(rule);
}
} else if (rule.name === 'media' && rule.params.indexOf('-resolution') !== -1) {
if (!_this.disabled(rule)) {
return resolution && resolution.process(rule);
}
}
return undefined;
});
// Selectors
css.walkRules(function (rule) {
if (_this.disabled(rule)) return undefined;
return _this.prefixes.add.selectors.map(function (selector) {
return selector.process(rule, result);
});
});
css.walkDecls(function (decl) {
if (_this.disabledDecl(decl)) return undefined;
if (decl.prop === 'display' && decl.value === 'box') {
result.warn('You should write display: flex by final spec ' + 'instead of display: box', { node: decl });
return undefined;
}
if (decl.value.indexOf('linear-gradient') !== -1) {
if (OLD_DIRECTION.test(decl.value)) {
result.warn('Gradient has outdated direction syntax. ' + 'New syntax is like `to left` instead of `right`.', { node: decl });
}
}
if (decl.prop === 'text-emphasis-position') {
if (decl.value === 'under' || decl.value === 'over') {
result.warn('You should use 2 values for text-emphasis-position ' + 'For example, `under left` instead of just `under`.', { node: decl });
}
}
if (SIZES.indexOf(decl.prop) !== -1) {
if (decl.value.indexOf('fill-available') !== -1) {
result.warn('Replace fill-available to stretch, ' + 'because spec had been changed', { node: decl });
} else if (decl.value.indexOf('fill') !== -1) {
result.warn('Replace fill to stretch, ' + 'because spec had been changed', { node: decl });
}
}
if (_this.prefixes.options.flexbox !== false) {
if (decl.prop === 'grid-row-end' && decl.value.indexOf('span') === -1) {
result.warn('IE supports only grid-row-end with span. ' + 'You should add grid: false option to Autoprefixer ' + 'and use some JS grid polyfill for full spec support', { node: decl });
}
if (decl.prop === 'grid-row') {
if (decl.value.indexOf('/') !== -1 && decl.value.indexOf('span') === -1) {
result.warn('IE supports only grid-row with / and span. ' + 'You should add grid: false option ' + 'to Autoprefixer and use some JS grid polyfill ' + 'for full spec support', { node: decl });
}
}
}
var prefixer = void 0;
if (decl.prop === 'transition' || decl.prop === 'transition-property') {
// Transition
return _this.prefixes.transition.add(decl, result);
} else if (decl.prop === 'align-self') {
// align-self flexbox or grid
var display = _this.displayType(decl);
if (display !== 'grid' && _this.prefixes.options.flexbox !== false) {
prefixer = _this.prefixes.add['align-self'];
if (prefixer && prefixer.prefixes) {
prefixer.process(decl);
}
}
if (display !== 'flex' && _this.prefixes.options.grid !== false) {
prefixer = _this.prefixes.add['grid-row-align'];
if (prefixer && prefixer.prefixes) {
return prefixer.process(decl);
}
}
} else if (decl.prop === 'justify-self') {
// justify-self flexbox or grid
var _display = _this.displayType(decl);
if (_display !== 'flex' && _this.prefixes.options.grid !== false) {
prefixer = _this.prefixes.add['grid-column-align'];
if (prefixer && prefixer.prefixes) {
return prefixer.process(decl);
}
}
} else {
// Properties
prefixer = _this.prefixes.add[decl.prop];
if (prefixer && prefixer.prefixes) {
return prefixer.process(decl);
}
}
return undefined;
});
// Values
return css.walkDecls(function (decl) {
if (_this.disabledValue(decl)) return;
var unprefixed = _this.prefixes.unprefixed(decl.prop);
for (var _iterator = _this.prefixes.values('add', unprefixed), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var value = _ref;
value.process(decl, result);
}
Value.save(_this.prefixes, decl);
});
};
/**
* Remove unnecessary pefixes
*/
Processor.prototype.remove = function remove(css) {
var _this2 = this;
// At-rules
var resolution = this.prefixes.remove['@resolution'];
css.walkAtRules(function (rule, i) {
if (_this2.prefixes.remove['@' + rule.name]) {
if (!_this2.disabled(rule)) {
rule.parent.removeChild(i);
}
} else if (rule.name === 'media' && rule.params.indexOf('-resolution') !== -1 && resolution) {
resolution.clean(rule);
}
});
// Selectors
var _loop = function _loop(checker) {
css.walkRules(function (rule, i) {
if (checker.check(rule)) {
if (!_this2.disabled(rule)) {
rule.parent.removeChild(i);
}
}
});
};
for (var _iterator2 = this.prefixes.remove.selectors, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var checker = _ref2;
_loop(checker);
}
return css.walkDecls(function (decl, i) {
if (_this2.disabled(decl)) return;
var rule = decl.parent;
var unprefixed = _this2.prefixes.unprefixed(decl.prop);
// Transition
if (decl.prop === 'transition' || decl.prop === 'transition-property') {
_this2.prefixes.transition.remove(decl);
}
// Properties
if (_this2.prefixes.remove[decl.prop] && _this2.prefixes.remove[decl.prop].remove) {
var notHack = _this2.prefixes.group(decl).down(function (other) {
return _this2.prefixes.normalize(other.prop) === unprefixed;
});
if (unprefixed === 'flex-flow') {
notHack = true;
}
if (notHack && !_this2.withHackValue(decl)) {
if (decl.raw('before').indexOf('\n') > -1) {
_this2.reduceSpaces(decl);
}
rule.removeChild(i);
return;
}
}
// Values
for (var _iterator3 = _this2.prefixes.values('remove', unprefixed), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var checker = _ref3;
if (checker.check(decl.value)) {
unprefixed = checker.unprefixed;
var _notHack = _this2.prefixes.group(decl).down(function (other) {
return other.value.indexOf(unprefixed) !== -1;
});
if (_notHack) {
rule.removeChild(i);
return;
} else if (checker.clean) {
checker.clean(decl);
return;
}
}
}
});
};
/**
* Some rare old values, which is not in standard
*/
Processor.prototype.withHackValue = function withHackValue(decl) {
return decl.prop === '-webkit-background-clip' && decl.value === 'text';
};
/**
* Check for grid/flexbox options.
*/
Processor.prototype.disabledValue = function disabledValue(node) {
if (this.prefixes.options.grid === false && node.type === 'decl') {
if (node.prop === 'display' && node.value.indexOf('grid') !== -1) {
return true;
}
}
if (this.prefixes.options.flexbox === false && node.type === 'decl') {
if (node.prop === 'display' && node.value.indexOf('flex') !== -1) {
return true;
}
}
return this.disabled(node);
};
/**
* Check for grid/flexbox options.
*/
Processor.prototype.disabledDecl = function disabledDecl(node) {
if (this.prefixes.options.grid === false && node.type === 'decl') {
if (node.prop.indexOf('grid') !== -1 || node.prop === 'justify-items') {
return true;
}
}
if (this.prefixes.options.flexbox === false && node.type === 'decl') {
var other = ['order', 'justify-content', 'align-items', 'align-content'];
if (node.prop.indexOf('flex') !== -1 || other.indexOf(node.prop) !== -1) {
return true;
}
}
return this.disabled(node);
};
/**
* Check for control comment and global options
*/
Processor.prototype.disabled = function disabled(node) {
if (node._autoprefixerDisabled !== undefined) {
return node._autoprefixerDisabled;
} else if (node.nodes) {
var status = undefined;
node.each(function (i) {
if (i.type !== 'comment') {
return undefined;
}
if (/(!\s*)?autoprefixer:\s*off/i.test(i.text)) {
status = false;
return false;
} else if (/(!\s*)?autoprefixer:\s*on/i.test(i.text)) {
status = true;
return false;
}
return undefined;
});
var result = false;
if (status !== undefined) {
result = !status;
} else if (node.parent) {
result = this.disabled(node.parent);
}
node._autoprefixerDisabled = result;
return node._autoprefixerDisabled;
} else if (node.parent) {
node._autoprefixerDisabled = this.disabled(node.parent);
return node._autoprefixerDisabled;
} else {
// unknown state
return false;
}
};
/**
* Normalize spaces in cascade declaration group
*/
Processor.prototype.reduceSpaces = function reduceSpaces(decl) {
var stop = false;
this.prefixes.group(decl).up(function () {
stop = true;
return true;
});
if (stop) {
return;
}
var parts = decl.raw('before').split('\n');
var prevMin = parts[parts.length - 1].length;
var diff = false;
this.prefixes.group(decl).down(function (other) {
parts = other.raw('before').split('\n');
var last = parts.length - 1;
if (parts[last].length > prevMin) {
if (diff === false) {
diff = parts[last].length - prevMin;
}
parts[last] = parts[last].slice(0, -diff);
other.raws.before = parts.join('\n');
}
});
};
/**
* Is it flebox or grid rule
*/
Processor.prototype.displayType = function displayType(decl) {
for (var _iterator4 = decl.parent.nodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var i = _ref4;
if (i.prop === 'display') {
if (i.value.indexOf('flex') !== -1) {
return 'flex';
} else if (i.value.indexOf('grid') !== -1) {
return 'grid';
}
}
}
return false;
};
return Processor;
}();
module.exports = Processor;
},{"./value":61}],56:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Prefixer = require('./prefixer');
var utils = require('./utils');
var n2f = require('num2fraction');
var regexp = /(min|max)-resolution\s*:\s*\d*\.?\d+(dppx|dpi)/gi;
var split = /(min|max)-resolution(\s*:\s*)(\d*\.?\d+)(dppx|dpi)/i;
var Resolution = function (_Prefixer) {
_inherits(Resolution, _Prefixer);
function Resolution() {
_classCallCheck(this, Resolution);
return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments));
}
/**
* Return prefixed query name
*/
Resolution.prototype.prefixName = function prefixName(prefix, name) {
var newName = prefix === '-moz-' ? name + '--moz-device-pixel-ratio' : prefix + name + '-device-pixel-ratio';
return newName;
};
/**
* Return prefixed query
*/
Resolution.prototype.prefixQuery = function prefixQuery(prefix, name, colon, value, units) {
if (units === 'dpi') {
value = Number(value / 96);
}
if (prefix === '-o-') {
value = n2f(value);
}
return this.prefixName(prefix, name) + colon + value;
};
/**
* Remove prefixed queries
*/
Resolution.prototype.clean = function clean(rule) {
var _this2 = this;
if (!this.bad) {
this.bad = [];
for (var _iterator = this.prefixes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prefix = _ref;
this.bad.push(this.prefixName(prefix, 'min'));
this.bad.push(this.prefixName(prefix, 'max'));
}
}
rule.params = utils.editList(rule.params, function (queries) {
return queries.filter(function (query) {
return _this2.bad.every(function (i) {
return query.indexOf(i) === -1;
});
});
});
};
/**
* Add prefixed queries
*/
Resolution.prototype.process = function process(rule) {
var _this3 = this;
var parent = this.parentPrefix(rule);
var prefixes = parent ? [parent] : this.prefixes;
rule.params = utils.editList(rule.params, function (origin, prefixed) {
for (var _iterator2 = origin, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var query = _ref2;
if (query.indexOf('min-resolution') === -1 && query.indexOf('max-resolution') === -1) {
prefixed.push(query);
continue;
}
var _loop = function _loop(prefix) {
if (prefix === '-moz-' && rule.params.indexOf('dpi') !== -1) {
return 'continue';
} else {
var processed = query.replace(regexp, function (str) {
var parts = str.match(split);
return _this3.prefixQuery(prefix, parts[1], parts[2], parts[3], parts[4]);
});
prefixed.push(processed);
}
};
for (var _iterator3 = prefixes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var prefix = _ref3;
var _ret = _loop(prefix);
if (_ret === 'continue') continue;
}
prefixed.push(query);
}
return utils.uniq(prefixed);
});
};
return Resolution;
}(Prefixer);
module.exports = Resolution;
},{"./prefixer":53,"./utils":60,"num2fraction":522}],57:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var OldSelector = require('./old-selector');
var Prefixer = require('./prefixer');
var Browsers = require('./browsers');
var utils = require('./utils');
var Selector = function (_Prefixer) {
_inherits(Selector, _Prefixer);
function Selector(name, prefixes, all) {
_classCallCheck(this, Selector);
var _this = _possibleConstructorReturn(this, _Prefixer.call(this, name, prefixes, all));
_this.regexpCache = {};
return _this;
}
/**
* Is rule selectors need to be prefixed
*/
Selector.prototype.check = function check(rule) {
if (rule.selector.indexOf(this.name) !== -1) {
return !!rule.selector.match(this.regexp());
} else {
return false;
}
};
/**
* Return prefixed version of selector
*/
Selector.prototype.prefixed = function prefixed(prefix) {
return this.name.replace(/^([^\w]*)/, '$1' + prefix);
};
/**
* Lazy loadRegExp for name
*/
Selector.prototype.regexp = function regexp(prefix) {
if (this.regexpCache[prefix]) {
return this.regexpCache[prefix];
}
var name = prefix ? this.prefixed(prefix) : this.name;
this.regexpCache[prefix] = new RegExp('(^|[^:"\'=])' + utils.escapeRegexp(name), 'gi');
return this.regexpCache[prefix];
};
/**
* All possible prefixes
*/
Selector.prototype.possible = function possible() {
return Browsers.prefixes();
};
/**
* Return all possible selector prefixes
*/
Selector.prototype.prefixeds = function prefixeds(rule) {
if (rule._autoprefixerPrefixeds) {
return rule._autoprefixerPrefixeds;
}
var prefixeds = {};
for (var _iterator = this.possible(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prefix = _ref;
prefixeds[prefix] = this.replace(rule.selector, prefix);
}
rule._autoprefixerPrefixeds = prefixeds;
return rule._autoprefixerPrefixeds;
};
/**
* Is rule already prefixed before
*/
Selector.prototype.already = function already(rule, prefixeds, prefix) {
var index = rule.parent.index(rule) - 1;
while (index >= 0) {
var before = rule.parent.nodes[index];
if (before.type !== 'rule') {
return false;
}
var some = false;
for (var key in prefixeds) {
var prefixed = prefixeds[key];
if (before.selector === prefixed) {
if (prefix === key) {
return true;
} else {
some = true;
break;
}
}
}
if (!some) {
return false;
}
index -= 1;
}
return false;
};
/**
* Replace selectors by prefixed one
*/
Selector.prototype.replace = function replace(selector, prefix) {
return selector.replace(this.regexp(), '$1' + this.prefixed(prefix));
};
/**
* Clone and add prefixes for at-rule
*/
Selector.prototype.add = function add(rule, prefix) {
var prefixeds = this.prefixeds(rule);
if (this.already(rule, prefixeds, prefix)) {
return;
}
var cloned = this.clone(rule, { selector: prefixeds[prefix] });
rule.parent.insertBefore(rule, cloned);
};
/**
* Return function to fast find prefixed selector
*/
Selector.prototype.old = function old(prefix) {
return new OldSelector(this, prefix);
};
return Selector;
}(Prefixer);
module.exports = Selector;
},{"./browsers":5,"./old-selector":51,"./prefixer":53,"./utils":60}],58:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Browsers = require('./browsers');
var brackets = require('./brackets');
var Value = require('./value');
var utils = require('./utils');
var postcss = require('postcss');
var supported = [];
var data = require('caniuse-lite').feature(require('caniuse-lite/data/features/css-featurequeries.js'));
for (var browser in data.stats) {
var versions = data.stats[browser];
for (var version in versions) {
var support = versions[version];
if (/y/.test(support)) {
supported.push(browser + ' ' + version);
}
}
}
var Supports = function () {
function Supports(Prefixes, all) {
_classCallCheck(this, Supports);
this.Prefixes = Prefixes;
this.all = all;
}
/**
* Return prefixer only with @supports supported browsers
*/
Supports.prototype.prefixer = function prefixer() {
if (this.prefixerCache) {
return this.prefixerCache;
}
var filtered = this.all.browsers.selected.filter(function (i) {
return supported.indexOf(i) !== -1;
});
var browsers = new Browsers(this.all.browsers.data, filtered, this.all.options);
this.prefixerCache = new this.Prefixes(this.all.data, browsers, this.all.options);
return this.prefixerCache;
};
/**
* Parse string into declaration property and value
*/
Supports.prototype.parse = function parse(str) {
var _str$split = str.split(':'),
prop = _str$split[0],
value = _str$split[1];
if (!value) value = '';
return [prop.trim(), value.trim()];
};
/**
* Create virtual rule to process it by prefixer
*/
Supports.prototype.virtual = function virtual(str) {
var _parse = this.parse(str),
prop = _parse[0],
value = _parse[1];
var rule = postcss.parse('a{}').first;
rule.append({ prop: prop, value: value, raws: { before: '' } });
return rule;
};
/**
* Return array of Declaration with all necessary prefixes
*/
Supports.prototype.prefixed = function prefixed(str) {
var rule = this.virtual(str);
if (this.disabled(rule.first)) {
return rule.nodes;
}
var prefixer = this.prefixer().add[rule.first.prop];
prefixer && prefixer.process && prefixer.process(rule.first);
for (var _iterator = rule.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var decl = _ref;
for (var _iterator2 = this.prefixer().values('add', rule.first.prop), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var value = _ref2;
value.process(decl);
}
Value.save(this.all, decl);
}
return rule.nodes;
};
/**
* Return true if brackets node is "not" word
*/
Supports.prototype.isNot = function isNot(node) {
return typeof node === 'string' && /not\s*/i.test(node);
};
/**
* Return true if brackets node is "or" word
*/
Supports.prototype.isOr = function isOr(node) {
return typeof node === 'string' && /\s*or\s*/i.test(node);
};
/**
* Return true if brackets node is (prop: value)
*/
Supports.prototype.isProp = function isProp(node) {
return (typeof node === 'undefined' ? 'undefined' : _typeof(node)) === 'object' && node.length === 1 && typeof node[0] === 'string';
};
/**
* Return true if prefixed property has no unprefixed
*/
Supports.prototype.isHack = function isHack(all, unprefixed) {
var check = new RegExp('(\\(|\\s)' + utils.escapeRegexp(unprefixed) + ':');
return !check.test(all);
};
/**
* Return true if we need to remove node
*/
Supports.prototype.toRemove = function toRemove(str, all) {
var _parse2 = this.parse(str),
prop = _parse2[0],
value = _parse2[1];
var unprefixed = this.all.unprefixed(prop);
var cleaner = this.all.cleaner();
if (cleaner.remove[prop] && cleaner.remove[prop].remove && !this.isHack(all, unprefixed)) {
return true;
}
for (var _iterator3 = cleaner.values('remove', unprefixed), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var checker = _ref3;
if (checker.check(value)) {
return true;
}
}
return false;
};
/**
* Remove all unnecessary prefixes
*/
Supports.prototype.remove = function remove(nodes, all) {
var i = 0;
while (i < nodes.length) {
if (!this.isNot(nodes[i - 1]) && this.isProp(nodes[i]) && this.isOr(nodes[i + 1])) {
if (this.toRemove(nodes[i][0], all)) {
nodes.splice(i, 2);
} else {
i += 2;
}
} else {
if (_typeof(nodes[i]) === 'object') {
nodes[i] = this.remove(nodes[i], all);
}
i += 1;
}
}
return nodes;
};
/**
* Clean brackets with one child
*/
Supports.prototype.cleanBrackets = function cleanBrackets(nodes) {
var _this = this;
return nodes.map(function (i) {
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object') {
if (i.length === 1 && _typeof(i[0]) === 'object') {
return _this.cleanBrackets(i[0]);
} else {
return _this.cleanBrackets(i);
}
} else {
return i;
}
});
};
/**
* Add " or " between properties and convert it to brackets format
*/
Supports.prototype.convert = function convert(progress) {
var result = [''];
for (var _iterator4 = progress, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var i = _ref4;
result.push([i.prop + ': ' + i.value]);
result.push(' or ');
}
result[result.length - 1] = '';
return result;
};
/**
* Compress value functions into a string nodes
*/
Supports.prototype.normalize = function normalize(nodes) {
var _this2 = this;
if ((typeof nodes === 'undefined' ? 'undefined' : _typeof(nodes)) === 'object') {
nodes = nodes.filter(function (i) {
return i !== '';
});
if (typeof nodes[0] === 'string' && nodes[0].indexOf(':') !== -1) {
return [brackets.stringify(nodes)];
} else {
return nodes.map(function (i) {
return _this2.normalize(i);
});
}
} else {
return nodes;
}
};
/**
* Add prefixes
*/
Supports.prototype.add = function add(nodes, all) {
var _this3 = this;
return nodes.map(function (i) {
if (_this3.isProp(i)) {
var prefixed = _this3.prefixed(i[0]);
if (prefixed.length > 1) {
return _this3.convert(prefixed);
} else {
return i;
}
} else if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object') {
return _this3.add(i, all);
} else {
return i;
}
});
};
/**
* Add prefixed declaration
*/
Supports.prototype.process = function process(rule) {
var ast = brackets.parse(rule.params);
ast = this.normalize(ast);
ast = this.remove(ast, rule.params);
ast = this.add(ast, rule.params);
ast = this.cleanBrackets(ast);
rule.params = brackets.stringify(ast);
};
/**
* Check global options
*/
Supports.prototype.disabled = function disabled(node) {
if (this.all.options.grid === false) {
if (node.prop === 'display' && node.value.indexOf('grid') !== -1) {
return true;
}
if (node.prop.indexOf('grid') !== -1 || node.prop === 'justify-items') {
return true;
}
}
if (this.all.options.flexbox === false) {
if (node.prop === 'display' && node.value.indexOf('flex') !== -1) {
return true;
}
var other = ['order', 'justify-content', 'align-items', 'align-content'];
if (node.prop.indexOf('flex') !== -1 || other.indexOf(node.prop) !== -1) {
return true;
}
}
return false;
};
return Supports;
}();
module.exports = Supports;
},{"./brackets":4,"./browsers":5,"./utils":60,"./value":61,"caniuse-lite":513,"caniuse-lite/data/features/css-featurequeries.js":144,"postcss":541}],59:[function(require,module,exports){
'use strict';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var parser = require('postcss-value-parser');
var vendor = require('postcss/lib/vendor');
var list = require('postcss/lib/list');
var Transition = function () {
function Transition(prefixes) {
_classCallCheck(this, Transition);
Object.defineProperty(this, 'props', {
enumerable: true,
writable: true,
value: ['transition', 'transition-property']
});
this.prefixes = prefixes;
}
/**
* Process transition and add prefies for all necessary properties
*/
Transition.prototype.add = function add(decl, result) {
var _this = this;
var prefix = void 0,
prop = void 0;
var declPrefixes = this.prefixes.add[decl.prop] && this.prefixes.add[decl.prop].prefixes || [];
var params = this.parse(decl.value);
var names = params.map(function (i) {
return _this.findProp(i);
});
var added = [];
if (names.some(function (i) {
return i[0] === '-';
})) {
return;
}
for (var _iterator = params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var param = _ref;
prop = this.findProp(param);
if (prop[0] === '-') {
continue;
}
var prefixer = this.prefixes.add[prop];
if (!prefixer || !prefixer.prefixes) {
continue;
}
for (var _iterator3 = prefixer.prefixes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
prefix = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
prefix = _i3.value;
}
var prefixed = this.prefixes.prefixed(prop, prefix);
if (prefixed !== '-ms-transform' && names.indexOf(prefixed) === -1) {
if (!this.disabled(prop, prefix)) {
added.push(this.clone(prop, prefixed, param));
}
}
}
}
params = params.concat(added);
var value = this.stringify(params);
var webkitClean = this.stringify(this.cleanFromUnprefixed(params, '-webkit-'));
if (declPrefixes.indexOf('-webkit-') !== -1) {
this.cloneBefore(decl, '-webkit-' + decl.prop, webkitClean);
}
this.cloneBefore(decl, decl.prop, webkitClean);
if (declPrefixes.indexOf('-o-') !== -1) {
var operaClean = this.stringify(this.cleanFromUnprefixed(params, '-o-'));
this.cloneBefore(decl, '-o-' + decl.prop, operaClean);
}
for (var _iterator2 = declPrefixes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
prefix = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
prefix = _i2.value;
}
if (prefix !== '-webkit-' && prefix !== '-o-') {
var prefixValue = this.stringify(this.cleanOtherPrefixes(params, prefix));
this.cloneBefore(decl, prefix + decl.prop, prefixValue);
}
}
if (value !== decl.value && !this.already(decl, decl.prop, value)) {
this.checkForWarning(result, decl);
decl.cloneBefore();
decl.value = value;
}
};
/**
* Find property name
*/
Transition.prototype.findProp = function findProp(param) {
var prop = param[0].value;
if (/^\d/.test(prop)) {
for (var i = 0; i < param.length; i++) {
var token = param[i];
if (i !== 0 && token.type === 'word') {
return token.value;
}
}
}
return prop;
};
/**
* Does we aready have this declaration
*/
Transition.prototype.already = function already(decl, prop, value) {
return decl.parent.some(function (i) {
return i.prop === prop && i.value === value;
});
};
/**
* Add declaration if it is not exist
*/
Transition.prototype.cloneBefore = function cloneBefore(decl, prop, value) {
if (!this.already(decl, prop, value)) {
decl.cloneBefore({ prop: prop, value: value });
}
};
/**
* Show transition-property warning
*/
Transition.prototype.checkForWarning = function checkForWarning(result, decl) {
if (decl.prop === 'transition-property') {
decl.parent.each(function (i) {
if (i.type !== 'decl') {
return undefined;
}
if (i.prop.indexOf('transition-') !== 0) {
return undefined;
}
if (i.prop === 'transition-property') {
return undefined;
}
if (list.comma(i.value).length > 1) {
decl.warn(result, 'Replace transition-property to transition, ' + 'because Autoprefixer could not support ' + 'any cases of transition-property ' + 'and other transition-*');
}
return false;
});
}
};
/**
* Process transition and remove all unnecessary properties
*/
Transition.prototype.remove = function remove(decl) {
var _this2 = this;
var params = this.parse(decl.value);
params = params.filter(function (i) {
var prop = _this2.prefixes.remove[_this2.findProp(i)];
return !prop || !prop.remove;
});
var value = this.stringify(params);
if (decl.value === value) {
return;
}
if (params.length === 0) {
decl.remove();
return;
}
var double = decl.parent.some(function (i) {
return i.prop === decl.prop && i.value === value;
});
var smaller = decl.parent.some(function (i) {
return i !== decl && i.prop === decl.prop && i.value.length > value.length;
});
if (double || smaller) {
decl.remove();
} else {
decl.value = value;
}
};
/**
* Parse properties list to array
*/
Transition.prototype.parse = function parse(value) {
var ast = parser(value);
var result = [];
var param = [];
for (var _iterator4 = ast.nodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref2;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref2 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref2 = _i4.value;
}
var node = _ref2;
param.push(node);
if (node.type === 'div' && node.value === ',') {
result.push(param);
param = [];
}
}
result.push(param);
return result.filter(function (i) {
return i.length > 0;
});
};
/**
* Return properties string from array
*/
Transition.prototype.stringify = function stringify(params) {
if (params.length === 0) {
return '';
}
var nodes = [];
for (var _iterator5 = params, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref3;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref3 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref3 = _i5.value;
}
var param = _ref3;
if (param[param.length - 1].type !== 'div') {
param.push(this.div(params));
}
nodes = nodes.concat(param);
}
if (nodes[0].type === 'div') {
nodes = nodes.slice(1);
}
if (nodes[nodes.length - 1].type === 'div') {
nodes = nodes.slice(0, +-2 + 1 || undefined);
}
return parser.stringify({ nodes: nodes });
};
/**
* Return new param array with different name
*/
Transition.prototype.clone = function clone(origin, name, param) {
var result = [];
var changed = false;
for (var _iterator6 = param, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref4;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref4 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref4 = _i6.value;
}
var i = _ref4;
if (!changed && i.type === 'word' && i.value === origin) {
result.push({ type: 'word', value: name });
changed = true;
} else {
result.push(i);
}
}
return result;
};
/**
* Find or create seperator
*/
Transition.prototype.div = function div(params) {
for (var _iterator7 = params, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
var _ref5;
if (_isArray7) {
if (_i7 >= _iterator7.length) break;
_ref5 = _iterator7[_i7++];
} else {
_i7 = _iterator7.next();
if (_i7.done) break;
_ref5 = _i7.value;
}
var param = _ref5;
for (var _iterator8 = param, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) {
var _ref6;
if (_isArray8) {
if (_i8 >= _iterator8.length) break;
_ref6 = _iterator8[_i8++];
} else {
_i8 = _iterator8.next();
if (_i8.done) break;
_ref6 = _i8.value;
}
var node = _ref6;
if (node.type === 'div' && node.value === ',') {
return node;
}
}
}
return { type: 'div', value: ',', after: ' ' };
};
Transition.prototype.cleanOtherPrefixes = function cleanOtherPrefixes(params, prefix) {
var _this3 = this;
return params.filter(function (param) {
var current = vendor.prefix(_this3.findProp(param));
return current === '' || current === prefix;
});
};
/**
* Remove all non-webkit prefixes and unprefixed params if we have prefixed
*/
Transition.prototype.cleanFromUnprefixed = function cleanFromUnprefixed(params, prefix) {
var _this4 = this;
var remove = params.map(function (i) {
return _this4.findProp(i);
}).filter(function (i) {
return i.slice(0, prefix.length) === prefix;
}).map(function (i) {
return _this4.prefixes.unprefixed(i);
});
var result = [];
for (var _iterator9 = params, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) {
var _ref7;
if (_isArray9) {
if (_i9 >= _iterator9.length) break;
_ref7 = _iterator9[_i9++];
} else {
_i9 = _iterator9.next();
if (_i9.done) break;
_ref7 = _i9.value;
}
var param = _ref7;
var prop = this.findProp(param);
var p = vendor.prefix(prop);
if (remove.indexOf(prop) === -1 && (p === prefix || p === '')) {
result.push(param);
}
}
return result;
};
/**
* Check property for disabled by option
*/
Transition.prototype.disabled = function disabled(prop, prefix) {
var other = ['order', 'justify-content', 'align-self', 'align-content'];
if (prop.indexOf('flex') !== -1 || other.indexOf(prop) !== -1) {
if (this.prefixes.options.flexbox === false) {
return true;
} else if (this.prefixes.options.flexbox === 'no-2009') {
return prefix.indexOf('2009') !== -1;
}
}
return undefined;
};
return Transition;
}();
module.exports = Transition;
},{"postcss-value-parser":524,"postcss/lib/list":536,"postcss/lib/vendor":551}],60:[function(require,module,exports){
'use strict';
var list = require('postcss/lib/list');
module.exports = {
/**
* Throw special error, to tell beniary,
* that this error is from Autoprefixer.
*/
error: function error(text) {
var err = new Error(text);
err.autoprefixer = true;
throw err;
},
/**
* Return array, that doesn’t contain duplicates.
*/
uniq: function uniq(array) {
var filtered = [];
for (var _iterator = array, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
if (filtered.indexOf(i) === -1) {
filtered.push(i);
}
}
return filtered;
},
/**
* Return "-webkit-" on "-webkit- old"
*/
removeNote: function removeNote(string) {
if (string.indexOf(' ') === -1) {
return string;
} else {
return string.split(' ')[0];
}
},
/**
* Escape RegExp symbols
*/
escapeRegexp: function escapeRegexp(string) {
return string.replace(/[.?*+\^\$\[\]\\(){}|\-]/g, '\\$&');
},
/**
* Return regexp to check, that CSS string contain word
*/
regexp: function regexp(word) {
var escape = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (escape) {
word = this.escapeRegexp(word);
}
return new RegExp('(^|[\\s,(])(' + word + '($|[\\s(,]))', 'gi');
},
/**
* Change comma list
*/
editList: function editList(value, callback) {
var origin = list.comma(value);
var changed = callback(origin, []);
if (origin === changed) {
return value;
} else {
var join = value.match(/,\s*/);
join = join ? join[0] : ', ';
return changed.join(join);
}
}
};
},{"postcss/lib/list":536}],61:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var Prefixer = require('./prefixer');
var OldValue = require('./old-value');
var utils = require('./utils');
var vendor = require('postcss/lib/vendor');
var Value = function (_Prefixer) {
_inherits(Value, _Prefixer);
function Value() {
_classCallCheck(this, Value);
return _possibleConstructorReturn(this, _Prefixer.apply(this, arguments));
}
/**
* Clone decl for each prefixed values
*/
Value.save = function save(prefixes, decl) {
var _this2 = this;
var prop = decl.prop;
var result = [];
for (var prefix in decl._autoprefixerValues) {
var value = decl._autoprefixerValues[prefix];
if (value === decl.value) {
continue;
}
var item = void 0;
var propPrefix = vendor.prefix(prop);
if (propPrefix === prefix) {
item = decl.value = value;
} else if (propPrefix === '-pie-') {
continue;
} else {
(function () {
var prefixed = prefixes.prefixed(prop, prefix);
var rule = decl.parent;
if (rule.every(function (i) {
return i.prop !== prefixed;
})) {
var trimmed = value.replace(/\s+/, ' ');
var already = rule.some(function (i) {
return i.prop === decl.prop && i.value.replace(/\s+/, ' ') === trimmed;
});
if (!already) {
var cloned = _this2.clone(decl, { value: value });
item = decl.parent.insertBefore(decl, cloned);
}
}
})();
}
result.push(item);
}
return result;
};
/**
* Is declaration need to be prefixed
*/
Value.prototype.check = function check(decl) {
var value = decl.value;
if (value.indexOf(this.name) !== -1) {
return !!value.match(this.regexp());
} else {
return false;
}
};
/**
* Lazy regexp loading
*/
Value.prototype.regexp = function regexp() {
return this.regexpCache || (this.regexpCache = utils.regexp(this.name));
};
/**
* Add prefix to values in string
*/
Value.prototype.replace = function replace(string, prefix) {
return string.replace(this.regexp(), '$1' + prefix + '$2');
};
/**
* Get value with comments if it was not changed
*/
Value.prototype.value = function value(decl) {
if (decl.raws.value && decl.raws.value.value === decl.value) {
return decl.raws.value.raw;
} else {
return decl.value;
}
};
/**
* Save values with next prefixed token
*/
Value.prototype.add = function add(decl, prefix) {
if (!decl._autoprefixerValues) {
decl._autoprefixerValues = {};
}
var value = decl._autoprefixerValues[prefix] || this.value(decl);
value = this.replace(value, prefix);
if (value) {
decl._autoprefixerValues[prefix] = value;
}
};
/**
* Return function to fast find prefixed value
*/
Value.prototype.old = function old(prefix) {
return new OldValue(this.name, prefix + this.name);
};
return Value;
}(Prefixer);
module.exports = Value;
},{"./old-value":52,"./prefixer":53,"./utils":60,"postcss/lib/vendor":551}],62:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var colorConvert = require('color-convert');
var wrapAnsi16 = function wrapAnsi16(fn, offset) {
return function () {
var code = fn.apply(colorConvert, arguments);
return '\x1B[' + (code + offset) + 'm';
};
};
var wrapAnsi256 = function wrapAnsi256(fn, offset) {
return function () {
var code = fn.apply(colorConvert, arguments);
return '\x1B[' + (38 + offset) + ';5;' + code + 'm';
};
};
var wrapAnsi16m = function wrapAnsi16m(fn, offset) {
return function () {
var rgb = fn.apply(colorConvert, arguments);
return '\x1B[' + (38 + offset) + ';2;' + rgb[0] + ';' + rgb[1] + ';' + rgb[2] + 'm';
};
};
function assembleStyles() {
var styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
// Bright color
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
// Fix humans
styles.color.grey = styles.color.gray;
Object.keys(styles).forEach(function (groupName) {
var group = styles[groupName];
Object.keys(group).forEach(function (styleName) {
var style = group[styleName];
styles[styleName] = {
open: '\x1B[' + style[0] + 'm',
close: '\x1B[' + style[1] + 'm'
};
group[styleName] = styles[styleName];
});
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
});
var rgb2rgb = function rgb2rgb(r, g, b) {
return [r, g, b];
};
styles.color.close = '\x1B[39m';
styles.bgColor.close = '\x1B[49m';
styles.color.ansi = {};
styles.color.ansi256 = {};
styles.color.ansi16m = {
rgb: wrapAnsi16m(rgb2rgb, 0)
};
styles.bgColor.ansi = {};
styles.bgColor.ansi256 = {};
styles.bgColor.ansi16m = {
rgb: wrapAnsi16m(rgb2rgb, 10)
};
for (var _iterator = Object.keys(colorConvert), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var key = _ref;
if (_typeof(colorConvert[key]) !== 'object') {
continue;
}
var suite = colorConvert[key];
if ('ansi16' in suite) {
styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
}
if ('ansi256' in suite) {
styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
}
if ('rgb' in suite) {
styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
}
}
return styles;
}
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});
},{"color-convert":515}],63:[function(require,module,exports){
'use strict';
exports.byteLength = byteLength;
exports.toByteArray = toByteArray;
exports.fromByteArray = fromByteArray;
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
revLookup['-'.charCodeAt(0)] = 62;
revLookup['_'.charCodeAt(0)] = 63;
function placeHoldersCount(b64) {
var len = b64.length;
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4');
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
}
function byteLength(b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64);
}
function toByteArray(b64) {
var i, l, tmp, placeHolders, arr;
var len = b64.length;
placeHolders = placeHoldersCount(b64);
arr = new Arr(len * 3 / 4 - placeHolders);
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len;
var L = 0;
for (i = 0; i < l; i += 4) {
tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
arr[L++] = tmp >> 16 & 0xFF;
arr[L++] = tmp >> 8 & 0xFF;
arr[L++] = tmp & 0xFF;
}
if (placeHolders === 2) {
tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
arr[L++] = tmp & 0xFF;
} else if (placeHolders === 1) {
tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
arr[L++] = tmp >> 8 & 0xFF;
arr[L++] = tmp & 0xFF;
}
return arr;
}
function tripletToBase64(num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
output.push(tripletToBase64(tmp));
}
return output.join('');
}
function fromByteArray(uint8) {
var tmp;
var len = uint8.length;
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
var output = '';
var parts = [];
var maxChunkLength = 16383; // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
output += lookup[tmp >> 2];
output += lookup[tmp << 4 & 0x3F];
output += '==';
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
output += lookup[tmp >> 10];
output += lookup[tmp >> 4 & 0x3F];
output += lookup[tmp << 2 & 0x3F];
output += '=';
}
parts.push(output);
return parts.join('');
}
},{}],64:[function(require,module,exports){
"use strict";
},{}],65:[function(require,module,exports){
(function (process){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var path = require('path');
var e2c = require('electron-to-chromium/versions');
var fs = require('fs');
var caniuse = require('caniuse-lite').agents;
var region = require('caniuse-lite').region;
function normalize(versions) {
return versions.filter(function (version) {
return typeof version === 'string';
});
}
var FLOAT_RANGE = /^\d+(\.\d+)?(-\d+(\.\d+)?)*$/;
var IS_SECTION = /^\s*\[(.+)\]\s*$/;
function uniq(array) {
var filtered = [];
for (var i = 0; i < array.length; i++) {
if (filtered.indexOf(array[i]) === -1) filtered.push(array[i]);
}
return filtered;
}
function BrowserslistError(message) {
this.name = 'BrowserslistError';
this.message = message || '';
this.browserslist = true;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, BrowserslistError);
}
}
BrowserslistError.prototype = Error.prototype;
// Helpers
function error(name) {
throw new BrowserslistError(name);
}
function fillUsage(result, name, data) {
for (var i in data) {
result[name + ' ' + i] = data[i];
}
}
var cacheEnabled = !(process && process.env && process.env.BROWSERSLIST_DISABLE_CACHE);
var filenessCache = {};
var configCache = {};
function isFile(file) {
if (!fs.existsSync) {
return false;
}
if (file in filenessCache) {
return filenessCache[file];
}
var result = fs.existsSync(file) && fs.statSync(file).isFile();
if (cacheEnabled) {
filenessCache[file] = result;
}
return result;
}
function eachParent(file, callback) {
var loc = path.resolve(file);
do {
var result = callback(loc);
if (typeof result !== 'undefined') return result;
} while (loc !== (loc = path.dirname(loc)));
return undefined;
}
function getStat(opts) {
if (opts.stats) {
return opts.stats;
} else if (process.env.BROWSERSLIST_STATS) {
return process.env.BROWSERSLIST_STATS;
} else if (opts.path) {
return eachParent(opts.path, function (dir) {
var file = path.join(dir, 'browserslist-stats.json');
if (isFile(file)) {
return file;
}
});
}
}
function parsePackage(file) {
var config = JSON.parse(fs.readFileSync(file)).browserslist;
if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config.length) {
config = { defaults: config };
}
return config;
}
function pickEnv(config, opts) {
if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) !== 'object') return config;
var env;
if (typeof opts.env === 'string') {
env = opts.env;
} else if (typeof process.env.BROWSERSLIST_ENV === 'string') {
env = process.env.BROWSERSLIST_ENV;
} else if (typeof process.env.NODE_ENV === 'string') {
env = process.env.NODE_ENV;
} else {
env = 'development';
}
return config[env] || config.defaults;
}
function generateFilter(sign, version) {
version = parseFloat(version);
if (sign === '>') {
return function (v) {
return parseFloat(v) > version;
};
} else if (sign === '>=') {
return function (v) {
return parseFloat(v) >= version;
};
} else if (sign === '<') {
return function (v) {
return parseFloat(v) < version;
};
} else if (sign === '<=') {
return function (v) {
return parseFloat(v) <= version;
};
}
}
function compareStrings(a, b) {
if (a < b) return -1;
if (a > b) return +1;
return 0;
}
/**
* Return array of browsers by selection queries.
*
* @param {string[]} queries Browser queries.
* @param {object} opts Options.
* @param {string} [opts.path="."] Path to processed file.
* It will be used to find config files.
* @param {string} [opts.env="development"] Processing environment.
* It will be used to take right
* queries from config file.
* @param {string} [opts.config] Path to config file with queries.
* @param {object} [opts.stats] Custom browser usage statistics
* for "> 1% in my stats" query.
* @return {string[]} Array with browser names in Can I Use.
*
* @example
* browserslist('IE >= 10, IE 8') //=> ['ie 11', 'ie 10', 'ie 8']
*/
var browserslist = function browserslist(queries, opts) {
if (typeof opts === 'undefined') opts = {};
if (!opts.hasOwnProperty('path')) {
opts.path = path.resolve('.');
}
if (typeof queries === 'undefined' || queries === null) {
if (process.env.BROWSERSLIST) {
queries = process.env.BROWSERSLIST;
} else if (opts.config || process.env.BROWSERSLIST_CONFIG) {
var file = opts.config || process.env.BROWSERSLIST_CONFIG;
if (path.basename(file) === 'package.json') {
queries = pickEnv(parsePackage(file), opts);
} else {
queries = pickEnv(browserslist.readConfig(file), opts);
}
} else if (opts.path) {
queries = pickEnv(browserslist.findConfig(opts.path), opts);
}
}
if (typeof queries === 'undefined' || queries === null) {
queries = browserslist.defaults;
}
if (typeof queries === 'string') {
queries = queries.split(/,\s*/);
}
var context = {};
var stats = getStat(opts);
if (stats) {
if (typeof stats === 'string') {
try {
stats = JSON.parse(fs.readFileSync(stats));
} catch (e) {
error('Can\'t read ' + stats);
}
}
if ('dataByBrowser' in stats) {
stats = stats.dataByBrowser;
}
context.customUsage = {};
for (var browser in stats) {
fillUsage(context.customUsage, browser, stats[browser]);
}
}
var result = [];
queries.forEach(function (selection, index) {
if (selection.trim() === '') return;
var exclude = selection.indexOf('not ') === 0;
if (exclude) {
if (index === 0) {
error('Write any browsers query (for instance, `defaults`) ' + 'before `' + selection + '`');
}
selection = selection.slice(4);
}
for (var i in browserslist.queries) {
var type = browserslist.queries[i];
var match = selection.match(type.regexp);
if (match) {
var args = [context].concat(match.slice(1));
var array = type.select.apply(browserslist, args);
if (exclude) {
array = array.concat(array.map(function (j) {
return j.replace(/\s\d+/, ' 0');
}));
result = result.filter(function (j) {
return array.indexOf(j) === -1;
});
} else {
result = result.concat(array);
}
return;
}
}
error('Unknown browser query `' + selection + '`');
});
result = result.map(function (i) {
var parts = i.split(' ');
var name = parts[0];
var version = parts[1];
if (version === '0') {
return name + ' ' + browserslist.byName(name).versions[0];
} else {
return i;
}
}).sort(function (name1, name2) {
name1 = name1.split(' ');
name2 = name2.split(' ');
if (name1[0] === name2[0]) {
if (FLOAT_RANGE.test(name1[1]) && FLOAT_RANGE.test(name2[1])) {
return parseFloat(name2[1]) - parseFloat(name1[1]);
} else {
return compareStrings(name2[1], name1[1]);
}
} else {
return compareStrings(name1[0], name2[0]);
}
});
return uniq(result);
};
var normalizeVersion = function normalizeVersion(data, version) {
if (data.versions.indexOf(version) !== -1) {
return version;
} else if (browserslist.versionAliases[data.name][version]) {
return browserslist.versionAliases[data.name][version];
} else if (data.versions.length === 1) {
return data.versions[0];
}
};
var loadCountryStatistics = function loadCountryStatistics(country) {
if (!browserslist.usage[country]) {
var usage = {};
var data = region(require('caniuse-lite/data/regions/' + country + '.js'));
for (var i in data) {
fillUsage(usage, i, data[i]);
}
browserslist.usage[country] = usage;
}
};
// Will be filled by Can I Use data below
browserslist.data = {};
browserslist.usage = {
global: {},
custom: null
};
// Default browsers query
browserslist.defaults = ['> 1%', 'last 2 versions', 'Firefox ESR'];
// Browser names aliases
browserslist.aliases = {
fx: 'firefox',
ff: 'firefox',
ios: 'ios_saf',
explorer: 'ie',
blackberry: 'bb',
explorermobile: 'ie_mob',
operamini: 'op_mini',
operamobile: 'op_mob',
chromeandroid: 'and_chr',
firefoxandroid: 'and_ff',
ucandroid: 'and_uc',
qqandroid: 'and_qq'
};
// Aliases to work with joined versions like `ios_saf 7.0-7.1`
browserslist.versionAliases = {};
// Get browser data by alias or case insensitive name
browserslist.byName = function (name) {
name = name.toLowerCase();
name = browserslist.aliases[name] || name;
return browserslist.data[name];
};
// Get browser data by alias or case insensitive name and throw error
// on unknown browser
browserslist.checkName = function (name) {
var data = browserslist.byName(name);
if (!data) error('Unknown browser ' + name);
return data;
};
// Read and parse config
browserslist.readConfig = function (file) {
if (!isFile(file)) {
error('Can\'t read ' + file + ' config');
}
return browserslist.parseConfig(fs.readFileSync(file));
};
// Find config, read file and parse it
browserslist.findConfig = function (from) {
from = path.resolve(from);
var cacheKey = isFile(from) ? path.dirname(from) : from;
if (cacheKey in configCache) {
return configCache[cacheKey];
}
var resolved = eachParent(from, function (dir) {
var config = path.join(dir, 'browserslist');
var pkg = path.join(dir, 'package.json');
var rc = path.join(dir, '.browserslistrc');
var pkgBrowserslist;
if (isFile(pkg)) {
try {
pkgBrowserslist = parsePackage(pkg);
} catch (e) {
console.warn('[Browserslist] Could not parse ' + pkg + '. ' + 'Ignoring it.');
}
}
if (isFile(config) && pkgBrowserslist) {
error(dir + ' contains both browserslist ' + 'and package.json with browsers');
} else if (isFile(rc) && pkgBrowserslist) {
error(dir + ' contains both .browserslistrc ' + 'and package.json with browsers');
} else if (isFile(config) && isFile(rc)) {
error(dir + ' contains both .browserslistrc and browserslist');
} else if (isFile(config)) {
return browserslist.readConfig(config);
} else if (isFile(rc)) {
return browserslist.readConfig(rc);
} else if (pkgBrowserslist) {
return pkgBrowserslist;
}
});
if (cacheEnabled) {
configCache[cacheKey] = resolved;
}
return resolved;
};
/**
* Return browsers market coverage.
*
* @param {string[]} browsers Browsers names in Can I Use.
* @param {string} [country="global"] Which country statistics should be used.
*
* @return {number} Total market coverage for all selected browsers.
*
* @example
* browserslist.coverage(browserslist('> 1% in US'), 'US') //=> 83.1
*/
browserslist.coverage = function (browsers, country) {
if (country && country !== 'global') {
country = country.toUpperCase();
loadCountryStatistics(country);
} else {
country = 'global';
}
return browsers.reduce(function (all, i) {
var usage = browserslist.usage[country][i];
if (usage === undefined) {
usage = browserslist.usage[country][i.replace(/ [\d.]+$/, ' 0')];
}
return all + (usage || 0);
}, 0);
};
// Return array of queries from config content
browserslist.parseConfig = function (string) {
var result = { defaults: [] };
var section = 'defaults';
string.toString().replace(/#[^\n]*/g, '').split(/\n/).map(function (line) {
return line.trim();
}).filter(function (line) {
return line !== '';
}).forEach(function (line) {
if (IS_SECTION.test(line)) {
section = line.match(IS_SECTION)[1].trim();
result[section] = result[section] || [];
} else {
result[section].push(line);
}
});
return result;
};
// Clear internal caches
browserslist.clearCaches = function () {
filenessCache = {};
configCache = {};
};
browserslist.queries = {
lastVersions: {
regexp: /^last\s+(\d+)\s+versions?$/i,
select: function select(context, versions) {
var selected = [];
Object.keys(caniuse).forEach(function (name) {
var data = browserslist.byName(name);
if (!data) return;
var array = data.released.slice(-versions);
array = array.map(function (v) {
return data.name + ' ' + v;
});
selected = selected.concat(array);
});
return selected;
}
},
lastByBrowser: {
regexp: /^last\s+(\d+)\s+(\w+)\s+versions?$/i,
select: function select(context, versions, name) {
var data = browserslist.checkName(name);
return data.released.slice(-versions).map(function (v) {
return data.name + ' ' + v;
});
}
},
globalStatistics: {
regexp: /^(>=?)\s*(\d*\.?\d+)%$/,
select: function select(context, sign, popularity) {
popularity = parseFloat(popularity);
var result = [];
for (var version in browserslist.usage.global) {
if (sign === '>') {
if (browserslist.usage.global[version] > popularity) {
result.push(version);
}
} else if (browserslist.usage.global[version] >= popularity) {
result.push(version);
}
}
return result;
}
},
customStatistics: {
regexp: /^(>=?)\s*(\d*\.?\d+)%\s+in\s+my\s+stats$/,
select: function select(context, sign, popularity) {
popularity = parseFloat(popularity);
var result = [];
if (!context.customUsage) {
error('Custom usage statistics was not provided');
}
for (var version in context.customUsage) {
if (sign === '>') {
if (context.customUsage[version] > popularity) {
result.push(version);
}
} else if (context.customUsage[version] >= popularity) {
result.push(version);
}
}
return result;
}
},
countryStatistics: {
regexp: /^(>=?)\s*(\d*\.?\d+)%\s+in\s+(\w\w)$/,
select: function select(context, sign, popularity, country) {
popularity = parseFloat(popularity);
country = country.toUpperCase();
var result = [];
loadCountryStatistics(country);
var usage = browserslist.usage[country];
for (var version in usage) {
if (sign === '>') {
if (usage[version] > popularity) {
result.push(version);
}
} else if (usage[version] >= popularity) {
result.push(version);
}
}
return result;
}
},
electronRange: {
regexp: /^electron\s+([\d\.]+)\s*-\s*([\d\.]+)$/i,
select: function select(context, from, to) {
if (!e2c[from]) error('Unknown version ' + from + ' of electron');
if (!e2c[to]) error('Unknown version ' + to + ' of electron');
from = parseFloat(from);
to = parseFloat(to);
return Object.keys(e2c).filter(function (i) {
var parsed = parseFloat(i);
return parsed >= from && parsed <= to;
}).map(function (i) {
return 'chrome ' + e2c[i];
});
}
},
range: {
regexp: /^(\w+)\s+([\d\.]+)\s*-\s*([\d\.]+)$/i,
select: function select(context, name, from, to) {
var data = browserslist.checkName(name);
from = parseFloat(normalizeVersion(data, from) || from);
to = parseFloat(normalizeVersion(data, to) || to);
var filter = function filter(v) {
var parsed = parseFloat(v);
return parsed >= from && parsed <= to;
};
return data.released.filter(filter).map(function (v) {
return data.name + ' ' + v;
});
}
},
electronVersions: {
regexp: /^electron\s*(>=?|<=?)\s*([\d\.]+)$/i,
select: function select(context, sign, version) {
return Object.keys(e2c).filter(generateFilter(sign, version)).map(function (i) {
return 'chrome ' + e2c[i];
});
}
},
versions: {
regexp: /^(\w+)\s*(>=?|<=?)\s*([\d\.]+)$/,
select: function select(context, name, sign, version) {
var data = browserslist.checkName(name);
var alias = normalizeVersion(data, version);
if (alias) {
version = alias;
}
return data.released.filter(generateFilter(sign, version)).map(function (v) {
return data.name + ' ' + v;
});
}
},
esr: {
regexp: /^(firefox|ff|fx)\s+esr$/i,
select: function select() {
return ['firefox 52'];
}
},
opMini: {
regexp: /(operamini|op_mini)\s+all/i,
select: function select() {
return ['op_mini all'];
}
},
electron: {
regexp: /^electron\s+([\d\.]+)$/i,
select: function select(context, version) {
var chrome = e2c[version];
if (!chrome) error('Unknown version ' + version + ' of electron');
return ['chrome ' + chrome];
}
},
direct: {
regexp: /^(\w+)\s+(tp|[\d\.]+)$/i,
select: function select(context, name, version) {
if (/tp/i.test(version)) version = 'TP';
var data = browserslist.checkName(name);
var alias = normalizeVersion(data, version);
if (alias) {
version = alias;
} else {
if (version.indexOf('.') === -1) {
alias = version + '.0';
} else if (/\.0$/.test(version)) {
alias = version.replace(/\.0$/, '');
}
alias = normalizeVersion(data, alias);
if (alias) {
version = alias;
} else {
error('Unknown version ' + version + ' of ' + name);
}
}
return [data.name + ' ' + version];
}
},
defaults: {
regexp: /^defaults$/i,
select: function select() {
return browserslist(browserslist.defaults);
}
}
};
// Get and convert Can I Use data
(function () {
for (var name in caniuse) {
var browser = caniuse[name];
browserslist.data[name] = {
name: name,
versions: normalize(caniuse[name].versions),
released: normalize(caniuse[name].versions.slice(0, -3))
};
fillUsage(browserslist.usage.global, name, browser.usage_global);
browserslist.versionAliases[name] = {};
for (var i = 0; i < browser.versions.length; i++) {
var full = browser.versions[i];
if (!full) continue;
if (full.indexOf('-') !== -1) {
var interval = full.split('-');
for (var j = 0; j < interval.length; j++) {
browserslist.versionAliases[name][interval[j]] = full;
}
}
}
}
})();
module.exports = browserslist;
}).call(this,require('_process'))
},{"_process":557,"caniuse-lite":513,"electron-to-chromium/versions":518,"fs":64,"path":523}],66:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict';
var base64 = require('base64-js');
var ieee754 = require('ieee754');
exports.Buffer = Buffer;
exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50;
var K_MAX_LENGTH = 0x7fffffff;
exports.kMaxLength = K_MAX_LENGTH;
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') {
console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.');
}
function typedArraySupport() {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1);
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function foo() {
return 42;
} };
return arr.foo() === 42;
} catch (e) {
return false;
}
}
function createBuffer(length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length');
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length);
buf.__proto__ = Buffer.prototype;
return buf;
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer(arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error('If encoding is specified then the first argument must be a string');
}
return allocUnsafe(arg);
}
return from(arg, encodingOrOffset, length);
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
});
}
Buffer.poolSize = 8192; // not used by this implementation
function from(value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number');
}
if (value instanceof ArrayBuffer) {
return fromArrayBuffer(value, encodingOrOffset, length);
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset);
}
return fromObject(value);
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length);
};
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype;
Buffer.__proto__ = Uint8Array;
function assertSize(size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number');
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative');
}
}
function alloc(size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(size);
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
}
return createBuffer(size);
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding);
};
function allocUnsafe(size) {
assertSize(size);
return createBuffer(size < 0 ? 0 : checked(size) | 0);
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size);
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size);
};
function fromString(string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8';
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding');
}
var length = byteLength(string, encoding) | 0;
var buf = createBuffer(length);
var actual = buf.write(string, encoding);
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual);
}
return buf;
}
function fromArrayLike(array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0;
var buf = createBuffer(length);
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255;
}
return buf;
}
function fromArrayBuffer(array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds');
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds');
}
var buf;
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array);
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset);
} else {
buf = new Uint8Array(array, byteOffset, length);
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype;
return buf;
}
function fromObject(obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0;
var buf = createBuffer(len);
if (buf.length === 0) {
return buf;
}
obj.copy(buf, 0, 0, len);
return buf;
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0);
}
return fromArrayLike(obj);
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data);
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.');
}
function checked(length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes');
}
return length | 0;
}
function SlowBuffer(length) {
if (+length != length) {
// eslint-disable-line eqeqeq
length = 0;
}
return Buffer.alloc(+length);
}
Buffer.isBuffer = function isBuffer(b) {
return b != null && b._isBuffer === true;
};
Buffer.compare = function compare(a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers');
}
if (a === b) return 0;
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
Buffer.isEncoding = function isEncoding(encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true;
default:
return false;
}
};
Buffer.concat = function concat(list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
if (list.length === 0) {
return Buffer.alloc(0);
}
var i;
if (length === undefined) {
length = 0;
for (i = 0; i < list.length; ++i) {
length += list[i].length;
}
}
var buffer = Buffer.allocUnsafe(length);
var pos = 0;
for (i = 0; i < list.length; ++i) {
var buf = list[i];
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
buf.copy(buffer, pos);
pos += buf.length;
}
return buffer;
};
function byteLength(string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length;
}
if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
return string.byteLength;
}
if (typeof string !== 'string') {
string = '' + string;
}
var len = string.length;
if (len === 0) return 0;
// Use a for loop to avoid recursion
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len;
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length;
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2;
case 'hex':
return len >>> 1;
case 'base64':
return base64ToBytes(string).length;
default:
if (loweredCase) return utf8ToBytes(string).length; // assume utf8
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer.byteLength = byteLength;
function slowToString(encoding, start, end) {
var loweredCase = false;
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0;
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return '';
}
if (end === undefined || end > this.length) {
end = this.length;
}
if (end <= 0) {
return '';
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0;
start >>>= 0;
if (end <= start) {
return '';
}
if (!encoding) encoding = 'utf8';
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end);
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end);
case 'ascii':
return asciiSlice(this, start, end);
case 'latin1':
case 'binary':
return latin1Slice(this, start, end);
case 'base64':
return base64Slice(this, start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end);
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
encoding = (encoding + '').toLowerCase();
loweredCase = true;
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true;
function swap(b, n, m) {
var i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer.prototype.swap16 = function swap16() {
var len = this.length;
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits');
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1);
}
return this;
};
Buffer.prototype.swap32 = function swap32() {
var len = this.length;
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits');
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this;
};
Buffer.prototype.swap64 = function swap64() {
var len = this.length;
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits');
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this;
};
Buffer.prototype.toString = function toString() {
var length = this.length;
if (length === 0) return '';
if (arguments.length === 0) return utf8Slice(this, 0, length);
return slowToString.apply(this, arguments);
};
Buffer.prototype.equals = function equals(b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer');
if (this === b) return true;
return Buffer.compare(this, b) === 0;
};
Buffer.prototype.inspect = function inspect() {
var str = '';
var max = exports.INSPECT_MAX_BYTES;
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
if (this.length > max) str += ' ... ';
}
return '<Buffer ' + str + '>';
};
Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer');
}
if (start === undefined) {
start = 0;
}
if (end === undefined) {
end = target ? target.length : 0;
}
if (thisStart === undefined) {
thisStart = 0;
}
if (thisEnd === undefined) {
thisEnd = this.length;
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index');
}
if (thisStart >= thisEnd && start >= end) {
return 0;
}
if (thisStart >= thisEnd) {
return -1;
}
if (start >= end) {
return 1;
}
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0;
var x = thisEnd - thisStart;
var y = end - start;
var len = Math.min(x, y);
var thisCopy = this.slice(thisStart, thisEnd);
var targetCopy = target.slice(start, end);
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1;
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff;
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000;
}
byteOffset = +byteOffset; // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : buffer.length - 1;
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
if (byteOffset >= buffer.length) {
if (dir) return -1;else byteOffset = buffer.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;else return -1;
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding);
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1;
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
} else if (typeof val === 'number') {
val = val & 0xFF; // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
}
}
return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
}
throw new TypeError('val must be string, number or Buffer');
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
var indexSize = 1;
var arrLength = arr.length;
var valLength = val.length;
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase();
if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1;
}
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read(buf, i) {
if (indexSize === 1) {
return buf[i];
} else {
return buf.readUInt16BE(i * indexSize);
}
}
var i;
if (dir) {
var foundIndex = -1;
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for (i = byteOffset; i >= 0; i--) {
var found = true;
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false;
break;
}
}
if (found) return i;
}
}
return -1;
}
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
offset = Number(offset) || 0;
var remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
// must be an even number of digits
var strLen = string.length;
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string');
if (length > strLen / 2) {
length = strLen / 2;
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16);
if (numberIsNaN(parsed)) return i;
buf[offset + i] = parsed;
}
return i;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function latin1Write(buf, string, offset, length) {
return asciiWrite(buf, string, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer.prototype.write = function write(string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8';
length = this.length;
offset = 0;
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0;
if (isFinite(length)) {
length = length >>> 0;
if (encoding === undefined) encoding = 'utf8';
} else {
encoding = length;
length = undefined;
}
} else {
throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
}
var remaining = this.length - offset;
if (length === undefined || length > remaining) length = remaining;
if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds');
}
if (!encoding) encoding = 'utf8';
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length);
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length);
case 'ascii':
return asciiWrite(this, string, offset, length);
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length);
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length);
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
};
Buffer.prototype.toJSON = function toJSON() {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
};
};
function base64Slice(buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf);
} else {
return base64.fromByteArray(buf.slice(start, end));
}
}
function utf8Slice(buf, start, end) {
end = Math.min(buf.length, end);
var res = [];
var i = start;
while (i < end) {
var firstByte = buf[i];
var codePoint = null;
var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte;
}
break;
case 2:
secondByte = buf[i + 1];
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint;
}
}
break;
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint;
}
}
break;
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD;
bytesPerSequence = 1;
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000;
res.push(codePoint >>> 10 & 0x3FF | 0xD800);
codePoint = 0xDC00 | codePoint & 0x3FF;
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000;
function decodeCodePointsArray(codePoints) {
var len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = '';
var i = 0;
while (i < len) {
res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
}
return res;
}
function asciiSlice(buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F);
}
return ret;
}
function latin1Slice(buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i]);
}
return ret;
}
function hexSlice(buf, start, end) {
var len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
var out = '';
for (var i = start; i < end; ++i) {
out += toHex(buf[i]);
}
return out;
}
function utf16leSlice(buf, start, end) {
var bytes = buf.slice(start, end);
var res = '';
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
}
return res;
}
Buffer.prototype.slice = function slice(start, end) {
var len = this.length;
start = ~~start;
end = end === undefined ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) {
end = len;
}
if (end < start) end = start;
var newBuf = this.subarray(start, end);
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype;
return newBuf;
};
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
}
Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
return val;
};
Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
checkOffset(offset, byteLength, this.length);
}
var val = this[offset + --byteLength];
var mul = 1;
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul;
}
return val;
};
Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset];
};
Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | this[offset + 1] << 8;
};
Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] << 8 | this[offset + 1];
};
Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
};
Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var i = byteLength;
var mul = 1;
var val = this[offset + --i];
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 0x80)) return this[offset];
return (0xff - this[offset] + 1) * -1;
};
Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset] | this[offset + 1] << 8;
return val & 0x8000 ? val | 0xFFFF0000 : val;
};
Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset + 1] | this[offset] << 8;
return val & 0x8000 ? val | 0xFFFF0000 : val;
};
Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, true, 23, 4);
};
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, false, 23, 4);
};
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, true, 52, 8);
};
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError('Index out of range');
}
Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var mul = 1;
var i = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = value / mul & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var i = byteLength - 1;
var mul = 1;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = value / mul & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset + 3] = value >>> 24;
this[offset + 2] = value >>> 16;
this[offset + 1] = value >>> 8;
this[offset] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = 0;
var mul = 1;
var sub = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1;
}
this[offset + i] = (value / mul >> 0) - sub & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = byteLength - 1;
var mul = 1;
var sub = 0;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1;
}
this[offset + i] = (value / mul >> 0) - sub & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
if (value < 0) value = 0xff + value + 1;
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
this[offset + 2] = value >>> 16;
this[offset + 3] = value >>> 24;
return offset + 4;
};
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (value < 0) value = 0xffffffff + value + 1;
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
function checkIEEE754(buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range');
if (offset < 0) throw new RangeError('Index out of range');
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38);
}
ieee754.write(buf, value, offset, littleEndian, 23, 4);
return offset + 4;
}
Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert);
};
Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308);
}
ieee754.write(buf, value, offset, littleEndian, 52, 8);
return offset + 8;
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert);
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert);
};
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy(target, targetStart, start, end) {
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
// Copy 0 bytes; we're done
if (end === start) return 0;
if (target.length === 0 || this.length === 0) return 0;
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds');
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds');
if (end < 0) throw new RangeError('sourceEnd out of bounds');
// Are we oob?
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start;
}
var len = end - start;
var i;
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start];
}
} else if (len < 1000) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start];
}
} else {
Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
}
return len;
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill(val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === 'string') {
encoding = end;
end = this.length;
}
if (val.length === 1) {
var code = val.charCodeAt(0);
if (code < 256) {
val = code;
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string');
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding);
}
} else if (typeof val === 'number') {
val = val & 255;
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index');
}
if (end <= start) {
return this;
}
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
if (!val) val = 0;
var i;
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val;
}
} else {
var bytes = Buffer.isBuffer(val) ? val : new Buffer(val, encoding);
var len = bytes.length;
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len];
}
}
return this;
};
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
function base64clean(str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '');
// Node converts strings with length < 2 to ''
if (str.length < 2) return '';
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '=';
}
return str;
}
function toHex(n) {
if (n < 16) return '0' + n.toString(16);
return n.toString(16);
}
function utf8ToBytes(string, units) {
units = units || Infinity;
var codePoint;
var length = string.length;
var leadSurrogate = null;
var bytes = [];
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i);
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue;
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue;
}
// valid lead
leadSurrogate = codePoint;
continue;
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
leadSurrogate = codePoint;
continue;
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
}
leadSurrogate = null;
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break;
bytes.push(codePoint);
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break;
bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break;
bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break;
bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
} else {
throw new Error('Invalid code point');
}
}
return bytes;
}
function asciiToBytes(str) {
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF);
}
return byteArray;
}
function utf16leToBytes(str, units) {
var c, hi, lo;
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break;
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray;
}
function base64ToBytes(str) {
return base64.toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if (i + offset >= dst.length || i >= src.length) break;
dst[i + offset] = src[i];
}
return i;
}
// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
function isArrayBufferView(obj) {
return typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(obj);
}
function numberIsNaN(obj) {
return obj !== obj; // eslint-disable-line no-self-compare
}
},{"base64-js":63,"ieee754":520}],67:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { J: 0.0174923, C: 0.0218654, G: 0.319234, E: 0.183669, B: 0.183669, A: 3.32354, TB: 0.009298 }, B: "ms", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "TB", "J", "C", "G", "E", "B", "A", "", "", ""], E: "IE" }, B: { A: { D: 0.04227, X: 0.097221, g: 1.09057, H: 0, L: 0 }, B: "ms", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "D", "X", "g", "H", "L", "", ""], E: "Edge" }, C: { A: { "0": 2.66724, "1": 0.016908, "2": 0.038043, "4": 0, RB: 0.004227, F: 0.004227, I: 0.004879, J: 0.020136, C: 0.005725, G: 0.012681, E: 0.00533, B: 0.004227, A: 0.008454, D: 0.008454, X: 0.004486, g: 0.00453, H: 0.008454, L: 0.008454, M: 0.004227, N: 0.008454, O: 0.004443, P: 0.004227, Q: 0.012681, R: 0.004227, S: 0.008454, T: 0.008454, U: 0.012681, V: 0.004227, W: 0.004227, u: 0.004227, Y: 0.008454, Z: 0.012681, a: 0.021135, b: 0.008454, c: 0.012681, d: 0.008454, e: 0.012681, f: 0.016908, K: 0.016908, h: 0.046497, i: 0.016908, j: 0.016908, k: 0.025362, l: 0.021135, m: 0.050724, n: 0.021135, o: 0.114129, p: 0.021135, q: 0.097221, r: 0.156399, w: 0.097221, x: 0.08454, v: 0.143718, z: 0.528375, t: 1.41182, s: 0, PB: 0.004534, OB: 0.012681 }, B: "moz", C: ["", "RB", "1", "PB", "OB", "F", "I", "J", "C", "G", "E", "B", "A", "D", "X", "g", "H", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "u", "Y", "Z", "a", "b", "c", "d", "e", "f", "K", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "w", "x", "v", "z", "0", "t", "2", "s", "4"], E: "Firefox" }, D: { A: { "0": 0.076086, "2": 0.274755, "4": 0.410019, "8": 3.2252, F: 0.004706, I: 0.004879, J: 0.004879, C: 0.005591, G: 0.005591, E: 0.005591, B: 0.004534, A: 0.021135, D: 0.004367, X: 0.004879, g: 0.004706, H: 0.004706, L: 0.004227, M: 0.004227, N: 0.008454, O: 0.008454, P: 0.004227, Q: 0.008454, R: 0.029589, S: 0.008454, T: 0.016908, U: 0.008454, V: 0.016908, W: 0.008454, u: 0.008454, Y: 0.016908, Z: 0.012681, a: 0.071859, b: 0.012681, c: 0.029589, d: 0.033816, e: 0.021135, f: 0.054951, K: 0.016908, h: 0.033816, i: 0.029589, j: 0.021135, k: 0.033816, l: 0.033816, m: 0.177534, n: 0.029589, o: 0.312798, p: 0.033816, q: 0.088767, r: 0.067632, w: 1.07789, x: 0.105675, v: 0.160626, z: 0.050724, t: 0.152172, s: 0.376203, DB: 18.7552, AB: 0.067632, SB: 0.04227, BB: 0 }, B: "webkit", C: ["F", "I", "J", "C", "G", "E", "B", "A", "D", "X", "g", "H", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "u", "Y", "Z", "a", "b", "c", "d", "e", "f", "K", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "w", "x", "v", "z", "0", "t", "2", "s", "4", "DB", "8", "AB", "SB", "BB"], E: "Chrome" }, E: { A: { "7": 0.008692, F: 0.008454, I: 0.021135, J: 0.004227, C: 0.012681, G: 0.059178, E: 0.067632, B: 0.304344, A: 0, CB: 0, EB: 0.04227, FB: 0.025362, GB: 0.004227, HB: 0.266301, IB: 1.31037, JB: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "CB", "7", "F", "I", "EB", "J", "FB", "C", "GB", "G", "E", "HB", "B", "IB", "A", "JB", ""], E: "Safari" }, F: { A: { "5": 0.004879, "6": 0.006229, E: 0.0082, A: 0.016581, D: 0.004227, H: 0.00685, L: 0.00685, M: 0.00685, N: 0.005014, O: 0.006015, P: 0.004879, Q: 0.006597, R: 0.006597, S: 0.013434, T: 0.006702, U: 0.006015, V: 0.005595, W: 0.004706, u: 0.008454, Y: 0.004879, Z: 0.004879, a: 0.00533, b: 0.005152, c: 0.005014, d: 0.009758, e: 0.004879, f: 0.029589, K: 0.004227, h: 0.004367, i: 0.004534, j: 0.004367, k: 0.004227, l: 0.008454, m: 0.021135, n: 0.004227, o: 0.667866, p: 0.025362, q: 0, r: 0, KB: 0.00685, LB: 0, MB: 0.008392, NB: 0.004706, QB: 0.004534, y: 0.076086 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "E", "KB", "LB", "MB", "NB", "A", "6", "5", "QB", "D", "y", "H", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "u", "Y", "Z", "a", "b", "c", "d", "e", "f", "K", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", ""], E: "Opera", D: { "5": "o", "6": "o", E: "o", A: "o", D: "o", KB: "o", LB: "o", MB: "o", NB: "o", QB: "o", y: "o" } }, G: { A: { "3": 0, "7": 0, "9": 0, G: 0, A: 0, UB: 0, VB: 0, WB: 0.0541219, XB: 0.0413873, YB: 0.0318364, ZB: 0.581545, aB: 1.98341, bB: 7.55478 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "7", "9", "3", "UB", "VB", "WB", "G", "XB", "YB", "ZB", "aB", "bB", "A", "", ""], E: "iOS Safari" }, H: { A: { cB: 3.08635 }, B: "o", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "cB", "", "", ""], E: "Opera Mini" }, I: { A: { "1": 0, "3": 0.353639, F: 0, s: 0, dB: 0, eB: 0, fB: 0, gB: 0.136723, hB: 0.950487, iB: 0.550836 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "dB", "eB", "fB", "1", "F", "gB", "3", "hB", "iB", "s", "", "", ""], E: "Android Browser" }, J: { A: { C: 0.0331948, B: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "C", "B", "", "", ""], E: "Blackberry Browser" }, K: { A: { "5": 0, "6": 0, B: 0, A: 0, D: 0, K: 0.0137477, y: 0 }, B: "o", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "B", "A", "6", "5", "D", "y", "K", "", "", ""], E: "Opera Mobile", D: { K: "webkit" } }, L: { A: { "8": 28.8994 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "8", "", "", ""], E: "Chrome for Android" }, M: { A: { t: 0.034638 }, B: "moz", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "t", "", "", ""], E: "Firefox for Android" }, N: { A: { B: 0.05773, A: 0.317515 }, B: "ms", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "B", "A", "", "", ""], E: "IE Mobile" }, O: { A: { jB: 9.13289 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "jB", "", "", ""], E: "UC Browser for Android", D: { jB: "webkit" } }, P: { A: { F: 3.79286, I: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "F", "I", "", "", ""], E: "Samsung Internet" }, Q: { A: { kB: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "kB", "", "", ""], E: "QQ Browser" }, R: { A: { lB: 0 }, B: "webkit", C: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "lB", "", "", ""], E: "Baidu Browser" } };
},{}],68:[function(require,module,exports){
"use strict";
module.exports = { "0": "53", "1": "3", "2": "55", "3": "4.2-4.3", "4": "57", "5": "11.5", "6": "11.1", "7": "3.2", "8": "59", "9": "4.0-4.1", A: "11", B: "10", C: "7", D: "12", E: "9", F: "4", G: "8", H: "15", I: "5", J: "6", K: "37", L: "16", M: "17", N: "18", O: "19", P: "20", Q: "21", R: "22", S: "23", T: "24", U: "25", V: "26", W: "27", X: "13", Y: "29", Z: "30", a: "31", b: "32", c: "33", d: "34", e: "35", f: "36", g: "14", h: "38", i: "39", j: "40", k: "41", l: "42", m: "43", n: "44", o: "45", p: "46", q: "47", r: "48", s: "56", t: "54", u: "28", v: "51", w: "49", x: "50", y: "12.1", z: "52", AB: "60", BB: "62", CB: "3.1", DB: "58", EB: "5.1", FB: "6.1", GB: "7.1", HB: "9.1", IB: "10.1", JB: "TP", KB: "9.5-9.6", LB: "10.0-10.1", MB: "10.5", NB: "10.6", OB: "3.6", PB: "3.5", QB: "11.6", RB: "2", SB: "61", TB: "5.5", UB: "5.0-5.1", VB: "6.0-6.1", WB: "7.0-7.1", XB: "8.1-8.4", YB: "9.0-9.2", ZB: "9.3", aB: "10.0-10.2", bB: "10.3", cB: "all", dB: "2.1", eB: "2.2", fB: "2.3", gB: "4.1", hB: "4.4", iB: "4.4.3-4.4.4", jB: "11.4", kB: "1.2", lB: "7.12" };
},{}],69:[function(require,module,exports){
"use strict";
module.exports = { A: "ie", B: "edge", C: "firefox", D: "chrome", E: "safari", F: "opera", G: "ios_saf", H: "op_mini", I: "android", J: "bb", K: "op_mob", L: "and_chr", M: "and_ff", N: "ie_mob", O: "and_uc", P: "samsung", Q: "and_qq", R: "baidu" };
},{}],70:[function(require,module,exports){
"use strict";
module.exports = { "aac": require("./features/aac"), "ac3-ec3": require("./features/ac3-ec3"), "addeventlistener": require("./features/addeventlistener"), "alternate-stylesheet": require("./features/alternate-stylesheet"), "ambient-light": require("./features/ambient-light"), "apng": require("./features/apng"), "arrow-functions": require("./features/arrow-functions"), "asmjs": require("./features/asmjs"), "async-functions": require("./features/async-functions"), "atob-btoa": require("./features/atob-btoa"), "audio-api": require("./features/audio-api"), "audio": require("./features/audio"), "audiotracks": require("./features/audiotracks"), "autofocus": require("./features/autofocus"), "aux-click": require("./features/aux-click"), "background-attachment": require("./features/background-attachment"), "background-img-opts": require("./features/background-img-opts"), "background-position-x-y": require("./features/background-position-x-y"), "background-repeat-round-space": require("./features/background-repeat-round-space"), "battery-status": require("./features/battery-status"), "beacon": require("./features/beacon"), "beforeafterprint": require("./features/beforeafterprint"), "blobbuilder": require("./features/blobbuilder"), "bloburls": require("./features/bloburls"), "border-image": require("./features/border-image"), "border-radius": require("./features/border-radius"), "broadcastchannel": require("./features/broadcastchannel"), "brotli": require("./features/brotli"), "calc": require("./features/calc"), "canvas-blending": require("./features/canvas-blending"), "canvas-text": require("./features/canvas-text"), "canvas": require("./features/canvas"), "ch-unit": require("./features/ch-unit"), "chacha20-poly1305": require("./features/chacha20-poly1305"), "channel-messaging": require("./features/channel-messaging"), "childnode-remove": require("./features/childnode-remove"), "classlist": require("./features/classlist"), "client-hints-dpr-width-viewport": require("./features/client-hints-dpr-width-viewport"), "clipboard": require("./features/clipboard"), "comparedocumentposition": require("./features/comparedocumentposition"), "console-basic": require("./features/console-basic"), "const": require("./features/const"), "contenteditable": require("./features/contenteditable"), "contentsecuritypolicy": require("./features/contentsecuritypolicy"), "contentsecuritypolicy2": require("./features/contentsecuritypolicy2"), "cors": require("./features/cors"), "credential-management": require("./features/credential-management"), "cryptography": require("./features/cryptography"), "css-all": require("./features/css-all"), "css-animation": require("./features/css-animation"), "css-any-link": require("./features/css-any-link"), "css-appearance": require("./features/css-appearance"), "css-apply-rule": require("./features/css-apply-rule"), "css-at-counter-style": require("./features/css-at-counter-style"), "css-backdrop-filter": require("./features/css-backdrop-filter"), "css-background-offsets": require("./features/css-background-offsets"), "css-backgroundblendmode": require("./features/css-backgroundblendmode"), "css-boxdecorationbreak": require("./features/css-boxdecorationbreak"), "css-boxshadow": require("./features/css-boxshadow"), "css-canvas": require("./features/css-canvas"), "css-case-insensitive": require("./features/css-case-insensitive"), "css-clip-path": require("./features/css-clip-path"), "css-containment": require("./features/css-containment"), "css-counters": require("./features/css-counters"), "css-crisp-edges": require("./features/css-crisp-edges"), "css-cross-fade": require("./features/css-cross-fade"), "css-default-pseudo": require("./features/css-default-pseudo"), "css-descendant-gtgt": require("./features/css-descendant-gtgt"), "css-deviceadaptation": require("./features/css-deviceadaptation"), "css-dir-pseudo": require("./features/css-dir-pseudo"), "css-display-contents": require("./features/css-display-contents"), "css-element-function": require("./features/css-element-function"), "css-exclusions": require("./features/css-exclusions"), "css-featurequeries": require("./features/css-featurequeries"), "css-filter-function": require("./features/css-filter-function"), "css-filters": require("./features/css-filters"), "css-first-letter": require("./features/css-first-letter"), "css-first-line": require("./features/css-first-line"), "css-fixed": require("./features/css-fixed"), "css-focus-within": require("./features/css-focus-within"), "css-font-rendering-controls": require("./features/css-font-rendering-controls"), "css-font-stretch": require("./features/css-font-stretch"), "css-gencontent": require("./features/css-gencontent"), "css-gradients": require("./features/css-gradients"), "css-grid": require("./features/css-grid"), "css-hanging-punctuation": require("./features/css-hanging-punctuation"), "css-has": require("./features/css-has"), "css-hyphenate": require("./features/css-hyphenate"), "css-hyphens": require("./features/css-hyphens"), "css-image-orientation": require("./features/css-image-orientation"), "css-image-set": require("./features/css-image-set"), "css-in-out-of-range": require("./features/css-in-out-of-range"), "css-indeterminate-pseudo": require("./features/css-indeterminate-pseudo"), "css-initial-letter": require("./features/css-initial-letter"), "css-initial-value": require("./features/css-initial-value"), "css-letter-spacing": require("./features/css-letter-spacing"), "css-line-clamp": require("./features/css-line-clamp"), "css-logical-props": require("./features/css-logical-props"), "css-marker-pseudo": require("./features/css-marker-pseudo"), "css-masks": require("./features/css-masks"), "css-matches-pseudo": require("./features/css-matches-pseudo"), "css-media-interaction": require("./features/css-media-interaction"), "css-media-resolution": require("./features/css-media-resolution"), "css-media-scripting": require("./features/css-media-scripting"), "css-mediaqueries": require("./features/css-mediaqueries"), "css-mixblendmode": require("./features/css-mixblendmode"), "css-motion-paths": require("./features/css-motion-paths"), "css-namespaces": require("./features/css-namespaces"), "css-not-sel-list": require("./features/css-not-sel-list"), "css-nth-child-of": require("./features/css-nth-child-of"), "css-opacity": require("./features/css-opacity"), "css-optional-pseudo": require("./features/css-optional-pseudo"), "css-overflow-anchor": require("./features/css-overflow-anchor"), "css-page-break": require("./features/css-page-break"), "css-paged-media": require("./features/css-paged-media"), "css-placeholder-shown": require("./features/css-placeholder-shown"), "css-placeholder": require("./features/css-placeholder"), "css-read-only-write": require("./features/css-read-only-write"), "css-rebeccapurple": require("./features/css-rebeccapurple"), "css-reflections": require("./features/css-reflections"), "css-regions": require("./features/css-regions"), "css-repeating-gradients": require("./features/css-repeating-gradients"), "css-resize": require("./features/css-resize"), "css-revert-value": require("./features/css-revert-value"), "css-rrggbbaa": require("./features/css-rrggbbaa"), "css-scroll-behavior": require("./features/css-scroll-behavior"), "css-scrollbar": require("./features/css-scrollbar"), "css-sel2": require("./features/css-sel2"), "css-sel3": require("./features/css-sel3"), "css-selection": require("./features/css-selection"), "css-shapes": require("./features/css-shapes"), "css-snappoints": require("./features/css-snappoints"), "css-sticky": require("./features/css-sticky"), "css-supports-api": require("./features/css-supports-api"), "css-table": require("./features/css-table"), "css-text-align-last": require("./features/css-text-align-last"), "css-text-indent": require("./features/css-text-indent"), "css-text-justify": require("./features/css-text-justify"), "css-text-orientation": require("./features/css-text-orientation"), "css-text-spacing": require("./features/css-text-spacing"), "css-textshadow": require("./features/css-textshadow"), "css-touch-action-2": require("./features/css-touch-action-2"), "css-touch-action": require("./features/css-touch-action"), "css-transitions": require("./features/css-transitions"), "css-unicode-bidi": require("./features/css-unicode-bidi"), "css-unset-value": require("./features/css-unset-value"), "css-variables": require("./features/css-variables"), "css-widows-orphans": require("./features/css-widows-orphans"), "css-writing-mode": require("./features/css-writing-mode"), "css-zoom": require("./features/css-zoom"), "css3-attr": require("./features/css3-attr"), "css3-boxsizing": require("./features/css3-boxsizing"), "css3-colors": require("./features/css3-colors"), "css3-cursors-grab": require("./features/css3-cursors-grab"), "css3-cursors-newer": require("./features/css3-cursors-newer"), "css3-cursors": require("./features/css3-cursors"), "css3-tabsize": require("./features/css3-tabsize"), "currentcolor": require("./features/currentcolor"), "custom-elements": require("./features/custom-elements"), "custom-elementsv1": require("./features/custom-elementsv1"), "customevent": require("./features/customevent"), "datalist": require("./features/datalist"), "dataset": require("./features/dataset"), "datauri": require("./features/datauri"), "details": require("./features/details"), "deviceorientation": require("./features/deviceorientation"), "devicepixelratio": require("./features/devicepixelratio"), "dialog": require("./features/dialog"), "dispatchevent": require("./features/dispatchevent"), "document-currentscript": require("./features/document-currentscript"), "document-evaluate-xpath": require("./features/document-evaluate-xpath"), "document-execcommand": require("./features/document-execcommand"), "documenthead": require("./features/documenthead"), "dom-manip-convenience": require("./features/dom-manip-convenience"), "dom-range": require("./features/dom-range"), "domcontentloaded": require("./features/domcontentloaded"), "domfocusin-domfocusout-events": require("./features/domfocusin-domfocusout-events"), "dommatrix": require("./features/dommatrix"), "download": require("./features/download"), "dragndrop": require("./features/dragndrop"), "element-closest": require("./features/element-closest"), "element-from-point": require("./features/element-from-point"), "eme": require("./features/eme"), "eot": require("./features/eot"), "es5": require("./features/es5"), "es6-class": require("./features/es6-class"), "es6-module": require("./features/es6-module"), "es6-number": require("./features/es6-number"), "eventsource": require("./features/eventsource"), "fetch": require("./features/fetch"), "fieldset-disabled": require("./features/fieldset-disabled"), "fileapi": require("./features/fileapi"), "filereader": require("./features/filereader"), "filereadersync": require("./features/filereadersync"), "filesystem": require("./features/filesystem"), "flac": require("./features/flac"), "flexbox": require("./features/flexbox"), "flow-root": require("./features/flow-root"), "focusin-focusout-events": require("./features/focusin-focusout-events"), "font-feature": require("./features/font-feature"), "font-kerning": require("./features/font-kerning"), "font-loading": require("./features/font-loading"), "font-size-adjust": require("./features/font-size-adjust"), "font-smooth": require("./features/font-smooth"), "font-unicode-range": require("./features/font-unicode-range"), "font-variant-alternates": require("./features/font-variant-alternates"), "fontface": require("./features/fontface"), "form-attribute": require("./features/form-attribute"), "form-submit-attributes": require("./features/form-submit-attributes"), "form-validation": require("./features/form-validation"), "forms": require("./features/forms"), "fullscreen": require("./features/fullscreen"), "gamepad": require("./features/gamepad"), "geolocation": require("./features/geolocation"), "getboundingclientrect": require("./features/getboundingclientrect"), "getcomputedstyle": require("./features/getcomputedstyle"), "getelementsbyclassname": require("./features/getelementsbyclassname"), "getrandomvalues": require("./features/getrandomvalues"), "hardwareconcurrency": require("./features/hardwareconcurrency"), "hashchange": require("./features/hashchange"), "heif": require("./features/heif"), "hevc": require("./features/hevc"), "hidden": require("./features/hidden"), "high-resolution-time": require("./features/high-resolution-time"), "history": require("./features/history"), "html-media-capture": require("./features/html-media-capture"), "html5semantic": require("./features/html5semantic"), "http-live-streaming": require("./features/http-live-streaming"), "http2": require("./features/http2"), "iframe-sandbox": require("./features/iframe-sandbox"), "iframe-seamless": require("./features/iframe-seamless"), "iframe-srcdoc": require("./features/iframe-srcdoc"), "imagecapture": require("./features/imagecapture"), "ime": require("./features/ime"), "img-naturalwidth-naturalheight": require("./features/img-naturalwidth-naturalheight"), "imports": require("./features/imports"), "indeterminate-checkbox": require("./features/indeterminate-checkbox"), "indexeddb": require("./features/indexeddb"), "indexeddb2": require("./features/indexeddb2"), "inline-block": require("./features/inline-block"), "innertext": require("./features/innertext"), "input-autocomplete-onoff": require("./features/input-autocomplete-onoff"), "input-color": require("./features/input-color"), "input-datetime": require("./features/input-datetime"), "input-email-tel-url": require("./features/input-email-tel-url"), "input-event": require("./features/input-event"), "input-file-accept": require("./features/input-file-accept"), "input-file-multiple": require("./features/input-file-multiple"), "input-inputmode": require("./features/input-inputmode"), "input-minlength": require("./features/input-minlength"), "input-number": require("./features/input-number"), "input-pattern": require("./features/input-pattern"), "input-placeholder": require("./features/input-placeholder"), "input-range": require("./features/input-range"), "input-search": require("./features/input-search"), "insert-adjacent": require("./features/insert-adjacent"), "insertadjacenthtml": require("./features/insertadjacenthtml"), "internationalization": require("./features/internationalization"), "intersectionobserver": require("./features/intersectionobserver"), "intrinsic-width": require("./features/intrinsic-width"), "jpeg2000": require("./features/jpeg2000"), "jpegxr": require("./features/jpegxr"), "json": require("./features/json"), "kerning-pairs-ligatures": require("./features/kerning-pairs-ligatures"), "keyboardevent-charcode": require("./features/keyboardevent-charcode"), "keyboardevent-code": require("./features/keyboardevent-code"), "keyboardevent-getmodifierstate": require("./features/keyboardevent-getmodifierstate"), "keyboardevent-key": require("./features/keyboardevent-key"), "keyboardevent-location": require("./features/keyboardevent-location"), "keyboardevent-which": require("./features/keyboardevent-which"), "lazyload": require("./features/lazyload"), "let": require("./features/let"), "link-icon-png": require("./features/link-icon-png"), "link-icon-svg": require("./features/link-icon-svg"), "link-rel-dns-prefetch": require("./features/link-rel-dns-prefetch"), "link-rel-preconnect": require("./features/link-rel-preconnect"), "link-rel-prefetch": require("./features/link-rel-prefetch"), "link-rel-preload": require("./features/link-rel-preload"), "link-rel-prerender": require("./features/link-rel-prerender"), "localecompare": require("./features/localecompare"), "matchesselector": require("./features/matchesselector"), "matchmedia": require("./features/matchmedia"), "mathml": require("./features/mathml"), "maxlength": require("./features/maxlength"), "media-attribute": require("./features/media-attribute"), "media-session-api": require("./features/media-session-api"), "mediacapture-fromelement": require("./features/mediacapture-fromelement"), "mediarecorder": require("./features/mediarecorder"), "mediasource": require("./features/mediasource"), "menu": require("./features/menu"), "meter": require("./features/meter"), "midi": require("./features/midi"), "minmaxwh": require("./features/minmaxwh"), "mp3": require("./features/mp3"), "mpeg4": require("./features/mpeg4"), "multibackgrounds": require("./features/multibackgrounds"), "multicolumn": require("./features/multicolumn"), "mutation-events": require("./features/mutation-events"), "mutationobserver": require("./features/mutationobserver"), "namevalue-storage": require("./features/namevalue-storage"), "nav-timing": require("./features/nav-timing"), "netinfo": require("./features/netinfo"), "node-contains": require("./features/node-contains"), "node-parentelement": require("./features/node-parentelement"), "notifications": require("./features/notifications"), "object-fit": require("./features/object-fit"), "object-observe": require("./features/object-observe"), "objectrtc": require("./features/objectrtc"), "offline-apps": require("./features/offline-apps"), "ogg-vorbis": require("./features/ogg-vorbis"), "ogv": require("./features/ogv"), "ol-reversed": require("./features/ol-reversed"), "once-event-listener": require("./features/once-event-listener"), "online-status": require("./features/online-status"), "opus": require("./features/opus"), "outline": require("./features/outline"), "pad-start-end": require("./features/pad-start-end"), "page-transition-events": require("./features/page-transition-events"), "pagevisibility": require("./features/pagevisibility"), "passive-event-listener": require("./features/passive-event-listener"), "payment-request": require("./features/payment-request"), "permissions-api": require("./features/permissions-api"), "picture": require("./features/picture"), "ping": require("./features/ping"), "png-alpha": require("./features/png-alpha"), "pointer-events": require("./features/pointer-events"), "pointer": require("./features/pointer"), "pointerlock": require("./features/pointerlock"), "progress": require("./features/progress"), "promises": require("./features/promises"), "proximity": require("./features/proximity"), "proxy": require("./features/proxy"), "publickeypinning": require("./features/publickeypinning"), "push-api": require("./features/push-api"), "queryselector": require("./features/queryselector"), "readonly-attr": require("./features/readonly-attr"), "referrer-policy": require("./features/referrer-policy"), "registerprotocolhandler": require("./features/registerprotocolhandler"), "rel-noopener": require("./features/rel-noopener"), "rel-noreferrer": require("./features/rel-noreferrer"), "rellist": require("./features/rellist"), "rem": require("./features/rem"), "requestanimationframe": require("./features/requestanimationframe"), "requestidlecallback": require("./features/requestidlecallback"), "resizeobserver": require("./features/resizeobserver"), "resource-timing": require("./features/resource-timing"), "rest-parameters": require("./features/rest-parameters"), "rtcpeerconnection": require("./features/rtcpeerconnection"), "ruby": require("./features/ruby"), "same-site-cookie-attribute": require("./features/same-site-cookie-attribute"), "screen-orientation": require("./features/screen-orientation"), "script-async": require("./features/script-async"), "script-defer": require("./features/script-defer"), "scrollintoview": require("./features/scrollintoview"), "scrollintoviewifneeded": require("./features/scrollintoviewifneeded"), "sdch": require("./features/sdch"), "selection-api": require("./features/selection-api"), "serviceworkers": require("./features/serviceworkers"), "setimmediate": require("./features/setimmediate"), "sha-2": require("./features/sha-2"), "shadowdom": require("./features/shadowdom"), "shadowdomv1": require("./features/shadowdomv1"), "sharedworkers": require("./features/sharedworkers"), "sni": require("./features/sni"), "spdy": require("./features/spdy"), "speech-recognition": require("./features/speech-recognition"), "speech-synthesis": require("./features/speech-synthesis"), "spellcheck-attribute": require("./features/spellcheck-attribute"), "sql-storage": require("./features/sql-storage"), "srcset": require("./features/srcset"), "stopimmediatepropagation": require("./features/stopimmediatepropagation"), "stream": require("./features/stream"), "stricttransportsecurity": require("./features/stricttransportsecurity"), "style-scoped": require("./features/style-scoped"), "subresource-integrity": require("./features/subresource-integrity"), "svg-css": require("./features/svg-css"), "svg-filters": require("./features/svg-filters"), "svg-fonts": require("./features/svg-fonts"), "svg-fragment": require("./features/svg-fragment"), "svg-html": require("./features/svg-html"), "svg-html5": require("./features/svg-html5"), "svg-img": require("./features/svg-img"), "svg-smil": require("./features/svg-smil"), "svg": require("./features/svg"), "tabindex-attr": require("./features/tabindex-attr"), "template-literals": require("./features/template-literals"), "template": require("./features/template"), "testfeat": require("./features/testfeat"), "text-decoration": require("./features/text-decoration"), "text-emphasis": require("./features/text-emphasis"), "text-overflow": require("./features/text-overflow"), "text-size-adjust": require("./features/text-size-adjust"), "text-stroke": require("./features/text-stroke"), "textcontent": require("./features/textcontent"), "textencoder": require("./features/textencoder"), "tls1-1": require("./features/tls1-1"), "tls1-2": require("./features/tls1-2"), "tls1-3": require("./features/tls1-3"), "token-binding": require("./features/token-binding"), "touch": require("./features/touch"), "transforms2d": require("./features/transforms2d"), "transforms3d": require("./features/transforms3d"), "ttf": require("./features/ttf"), "typedarrays": require("./features/typedarrays"), "u2f": require("./features/u2f"), "upgradeinsecurerequests": require("./features/upgradeinsecurerequests"), "url": require("./features/url"), "urlsearchparams": require("./features/urlsearchparams"), "use-strict": require("./features/use-strict"), "user-select-none": require("./features/user-select-none"), "user-timing": require("./features/user-timing"), "vibration": require("./features/vibration"), "video": require("./features/video"), "videotracks": require("./features/videotracks"), "viewport-units": require("./features/viewport-units"), "wai-aria": require("./features/wai-aria"), "wasm": require("./features/wasm"), "wav": require("./features/wav"), "wbr-element": require("./features/wbr-element"), "web-animation": require("./features/web-animation"), "web-app-manifest": require("./features/web-app-manifest"), "web-bluetooth": require("./features/web-bluetooth"), "web-share": require("./features/web-share"), "webgl": require("./features/webgl"), "webgl2": require("./features/webgl2"), "webm": require("./features/webm"), "webp": require("./features/webp"), "websockets": require("./features/websockets"), "webvr": require("./features/webvr"), "webvtt": require("./features/webvtt"), "webworkers": require("./features/webworkers"), "will-change": require("./features/will-change"), "woff": require("./features/woff"), "woff2": require("./features/woff2"), "word-break": require("./features/word-break"), "wordwrap": require("./features/wordwrap"), "x-doc-messaging": require("./features/x-doc-messaging"), "x-frame-options": require("./features/x-frame-options"), "xhr2": require("./features/xhr2"), "xhtml": require("./features/xhtml"), "xhtmlsmil": require("./features/xhtmlsmil"), "xml-serializer": require("./features/xml-serializer") };
},{"./features/aac":71,"./features/ac3-ec3":72,"./features/addeventlistener":73,"./features/alternate-stylesheet":74,"./features/ambient-light":75,"./features/apng":76,"./features/arrow-functions":77,"./features/asmjs":78,"./features/async-functions":79,"./features/atob-btoa":80,"./features/audio":82,"./features/audio-api":81,"./features/audiotracks":83,"./features/autofocus":84,"./features/aux-click":85,"./features/background-attachment":86,"./features/background-img-opts":87,"./features/background-position-x-y":88,"./features/background-repeat-round-space":89,"./features/battery-status":90,"./features/beacon":91,"./features/beforeafterprint":92,"./features/blobbuilder":93,"./features/bloburls":94,"./features/border-image":95,"./features/border-radius":96,"./features/broadcastchannel":97,"./features/brotli":98,"./features/calc":99,"./features/canvas":102,"./features/canvas-blending":100,"./features/canvas-text":101,"./features/ch-unit":103,"./features/chacha20-poly1305":104,"./features/channel-messaging":105,"./features/childnode-remove":106,"./features/classlist":107,"./features/client-hints-dpr-width-viewport":108,"./features/clipboard":109,"./features/comparedocumentposition":110,"./features/console-basic":111,"./features/const":112,"./features/contenteditable":113,"./features/contentsecuritypolicy":114,"./features/contentsecuritypolicy2":115,"./features/cors":116,"./features/credential-management":117,"./features/cryptography":118,"./features/css-all":119,"./features/css-animation":120,"./features/css-any-link":121,"./features/css-appearance":122,"./features/css-apply-rule":123,"./features/css-at-counter-style":124,"./features/css-backdrop-filter":125,"./features/css-background-offsets":126,"./features/css-backgroundblendmode":127,"./features/css-boxdecorationbreak":128,"./features/css-boxshadow":129,"./features/css-canvas":130,"./features/css-case-insensitive":131,"./features/css-clip-path":132,"./features/css-containment":133,"./features/css-counters":134,"./features/css-crisp-edges":135,"./features/css-cross-fade":136,"./features/css-default-pseudo":137,"./features/css-descendant-gtgt":138,"./features/css-deviceadaptation":139,"./features/css-dir-pseudo":140,"./features/css-display-contents":141,"./features/css-element-function":142,"./features/css-exclusions":143,"./features/css-featurequeries":144,"./features/css-filter-function":145,"./features/css-filters":146,"./features/css-first-letter":147,"./features/css-first-line":148,"./features/css-fixed":149,"./features/css-focus-within":150,"./features/css-font-rendering-controls":151,"./features/css-font-stretch":152,"./features/css-gencontent":153,"./features/css-gradients":154,"./features/css-grid":155,"./features/css-hanging-punctuation":156,"./features/css-has":157,"./features/css-hyphenate":158,"./features/css-hyphens":159,"./features/css-image-orientation":160,"./features/css-image-set":161,"./features/css-in-out-of-range":162,"./features/css-indeterminate-pseudo":163,"./features/css-initial-letter":164,"./features/css-initial-value":165,"./features/css-letter-spacing":166,"./features/css-line-clamp":167,"./features/css-logical-props":168,"./features/css-marker-pseudo":169,"./features/css-masks":170,"./features/css-matches-pseudo":171,"./features/css-media-interaction":172,"./features/css-media-resolution":173,"./features/css-media-scripting":174,"./features/css-mediaqueries":175,"./features/css-mixblendmode":176,"./features/css-motion-paths":177,"./features/css-namespaces":178,"./features/css-not-sel-list":179,"./features/css-nth-child-of":180,"./features/css-opacity":181,"./features/css-optional-pseudo":182,"./features/css-overflow-anchor":183,"./features/css-page-break":184,"./features/css-paged-media":185,"./features/css-placeholder":187,"./features/css-placeholder-shown":186,"./features/css-read-only-write":188,"./features/css-rebeccapurple":189,"./features/css-reflections":190,"./features/css-regions":191,"./features/css-repeating-gradients":192,"./features/css-resize":193,"./features/css-revert-value":194,"./features/css-rrggbbaa":195,"./features/css-scroll-behavior":196,"./features/css-scrollbar":197,"./features/css-sel2":198,"./features/css-sel3":199,"./features/css-selection":200,"./features/css-shapes":201,"./features/css-snappoints":202,"./features/css-sticky":203,"./features/css-supports-api":204,"./features/css-table":205,"./features/css-text-align-last":206,"./features/css-text-indent":207,"./features/css-text-justify":208,"./features/css-text-orientation":209,"./features/css-text-spacing":210,"./features/css-textshadow":211,"./features/css-touch-action":213,"./features/css-touch-action-2":212,"./features/css-transitions":214,"./features/css-unicode-bidi":215,"./features/css-unset-value":216,"./features/css-variables":217,"./features/css-widows-orphans":218,"./features/css-writing-mode":219,"./features/css-zoom":220,"./features/css3-attr":221,"./features/css3-boxsizing":222,"./features/css3-colors":223,"./features/css3-cursors":226,"./features/css3-cursors-grab":224,"./features/css3-cursors-newer":225,"./features/css3-tabsize":227,"./features/currentcolor":228,"./features/custom-elements":229,"./features/custom-elementsv1":230,"./features/customevent":231,"./features/datalist":232,"./features/dataset":233,"./features/datauri":234,"./features/details":235,"./features/deviceorientation":236,"./features/devicepixelratio":237,"./features/dialog":238,"./features/dispatchevent":239,"./features/document-currentscript":240,"./features/document-evaluate-xpath":241,"./features/document-execcommand":242,"./features/documenthead":243,"./features/dom-manip-convenience":244,"./features/dom-range":245,"./features/domcontentloaded":246,"./features/domfocusin-domfocusout-events":247,"./features/dommatrix":248,"./features/download":249,"./features/dragndrop":250,"./features/element-closest":251,"./features/element-from-point":252,"./features/eme":253,"./features/eot":254,"./features/es5":255,"./features/es6-class":256,"./features/es6-module":257,"./features/es6-number":258,"./features/eventsource":259,"./features/fetch":260,"./features/fieldset-disabled":261,"./features/fileapi":262,"./features/filereader":263,"./features/filereadersync":264,"./features/filesystem":265,"./features/flac":266,"./features/flexbox":267,"./features/flow-root":268,"./features/focusin-focusout-events":269,"./features/font-feature":270,"./features/font-kerning":271,"./features/font-loading":272,"./features/font-size-adjust":273,"./features/font-smooth":274,"./features/font-unicode-range":275,"./features/font-variant-alternates":276,"./features/fontface":277,"./features/form-attribute":278,"./features/form-submit-attributes":279,"./features/form-validation":280,"./features/forms":281,"./features/fullscreen":282,"./features/gamepad":283,"./features/geolocation":284,"./features/getboundingclientrect":285,"./features/getcomputedstyle":286,"./features/getelementsbyclassname":287,"./features/getrandomvalues":288,"./features/hardwareconcurrency":289,"./features/hashchange":290,"./features/heif":291,"./features/hevc":292,"./features/hidden":293,"./features/high-resolution-time":294,"./features/history":295,"./features/html-media-capture":296,"./features/html5semantic":297,"./features/http-live-streaming":298,"./features/http2":299,"./features/iframe-sandbox":300,"./features/iframe-seamless":301,"./features/iframe-srcdoc":302,"./features/imagecapture":303,"./features/ime":304,"./features/img-naturalwidth-naturalheight":305,"./features/imports":306,"./features/indeterminate-checkbox":307,"./features/indexeddb":308,"./features/indexeddb2":309,"./features/inline-block":310,"./features/innertext":311,"./features/input-autocomplete-onoff":312,"./features/input-color":313,"./features/input-datetime":314,"./features/input-email-tel-url":315,"./features/input-event":316,"./features/input-file-accept":317,"./features/input-file-multiple":318,"./features/input-inputmode":319,"./features/input-minlength":320,"./features/input-number":321,"./features/input-pattern":322,"./features/input-placeholder":323,"./features/input-range":324,"./features/input-search":325,"./features/insert-adjacent":326,"./features/insertadjacenthtml":327,"./features/internationalization":328,"./features/intersectionobserver":329,"./features/intrinsic-width":330,"./features/jpeg2000":331,"./features/jpegxr":332,"./features/json":333,"./features/kerning-pairs-ligatures":334,"./features/keyboardevent-charcode":335,"./features/keyboardevent-code":336,"./features/keyboardevent-getmodifierstate":337,"./features/keyboardevent-key":338,"./features/keyboardevent-location":339,"./features/keyboardevent-which":340,"./features/lazyload":341,"./features/let":342,"./features/link-icon-png":343,"./features/link-icon-svg":344,"./features/link-rel-dns-prefetch":345,"./features/link-rel-preconnect":346,"./features/link-rel-prefetch":347,"./features/link-rel-preload":348,"./features/link-rel-prerender":349,"./features/localecompare":350,"./features/matchesselector":351,"./features/matchmedia":352,"./features/mathml":353,"./features/maxlength":354,"./features/media-attribute":355,"./features/media-session-api":356,"./features/mediacapture-fromelement":357,"./features/mediarecorder":358,"./features/mediasource":359,"./features/menu":360,"./features/meter":361,"./features/midi":362,"./features/minmaxwh":363,"./features/mp3":364,"./features/mpeg4":365,"./features/multibackgrounds":366,"./features/multicolumn":367,"./features/mutation-events":368,"./features/mutationobserver":369,"./features/namevalue-storage":370,"./features/nav-timing":371,"./features/netinfo":372,"./features/node-contains":373,"./features/node-parentelement":374,"./features/notifications":375,"./features/object-fit":376,"./features/object-observe":377,"./features/objectrtc":378,"./features/offline-apps":379,"./features/ogg-vorbis":380,"./features/ogv":381,"./features/ol-reversed":382,"./features/once-event-listener":383,"./features/online-status":384,"./features/opus":385,"./features/outline":386,"./features/pad-start-end":387,"./features/page-transition-events":388,"./features/pagevisibility":389,"./features/passive-event-listener":390,"./features/payment-request":391,"./features/permissions-api":392,"./features/picture":393,"./features/ping":394,"./features/png-alpha":395,"./features/pointer":397,"./features/pointer-events":396,"./features/pointerlock":398,"./features/progress":399,"./features/promises":400,"./features/proximity":401,"./features/proxy":402,"./features/publickeypinning":403,"./features/push-api":404,"./features/queryselector":405,"./features/readonly-attr":406,"./features/referrer-policy":407,"./features/registerprotocolhandler":408,"./features/rel-noopener":409,"./features/rel-noreferrer":410,"./features/rellist":411,"./features/rem":412,"./features/requestanimationframe":413,"./features/requestidlecallback":414,"./features/resizeobserver":415,"./features/resource-timing":416,"./features/rest-parameters":417,"./features/rtcpeerconnection":418,"./features/ruby":419,"./features/same-site-cookie-attribute":420,"./features/screen-orientation":421,"./features/script-async":422,"./features/script-defer":423,"./features/scrollintoview":424,"./features/scrollintoviewifneeded":425,"./features/sdch":426,"./features/selection-api":427,"./features/serviceworkers":428,"./features/setimmediate":429,"./features/sha-2":430,"./features/shadowdom":431,"./features/shadowdomv1":432,"./features/sharedworkers":433,"./features/sni":434,"./features/spdy":435,"./features/speech-recognition":436,"./features/speech-synthesis":437,"./features/spellcheck-attribute":438,"./features/sql-storage":439,"./features/srcset":440,"./features/stopimmediatepropagation":441,"./features/stream":442,"./features/stricttransportsecurity":443,"./features/style-scoped":444,"./features/subresource-integrity":445,"./features/svg":454,"./features/svg-css":446,"./features/svg-filters":447,"./features/svg-fonts":448,"./features/svg-fragment":449,"./features/svg-html":450,"./features/svg-html5":451,"./features/svg-img":452,"./features/svg-smil":453,"./features/tabindex-attr":455,"./features/template":457,"./features/template-literals":456,"./features/testfeat":458,"./features/text-decoration":459,"./features/text-emphasis":460,"./features/text-overflow":461,"./features/text-size-adjust":462,"./features/text-stroke":463,"./features/textcontent":464,"./features/textencoder":465,"./features/tls1-1":466,"./features/tls1-2":467,"./features/tls1-3":468,"./features/token-binding":469,"./features/touch":470,"./features/transforms2d":471,"./features/transforms3d":472,"./features/ttf":473,"./features/typedarrays":474,"./features/u2f":475,"./features/upgradeinsecurerequests":476,"./features/url":477,"./features/urlsearchparams":478,"./features/use-strict":479,"./features/user-select-none":480,"./features/user-timing":481,"./features/vibration":482,"./features/video":483,"./features/videotracks":484,"./features/viewport-units":485,"./features/wai-aria":486,"./features/wasm":487,"./features/wav":488,"./features/wbr-element":489,"./features/web-animation":490,"./features/web-app-manifest":491,"./features/web-bluetooth":492,"./features/web-share":493,"./features/webgl":494,"./features/webgl2":495,"./features/webm":496,"./features/webp":497,"./features/websockets":498,"./features/webvr":499,"./features/webvtt":500,"./features/webworkers":501,"./features/will-change":502,"./features/woff":503,"./features/woff2":504,"./features/word-break":505,"./features/wordwrap":506,"./features/x-doc-messaging":507,"./features/x-frame-options":508,"./features/xhr2":509,"./features/xhtml":510,"./features/xhtmlsmil":511,"./features/xml-serializer":512}],71:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "132": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E", "16": "B A" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "132": "t" }, N: { "1": "B", "2": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "AAC audio file format" };
},{}],72:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB", "132": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "132": "B" }, K: { "2": "5 6 B A D K", "132": "y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "132": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "AC-3 (Dolby Digital) and EC-3 (Dolby Digital Plus) codecs" };
},{}],73:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "130": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "257": "1 RB F I J PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "EventTarget.addEventListener()" };
},{}],74:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "J C TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D KB LB MB NB QB y", "16": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "16": "8" }, M: { "16": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "2": "kB" }, R: { "16": "lB" } }, B: 1, C: "Alternate stylesheet" };
},{}],75:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "132": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "322": "8 DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "Ambient Light API" };
},{}],76:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "1": "8 AB SB BB", "2": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "5 6 A D p q r KB LB MB NB QB y", "2": "E H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "5 6 B A D y", "2": "K" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Animated PNG (APNG)" };
},{}],77:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Arrow functions" };
},{}],78:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "322": "D" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W", "132": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "132": "K" }, L: { "132": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "132": "I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 6, C: "asm.js" };
},{}],79:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X", "194": "g" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "2 4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Async functions" };
},{}],80:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB LB", "16": "MB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "16": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Base64 encoding and decoding" };
},{}],81:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB" }, D: { "1": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E", "33": "B A D X g H L M N O P Q R S T U V W u Y Z a b c" }, E: { "2": "7 F I CB EB", "33": "J C G E B A FB GB HB IB JB" }, F: { "1": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q" }, G: { "2": "3 7 9 UB", "33": "G A VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Web Audio API" };
},{}],82:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "132": "F I J C G E B A D X g H L M N O PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E", "4": "KB LB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "2": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Audio element" };
},{}],83:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "194": "0 2 4 c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Audio Tracks" };
},{}],84:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Autofocus attribute" };
},{}],85:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "129": "0 2 4 t s" }, D: { "1": "2 4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "16": "kB" }, R: { "1": "lB" } }, B: 5, C: "Auxclick" };
},{}],86:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "132": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "132": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "132": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "132": "E KB LB" }, G: { "2": "3 7 9", "772": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 F s dB eB fB hB iB", "132": "3 gB" }, J: { "260": "C B" }, K: { "1": "5 6 A D K y", "132": "B" }, L: { "1028": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "132": "jB" }, P: { "2": "F", "1028": "I" }, Q: { "1": "kB" }, R: { "1028": "lB" } }, B: 4, C: "CSS background-attachment" };
},{}],87:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "36": "OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "516": "F I J C G E B A D X g" }, E: { "1": "C G E B A GB HB IB JB", "772": "7 F I J CB EB FB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB", "36": "LB" }, G: { "1": "G A WB XB YB ZB aB bB", "4": "3 7 9 VB", "516": "UB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "36": "dB", "516": "1 3 F gB", "548": "eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Background-image options" };
},{}],88:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "background-position-x & background-position-y" };
},{}],89:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G TB", "132": "E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "0 2 4 8 b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "5 6 A D O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E H L M N KB LB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS background-repeat round and space" };
},{}],90:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "m n o p q r w x v", "2": "0 1 2 4 RB F I J C G E z t s PB OB", "132": "L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "164": "B A D X g H" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f", "66": "K" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "132": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "Battery Status API" };
},{}],91:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB" }, D: { "1": "0 2 4 8 i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Beacon API" };
},{}],92:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "2": "I", "16": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 2, C: "Printing Events" };
},{}],93:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB", "36": "J C G E B A D" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C", "36": "G E B A D X g H L M N O" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB fB", "36": "1 3 F gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Blob constructing" };
},{}],94:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C", "33": "G E B A D X g H L M N O P Q R" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "33": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB", "33": "VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 dB eB fB", "33": "3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "33": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Blob URLs" };
},{}],95:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "g H L", "129": "D X" }, C: { "1": "0 2 4 x v z t s", "2": "1 RB", "260": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "804": "F I J C G E B A D X g PB OB" }, D: { "260": "0 2 4 8 v z t s DB AB SB BB", "388": "Z a b c d e f K h i j k l m n o p q r w x", "1412": "H L M N O P Q R S T U V W u Y", "1956": "F I J C G E B A D X g" }, E: { "129": "B A HB IB JB", "1412": "J C G E FB GB", "1956": "7 F I CB EB" }, F: { "2": "E KB LB", "260": "h i j k l m n o p q r", "388": "H L M N O P Q R S T U V W u Y Z a b c d e f K", "1796": "MB NB", "1828": "5 6 A D QB y" }, G: { "129": "A ZB aB bB", "1412": "G VB WB XB YB", "1956": "3 7 9 UB" }, H: { "1828": "cB" }, I: { "388": "s hB iB", "1956": "1 3 F dB eB fB gB" }, J: { "1412": "B", "1924": "C" }, K: { "2": "B", "388": "K", "1828": "5 6 A D y" }, L: { "260": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "388": "jB" }, P: { "260": "I", "388": "F" }, Q: { "260": "kB" }, R: { "260": "lB" } }, B: 4, C: "CSS3 Border images" };
},{}],96:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 x v z t s", "257": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "289": "1 PB OB", "292": "RB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F" }, E: { "1": "I C G E B A GB HB IB JB", "33": "7 F CB", "129": "J EB FB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "33": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "33": "dB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Border-radius (rounded corners)" };
},{}],97:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "1": "2 4 8 t s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "BroadcastChannel" };
},{}],98:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m PB OB" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "194": "w", "257": "x" }, E: { "2": "7 F I J C G E B CB EB FB GB HB IB", "513": "A JB" }, F: { "1": "h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y", "194": "f K" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "257": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 6, C: "Brotli Accept-Encoding/Content-Encoding" };
},{}],99:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G TB", "260": "E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "F I J C G E B A D X g H" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N", "33": "O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "33": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB", "33": "VB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "132": "hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "calc() as CSS unit value" };
},{}],100:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Canvas blend modes" };
},{}],101:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "8": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "8": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "8": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Text API for Canvas" };
},{}],102:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "132": "1 RB PB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "132": "7 CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "260": "cB" }, I: { "1": "1 3 F s gB hB iB", "132": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Canvas (basic support)" };
},{}],103:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "ch (character) unit" };
},{}],104:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b", "129": "c d e f K h i j k l m n o p q r" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB", "16": "iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "ChaCha20-Poly1305 cipher suites for TLS" };
},{}],105:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U PB OB", "194": "V W u Y Z a b c d e f K h i j" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB LB", "16": "MB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Channel messaging" };
},{}],106:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "16": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "ChildNode.remove()" };
},{}],107:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "8": "J C G E TB", "900": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB PB", "516": "T U", "772": "F I J C G E B A D X g H L M N O P Q R S OB" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F I J C", "516": "T U V W", "772": "S", "900": "G E B A D X g H L M N O P Q R" }, E: { "1": "C G E B A GB HB IB JB", "8": "7 F I CB", "900": "J EB FB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "8": "6 E A KB LB MB NB", "900": "5 D QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "8": "3 7 9", "900": "UB VB" }, H: { "900": "cB" }, I: { "1": "s hB iB", "8": "dB eB fB", "900": "1 3 F gB" }, J: { "1": "B", "900": "C" }, K: { "1": "K", "8": "B A", "900": "5 6 D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "900": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "classList (DOMTokenList)" };
},{}],108:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Client Hints: DPR, Width, Viewport-Width" };
},{}],109:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2436": "J C G E B A TB" }, B: { "2436": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "772": "R S T U V W u Y Z a b c d e f K h i j", "4100": "0 2 4 k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D", "2564": "X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "10244": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 CB", "2308": "B A IB JB", "2820": "F I J C G E EB FB GB HB" }, F: { "2": "5 6 E A KB LB MB NB QB", "16": "D", "516": "y", "2564": "H L M N O P Q R S T U V W u Y", "10244": "Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9", "2820": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "2308": "s hB iB" }, J: { "2": "C", "2308": "B" }, K: { "2": "5 6 B A D", "16": "y", "3076": "K" }, L: { "2052": "8" }, M: { "1028": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2052": "I", "2308": "F" }, Q: { "10244": "kB" }, R: { "2052": "lB" } }, B: 5, C: "Clipboard API" };
},{}],110:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "16": "1 RB PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g", "132": "H L M N O P Q R S T U V W u Y" }, E: { "1": "B A IB JB", "16": "7 F I J CB", "132": "C G E FB GB HB", "260": "EB" }, F: { "1": "D M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "5 6 E A KB LB MB NB", "132": "H L" }, G: { "1": "A aB bB", "16": "7", "132": "3 9 G UB VB WB XB YB ZB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "132": "1 3 F fB gB" }, J: { "132": "C B" }, K: { "1": "D K y", "16": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.compareDocumentPosition()" };
},{}],111:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C TB", "132": "G E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB" }, G: { "1": "3 7 9 UB", "513": "G A VB WB XB YB ZB aB bB" }, H: { "4097": "cB" }, I: { "1025": "1 3 F s dB eB fB gB hB iB" }, J: { "258": "C B" }, K: { "2": "B", "258": "5 6 A D K y" }, L: { "1025": "8" }, M: { "2049": "t" }, N: { "258": "B A" }, O: { "258": "jB" }, P: { "1025": "F I" }, Q: { "1": "kB" }, R: { "1025": "lB" } }, B: 1, C: "Basic console logging functions" };
},{}],112:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "132": "1 RB F I J C G E B A D PB OB", "260": "X g H L M N O P Q R S T U V W u Y Z a b c d e" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "260": "F I J C G E B A D X g H L M N O P", "772": "Q R S T U V W u Y Z a b c d e f K h i j", "1028": "k l m n o p q r" }, E: { "1": "B A IB JB", "260": "7 F I CB", "772": "J C G E EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "E KB", "132": "5 6 A LB MB NB", "644": "D QB y", "772": "H L M N O P Q R S T U V W", "1028": "u Y Z a b c d e" }, G: { "1": "A aB bB", "260": "3 7 9", "772": "G UB VB WB XB YB ZB" }, H: { "644": "cB" }, I: { "1": "s", "16": "dB eB", "260": "fB", "772": "1 3 F gB hB iB" }, J: { "772": "C B" }, K: { "1": "K", "132": "5 6 B A", "644": "D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "772": "jB" }, P: { "1": "I", "1028": "F" }, Q: { "772": "kB" }, R: { "1028": "lB" } }, B: 6, C: "const" };
},{}],113:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB", "4": "1" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "contenteditable attribute (basic support)" };
},{}],114:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "129": "F I J C G E B A D X g H L M N O P Q R" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X", "257": "g H L M N O P Q R S T" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I CB", "257": "J FB", "260": "EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9", "257": "VB", "260": "UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C", "257": "B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "257": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Content Security Policy 1.0" };
},{}],115:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB", "132": "a b c d", "260": "e", "516": "f K h i j k l m n", "8196": "0 2 4 o p q r w x v z t s" }, D: { "1": "0 2 4 8 j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e", "1028": "f K h", "2052": "i" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R KB LB MB NB QB y", "1028": "S T U", "2052": "V" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "4100": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Content Security Policy Level 2" };
},{}],116:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C TB", "132": "B", "260": "G E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D" }, E: { "2": "7 CB", "513": "J C G E B A FB GB HB IB JB", "644": "F I EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB" }, G: { "513": "G A VB WB XB YB ZB aB bB", "644": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "132": "1 3 F dB eB fB gB" }, J: { "1": "B", "132": "C" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "132": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Cross-Origin Resource Sharing" };
},{}],117:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "4 8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q", "66": "r w x", "129": "0 2 v z t s" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "Credential Management API" };
},{}],118:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E B", "164": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a PB OB", "322": "b c" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, E: { "1": "A", "8": "7 F I J C CB EB FB", "545": "G E B GB HB IB JB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "8": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A", "8": "3 7 9 UB VB WB", "545": "G XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "8": "1 3 F dB eB fB gB hB iB" }, J: { "8": "C B" }, K: { "1": "K", "8": "5 6 B A D y" }, L: { "1": "8" }, M: { "8": "t" }, N: { "8": "B", "164": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Web Cryptography" };
},{}],119:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS all property" };
},{}],120:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F PB OB", "33": "I J C G E B A D X g H" }, D: { "1": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, E: { "1": "E B A HB IB JB", "2": "7 CB", "33": "J C G EB FB GB", "292": "F I" }, F: { "1": "Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "33": "D H L M N O P Q R S T U V W u Y" }, G: { "1": "A YB ZB aB bB", "33": "G VB WB XB", "164": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s", "33": "3 F gB hB iB", "164": "1 dB eB fB" }, J: { "33": "C B" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "33": "jB" }, P: { "1": "F I" }, Q: { "33": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS Animation" };
},{}],121:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 x v z t s", "16": "1 RB F I J C G E B A D X g H L M N O P PB OB", "33": "Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w" }, D: { "16": "F I J C G E B A D X g H L M N O P Q R S", "33": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 F I J CB EB", "33": "C G E B A FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9 UB", "33": "G A VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "1 3 F dB eB fB gB hB iB", "33": "s" }, J: { "16": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "33": "t" }, N: { "2": "B A" }, O: { "16": "jB" }, P: { "16": "F", "33": "I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 5, C: "CSS :any-link selector" };
},{}],122:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "388": "D X g H L" }, C: { "164": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "676": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB" }, D: { "164": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "164": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "164": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "164": "1 3 F s dB eB fB gB hB iB" }, J: { "164": "C B" }, K: { "2": "5 6 B A D y", "164": "K" }, L: { "164": "8" }, M: { "164": "t" }, N: { "2": "B", "388": "A" }, O: { "164": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 5, C: "CSS Appearance" };
},{}],123:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "16": "H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "194": "0 2 4 8 v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y", "194": "h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "194": "K" }, L: { "194": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "2": "kB" }, R: { "194": "lB" } }, B: 7, C: "CSS @apply rule" };
},{}],124:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "132": "0 2 4 c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "132": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Counter Styles" };
},{}],125:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p", "194": "0 2 4 8 q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "33": "E B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c KB LB MB NB QB y", "194": "d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB", "33": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "194": "K" }, L: { "194": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "194": "kB" }, R: { "194": "lB" } }, B: 7, C: "CSS Backdrop Filter" };
},{}],126:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D PB OB" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS background-position edge offsets" };
},{}],127:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB" }, D: { "1": "0 2 4 8 e f K h i j k l m n o q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d", "260": "p" }, E: { "2": "7 F I J C CB EB FB", "132": "G E B A GB HB IB JB" }, F: { "1": "R S T U V W u Y Z a b d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q KB LB MB NB QB y", "260": "c" }, G: { "2": "3 7 9 UB VB WB", "132": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "260": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS background-blend-mode" };
},{}],128:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q", "164": "0 2 4 8 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J CB EB", "164": "C G E B A FB GB HB IB JB" }, F: { "2": "E KB LB MB NB", "129": "5 6 A D QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 UB VB", "164": "G A WB XB YB ZB aB bB" }, H: { "132": "cB" }, I: { "2": "1 3 F dB eB fB gB", "164": "s hB iB" }, J: { "2": "C", "164": "B" }, K: { "2": "B", "129": "5 6 A D y", "164": "K" }, L: { "164": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 5, C: "CSS box-decoration-break" };
},{}],129:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "33": "PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "33": "I", "164": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "33": "3 9", "164": "7" }, H: { "2": "cB" }, I: { "1": "3 F s gB hB iB", "164": "1 dB eB fB" }, J: { "1": "B", "33": "C" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Box-shadow" };
},{}],130:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "2": "0 2 4 8 r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "2": "7 CB", "33": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D e f K h i j k l m n o p q r KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d" }, G: { "33": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "s", "33": "1 3 F dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "2": "I", "33": "F" }, Q: { "33": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS Canvas Drawings" };
},{}],131:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Case-insensitive CSS attribute selectors" };
},{}],132:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "2 4 t s", "2": "1 RB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB", "644": "0 q r w x v z" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S", "260": "2 4 8 s DB AB SB BB", "292": "0 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "2": "7 F I J CB EB FB", "292": "C G E B A GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "260": "l m n o p q r", "292": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k" }, G: { "2": "3 7 9 UB VB", "292": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "260": "s", "292": "hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "292": "K" }, L: { "260": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "292": "jB" }, P: { "292": "F I" }, Q: { "292": "kB" }, R: { "260": "lB" } }, B: 4, C: "CSS clip-path property (for HTML)" };
},{}],133:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "1": "0 2 4 8 z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "194": "v" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y", "194": "h i" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS Containment" };
},{}],134:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS Counters" };
},{}],135:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J TB", "2340": "C G E B A" }, B: { "2": "D X g H L" }, C: { "2": "1 RB PB", "545": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "1025": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A IB JB", "2": "7 F I CB EB", "164": "J", "4644": "C G E FB GB HB" }, F: { "2": "5 6 E A H L M N O P Q R S T U V W KB LB MB NB", "545": "D QB y", "1025": "u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "A aB bB", "2": "3 7 9", "4260": "UB VB", "4644": "G WB XB YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "1025": "s" }, J: { "2": "C", "4260": "B" }, K: { "2": "5 6 B A", "545": "D y", "1025": "K" }, L: { "1025": "8" }, M: { "545": "t" }, N: { "2340": "B A" }, O: { "4260": "jB" }, P: { "1025": "F I" }, Q: { "2": "kB" }, R: { "1025": "lB" } }, B: 7, C: "Crisp edges/pixelated images" };
},{}],136:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L", "33": "0 2 4 8 M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A IB JB", "2": "7 F I CB", "33": "J C G E EB FB GB HB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "A aB bB", "2": "3 7 9", "33": "G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "33": "s hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS Cross-Fade Function" };
},{}],137:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "16": "1 RB PB OB" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "16": "F I J C G E B A D X g", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "1": "A IB JB", "16": "7 F I CB", "132": "J C G E B EB FB GB HB" }, F: { "1": "h i j k l m n o p q r", "16": "5 6 E A KB LB MB NB", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K", "260": "D QB y" }, G: { "1": "A bB", "16": "3 7 9 UB VB", "132": "G WB XB YB ZB aB" }, H: { "260": "cB" }, I: { "1": "s", "16": "1 dB eB fB", "132": "3 F gB hB iB" }, J: { "16": "C", "132": "B" }, K: { "16": "5 6 B A D", "132": "K", "260": "y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "132": "jB" }, P: { "1": "I", "132": "F" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 7, C: ":default CSS pseudo-class" };
},{}],138:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Explicit descendant combinator >>" };
},{}],139:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "164": "B A" }, B: { "164": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u", "66": "0 2 4 8 Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y", "66": "j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "292": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "B K", "292": "5 6 A D y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "164": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "66": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Device Adaptation" };
},{}],140:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L PB OB", "33": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: ":dir() CSS pseudo-class" };
},{}],141:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS display: contents" };
},{}],142:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "33": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "164": "1 RB PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "33": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS element() function" };
},{}],143:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "33": "B A" }, B: { "33": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "33": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Exclusions Level 1" };
},{}],144:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Feature Queries" };
},{}],145:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G CB EB FB GB", "33": "E" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB", "33": "YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS filter() function" };
},{}],146:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1028": "X g H L", "1346": "D" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "196": "d", "516": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c OB" }, D: { "1": "0 2 4 8 t s DB AB SB BB", "2": "F I J C G E B A D X g H L M", "33": "N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, E: { "1": "B A HB IB JB", "2": "7 F I CB EB", "33": "J C G E FB GB" }, F: { "1": "j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i" }, G: { "1": "A ZB aB bB", "2": "3 7 9 UB", "33": "G VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "33": "hB iB" }, J: { "2": "C", "33": "B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 5, C: "CSS Filter Effects" };
},{}],147:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "16": "TB", "516": "G", "1540": "J C" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "132": "1", "260": "RB" }, D: { "1": "0 2 4 8 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "I J C G", "132": "F" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "I CB", "132": "7 F" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "E KB", "260": "5 6 A LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "16": "dB eB", "132": "fB" }, J: { "1": "C B" }, K: { "1": "D K y", "260": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "::first-letter CSS pseudo-element selector" };
},{}],148:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "132": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS first-line pseudo-element" };
},{}],149:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "C G E B A", "2": "TB", "8": "J" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9", "132": "UB VB WB" }, H: { "2": "cB" }, I: { "1": "1 s hB iB", "260": "dB eB fB", "513": "3 F gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS position:fixed" };
},{}],150:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "AB SB BB", "2": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "194": "8" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o KB LB MB NB QB y", "194": "p q r" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: ":focus-within CSS pseudo-class" };
},{}],151:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o PB OB", "322": "0 2 4 p q r w x v z t s" }, D: { "1": "AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "194": "0 2 4 8 w x v z t s DB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y", "194": "f K h i j k l m n o p" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "194": "K" }, L: { "194": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "194": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS font-rendering controls" };
},{}],152:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G PB OB" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS font-stretch" };
},{}],153:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C TB", "132": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS Generated content for pseudo-elements" };
},{}],154:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "33": "F I J C G E B A D X g H OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "B A D X g H L M N O P Q R S T U", "36": "F I J C G E" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 CB", "33": "J EB", "36": "F I" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E A KB LB MB NB", "33": "D QB", "164": "5 6" }, G: { "1": "G A WB XB YB ZB aB bB", "33": "UB VB", "36": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "33": "3 F gB", "36": "1 dB eB fB" }, J: { "1": "B", "36": "C" }, K: { "1": "K y", "2": "B A", "33": "D", "164": "5 6" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Gradients" };
},{}],155:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "8": "E", "292": "B A" }, B: { "292": "D X g H", "2049": "L" }, C: { "1": "2 4 t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB", "8": "O P Q R S T U V W u Y Z a b c d e f K h i", "584": "j k l m n o p q r w x v", "1025": "0 z" }, D: { "1": "8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T", "8": "U V W u", "200": "0 2 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "1025": "4" }, E: { "1": "A IB JB", "2": "7 F I CB EB", "8": "J C G E B FB GB HB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y", "200": "u Y Z a b c d e f K h i j k l m" }, G: { "1": "A bB", "2": "3 7 9 UB", "8": "G VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 F dB eB fB gB", "8": "3 hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "8": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "292": "B A" }, O: { "2": "jB" }, P: { "2": "I", "8": "F" }, Q: { "200": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Grid Layout" };
},{}],156:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "16": "H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS hanging-punctuation" };
},{}],157:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: ":has() CSS relational pseudo-class" };
},{}],158:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "J C G E B A TB" }, B: { "16": "D X g H L" }, C: { "16": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "2 4 8 s DB AB SB BB", "16": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "16": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "16": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "16": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "16": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "16": "8" }, M: { "16": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 5, C: "CSS4 Hyphenation" };
},{}],159:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "33": "B A" }, B: { "33": "D X g H L" }, C: { "1": "0 2 4 m n o p q r w x v z t s", "2": "1 RB F I PB OB", "33": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, D: { "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t", "132": "2 4 8 s DB AB SB BB" }, E: { "2": "7 F I CB", "33": "J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y", "132": "l m n o p q r" }, G: { "2": "7 9", "33": "3 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "132": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "36": "jB" }, P: { "2": "F", "132": "I" }, Q: { "2": "kB" }, R: { "132": "lB" } }, B: 5, C: "CSS Hyphenation" };
},{}],160:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "132": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 image-orientation" };
},{}],161:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P", "33": "0 2 4 8 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I CB EB", "33": "J C G E B A FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 UB", "33": "G A VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "33": "s hB iB" }, J: { "2": "C", "33": "B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS image-set" };
},{}],162:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D", "260": "X g H L" }, C: { "1": "0 2 4 x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "516": "Y Z a b c d e f K h i j k l m n o p q r w" }, D: { "1": "0 2 4 8 t s DB AB SB BB", "2": "F", "16": "I J C G E B A D X g", "260": "z", "772": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v" }, E: { "1": "A IB JB", "2": "7 F CB", "16": "I", "772": "J C G E B EB FB GB HB" }, F: { "1": "j k l m n o p q r", "16": "E KB", "260": "5 6 A D i LB MB NB QB y", "772": "H L M N O P Q R S T U V W u Y Z a b c d e f K h" }, G: { "1": "A bB", "2": "3 7 9", "772": "G UB VB WB XB YB ZB aB" }, H: { "132": "cB" }, I: { "1": "s", "2": "1 dB eB fB", "260": "3 F gB hB iB" }, J: { "2": "C", "260": "B" }, K: { "260": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "260": "jB" }, P: { "1": "I", "260": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: ":in-range and :out-of-range CSS pseudo-classes" };
},{}],163:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "B A", "388": "E" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 v z t s", "16": "1 RB PB OB", "132": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "388": "F I" }, D: { "1": "0 2 4 8 i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h" }, E: { "1": "A IB JB", "16": "7 F I J CB", "132": "C G E B FB GB HB", "388": "EB" }, F: { "1": "V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "5 6 E A KB LB MB NB", "132": "H L M N O P Q R S T U", "516": "D QB y" }, G: { "1": "A bB", "16": "3 7 9 UB VB", "132": "G WB XB YB ZB aB" }, H: { "516": "cB" }, I: { "1": "s", "16": "1 dB eB fB iB", "132": "hB", "388": "3 F gB" }, J: { "16": "C", "132": "B" }, K: { "1": "K", "16": "5 6 B A D", "516": "y" }, L: { "1": "8" }, M: { "132": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: ":indeterminate CSS pseudo-class" };
},{}],164:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "4": "E", "164": "B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB", "164": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Initial Letter" };
},{}],165:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS initial value" };
},{}],166:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "16": "TB", "132": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "C G E B A FB GB HB IB JB", "16": "CB", "132": "7 F I J EB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E KB", "132": "5 6 A D H L LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "2": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "132": "1 3 F fB gB" }, J: { "132": "C B" }, K: { "1": "K", "132": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "letter-spacing CSS property" };
},{}],167:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "16": "F I J C G E B A D X", "33": "0 2 4 8 g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F CB", "33": "I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9", "33": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "dB eB", "33": "1 3 F s fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS line-clamp" };
},{}],168:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "RB", "164": "1 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j PB OB" }, D: { "292": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "292": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "292": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "292": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "292": "1 3 F s dB eB fB gB hB iB" }, J: { "292": "C B" }, K: { "2": "5 6 B A D y", "292": "K" }, L: { "292": "8" }, M: { "164": "t" }, N: { "2": "B A" }, O: { "292": "jB" }, P: { "292": "F I" }, Q: { "292": "kB" }, R: { "292": "lB" } }, B: 7, C: "CSS Logical Properties" };
},{}],169:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS ::marker pseudo-element" };
},{}],170:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 t s", "2": "1 RB", "260": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB" }, D: { "164": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "164": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "164": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "164": "s hB iB", "676": "1 3 F dB eB fB gB" }, J: { "164": "C B" }, K: { "2": "5 6 B A D y", "164": "K" }, L: { "164": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "164": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 4, C: "CSS Masks" };
},{}],171:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "16": "1 RB PB OB", "548": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "16": "F I J C G E B A D X g", "164": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F CB", "16": "I", "164": "J C G EB FB GB", "257": "E B A HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9 UB VB", "164": "G WB XB", "257": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "1 dB eB fB", "164": "3 F s gB hB iB" }, J: { "16": "C", "164": "B" }, K: { "2": "5 6 B A D y", "164": "K" }, L: { "164": "8" }, M: { "548": "t" }, N: { "2": "B A" }, O: { "164": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 5, C: ":matches() CSS pseudo-class" };
},{}],172:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Media Queries: interaction media features" };
},{}],173:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "260": "F I J C G E B A D X g H PB OB" }, D: { "1": "0 2 4 8 Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "548": "F I J C G E B A D X g H L M N O P Q R S T U V W u" }, E: { "2": "7 CB", "548": "F I J C G E B A EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E", "548": "5 6 A D KB LB MB NB QB" }, G: { "16": "7", "548": "3 9 G A UB VB WB XB YB ZB aB bB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "548": "1 3 F fB gB" }, J: { "548": "C B" }, K: { "1": "K y", "548": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Media Queries: resolution feature" };
},{}],174:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "16": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB y", "16": "q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "Media Queries: scripting media feature" };
},{}],175:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "8": "J C G TB", "129": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "129": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "129": "F I J EB", "388": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "G A WB XB YB ZB aB bB", "129": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "129": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS3 Media Queries" };
},{}],176:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u", "194": "Y Z a b c d e f K h i j" }, E: { "2": "7 F I J C CB EB FB", "260": "G E B A GB HB IB JB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u KB LB MB NB QB y" }, G: { "2": "3 7 9 UB VB WB", "260": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Blending of HTML/SVG elements" };
},{}],177:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "194": "m n o" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y", "194": "Z a b" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 7, C: "CSS Motion Path" };
},{}],178:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "16": "7 CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "16": "7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS namespaces" };
},{}],179:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t PB OB", "16": "2 4 s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "selector list argument of :not()" };
},{}],180:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "selector list argument of :nth-child and :nth-last-child CSS pseudo-classes" };
},{}],181:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "4": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS3 Opacity" };
},{}],182:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E KB", "132": "5 6 A D LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "132": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "132": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: ":optional CSS pseudo-class" };
},{}],183:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "4 8 s DB AB SB BB", "2": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS overflow-anchor (Scroll Anchoring)" };
},{}],184:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "388": "B A", "900": "J C G E TB" }, B: { "388": "D X g H L" }, C: { "900": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "900": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "772": "B", "900": "7 F I J C G E A CB EB FB GB HB IB JB" }, F: { "16": "E KB", "129": "5 6 A D LB MB NB QB y", "900": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "900": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "129": "cB" }, I: { "900": "1 3 F s dB eB fB gB hB iB" }, J: { "900": "C B" }, K: { "129": "5 6 B A D y", "900": "K" }, L: { "900": "8" }, M: { "900": "t" }, N: { "388": "B A" }, O: { "900": "jB" }, P: { "900": "F I" }, Q: { "900": "kB" }, R: { "900": "lB" } }, B: 2, C: "CSS page-break properties" };
},{}],185:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "132": "G E B A" }, B: { "132": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N PB OB", "132": "0 2 4 O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "132": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "16": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D y", "258": "K" }, L: { "1": "8" }, M: { "132": "t" }, N: { "258": "B A" }, O: { "258": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS Paged Media (@page)" };
},{}],186:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB" }, D: { "1": "0 2 4 8 q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: ":placeholder-shown CSS pseudo-class" };
},{}],187:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "36": "B A" }, B: { "36": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB PB OB", "33": "O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "164": "F I J C G E B A D X g H L M N" }, D: { "1": "4 8 DB AB SB BB", "36": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "1": "A IB JB", "2": "7 F CB", "36": "I J C G E B EB FB GB HB" }, F: { "1": "n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "36": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m" }, G: { "1": "A bB", "2": "7 9", "36": "3 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "36": "1 3 F dB eB fB gB hB iB" }, J: { "36": "C B" }, K: { "2": "5 6 B A D y", "36": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "36": "B A" }, O: { "36": "jB" }, P: { "36": "F I" }, Q: { "36": "kB" }, R: { "1": "lB" } }, B: 5, C: "::placeholder CSS pseudo-element" };
},{}],188:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "16": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB", "33": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "16": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c", "132": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 F I J CB EB FB", "132": "C G E B A GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9 UB VB WB", "132": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "16": "C B" }, K: { "2": "5 6 B A D y", "132": "K" }, L: { "132": "8" }, M: { "33": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "2": "F", "132": "I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 1, C: "CSS :read-only and :read-write selectors" };
},{}],189:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "132": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB", "16": "FB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Rebeccapurple color" };
},{}],190:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "33": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "33": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "33": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "33": "1 3 F s dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS Reflections" };
},{}],191:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "420": "B A" }, B: { "420": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "36": "H L M N", "66": "O P Q R S T U V W u Y Z a b c d" }, E: { "2": "7 F I J CB EB", "33": "C G E B A FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 UB VB", "33": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "420": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Regions" };
},{}],192:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "33": "F I J C G E B A D X g H OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E", "33": "B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB", "33": "J EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E A KB LB MB NB", "33": "D QB", "36": "5 6" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9", "33": "UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 dB eB fB", "33": "3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "B A", "33": "D", "36": "5 6" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Repeating Gradients" };
},{}],193:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "F" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB", "132": "y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS resize property" };
},{}],194:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS revert value" };
},{}],195:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v", "194": "0 2 4 8 z t s DB AB SB BB" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h KB LB MB NB QB y", "194": "i j k l m n o p q r" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "194": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "194": "kB" }, R: { "194": "lB" } }, B: 7, C: "#rrggbbaa hex color notation" };
},{}],196:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "450": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y", "450": "u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "450": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSSOM Scroll-behavior" };
},{}],197:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "289": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 F I CB", "289": "J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "289": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9 UB VB", "289": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "dB eB", "289": "1 3 F s fB gB hB iB" }, J: { "289": "C B" }, K: { "2": "5 6 B A D y", "289": "K" }, L: { "289": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "289": "jB" }, P: { "289": "F I" }, Q: { "289": "kB" }, R: { "289": "lB" } }, B: 7, C: "CSS scrollbar styling" };
},{}],198:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "C G E B A", "2": "TB", "8": "J" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS 2.1 selectors" };
},{}],199:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J", "132": "C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "2": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS3 selectors" };
},{}],200:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "33": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 D K y", "16": "6 B A" }, L: { "1": "8" }, M: { "33": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "::selection CSS pseudo-element" };
},{}],201:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c", "194": "d e f" }, E: { "1": "A IB JB", "2": "7 F I J C CB EB FB", "33": "G E B GB HB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 UB VB WB", "33": "G XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Shapes Level 1" };
},{}],202:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "6308": "B", "6436": "A" }, B: { "6436": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h PB OB", "2052": "0 2 4 i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "A JB", "2": "7 F I J C G CB EB FB GB", "3108": "E B HB IB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB", "3108": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2052": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Scroll snap points" };
},{}],203:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "L", "2": "D X g H" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U PB OB", "194": "V W u Y Z a", "516": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R K h i j k l m n o p q r w x v", "322": "0 2 S T U V W u Y Z a b c d e f z t", "1028": "4 8 s DB AB SB BB" }, E: { "2": "7 F I J CB EB", "33": "G E B A GB HB IB JB", "2084": "C FB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h KB LB MB NB QB y", "322": "i j k", "1028": "l m n o p q r" }, G: { "2": "3 7 9 UB", "33": "G A XB YB ZB aB bB", "2084": "VB WB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "1028": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1028": "8" }, M: { "516": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "322": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS position:sticky" };
},{}],204:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O PB OB", "66": "P Q R" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB", "132": "y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D", "132": "y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS.supports() API" };
},{}],205:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "132": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS Table display" };
},{}],206:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "4": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A PB OB", "33": "D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, D: { "1": "0 2 4 8 q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d", "322": "e f K h i j k l m n o p" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q KB LB MB NB QB y", "578": "R S T U V W u Y Z a b c" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 text-align-last" };
},{}],207:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "132": "D X g H L" }, C: { "132": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K", "388": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "132": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "132": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y", "388": "U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "132": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "132": "cB" }, I: { "132": "1 3 F s dB eB fB gB hB iB" }, J: { "132": "C B" }, K: { "132": "5 6 B A D y", "388": "K" }, L: { "388": "8" }, M: { "132": "t" }, N: { "132": "B A" }, O: { "132": "jB" }, P: { "132": "F", "388": "I" }, Q: { "388": "kB" }, R: { "388": "lB" } }, B: 5, C: "CSS text-indent" };
},{}],208:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "J C TB", "132": "G E B A" }, B: { "132": "D X g H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "1025": "2 4 s", "1602": "t" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "322": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y", "322": "Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "322": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "322": "K" }, L: { "322": "8" }, M: { "1602": "t" }, N: { "132": "B A" }, O: { "2": "jB" }, P: { "2": "F", "322": "I" }, Q: { "322": "kB" }, R: { "322": "lB" } }, B: 5, C: "CSS text-justify" };
},{}],209:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "2": "7 F I J C G E CB EB FB GB HB", "16": "B", "33": "A IB JB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS text-orientation" };
},{}],210:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "161": "G E B A" }, B: { "161": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "16": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS Text 4 text-spacing" };
},{}],211:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "129": "B A" }, B: { "129": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "260": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "4": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "B", "4": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Text-shadow" };
},{}],212:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "A", "164": "B" }, B: { "132": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t", "260": "2" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y", "260": "l" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "132": "A", "164": "B" }, O: { "2": "jB" }, P: { "1": "I", "16": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS touch-action level 2 values" };
},{}],213:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E TB", "289": "B" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "194": "Y Z a b c d e f K h i j k l m n o p q r w x v", "1025": "0 2 4 z t s" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB YB", "516": "A ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "289": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS touch-action property" };
},{}],214:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "I J C G E B A D X g H", "164": "F" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "33": "J EB", "164": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB", "33": "D", "164": "5 6 A MB NB QB" }, G: { "1": "G A WB XB YB ZB aB bB", "33": "VB", "164": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "33": "1 3 F dB eB fB gB" }, J: { "1": "B", "33": "C" }, K: { "1": "K y", "33": "D", "164": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 Transitions" };
},{}],215:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 x v z t s", "33": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "132": "1 RB F I J C G E PB OB", "292": "B A D X g H L" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L", "548": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "132": "7 F I J C G CB EB FB GB", "548": "E B A HB IB JB" }, F: { "132": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "132": "3 7 9 G UB VB WB XB", "548": "A YB ZB aB bB" }, H: { "16": "cB" }, I: { "1": "s", "16": "1 3 F dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 4, C: "CSS unicode-bidi property" };
},{}],216:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS unset value" };
},{}],217:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "260": "H L" }, C: { "1": "0 2 4 a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q", "194": "r" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y", "194": "e" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Variables (Custom Properties)" };
},{}],218:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C TB", "129": "G E" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "129": "5 6 E A KB LB MB NB QB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS widows & orphans" };
},{}],219:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "132": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB", "322": "f K h i j" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J", "16": "C", "33": "G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q" }, E: { "2": "7 F CB", "16": "I", "33": "J C G E B A EB FB GB HB IB JB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d" }, G: { "16": "3 7 9", "33": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB fB", "33": "1 3 F gB hB iB" }, J: { "33": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "36": "B A" }, O: { "33": "jB" }, P: { "1": "I", "33": "F" }, Q: { "33": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS writing-mode property" };
},{}],220:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C TB", "129": "G E B A" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "CSS zoom" };
},{}],221:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 attr() function" };
},{}],222:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "8": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "33": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "33": "7 F I CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "33": "3 7 9" }, H: { "1": "cB" }, I: { "1": "3 F s gB hB iB", "33": "1 dB eB fB" }, J: { "1": "B", "33": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Box-sizing" };
},{}],223:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "4": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "2": "E", "4": "KB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS3 Colors" };
},{}],224:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "33": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB" }, D: { "33": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "33": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D QB y", "2": "5 6 E A KB LB MB NB", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "33": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 Cursors: grab & grabbing" };
},{}],225:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "33": "1 RB F I J C G E B A D X g H L M N O P Q R S PB OB" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, E: { "1": "E B A HB IB JB", "33": "7 F I J C G CB EB FB GB" }, F: { "1": "D T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB", "33": "H L M N O P Q R S" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 Cursors: zoom-in & zoom-out" };
},{}],226:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "132": "J C G TB" }, B: { "1": "g H L", "260": "D X" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "4": "1 RB PB OB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "4": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "260": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS3 Cursors (original values)" };
},{}],227:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB PB OB", "33": "0 2 4 t s", "164": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, D: { "1": "0 2 4 8 l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P", "132": "Q R S T U V W u Y Z a b c d e f K h i j k" }, E: { "2": "7 F I J CB EB", "132": "C G E B A FB GB HB IB JB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "E KB LB MB", "132": "H L M N O P Q R S T U V W u", "164": "5 6 A D NB QB y" }, G: { "2": "3 7 9 UB VB", "132": "G A WB XB YB ZB aB bB" }, H: { "164": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "132": "hB iB" }, J: { "132": "C B" }, K: { "1": "K", "2": "B", "164": "5 6 A D y" }, L: { "1": "8" }, M: { "33": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 tab-size" };
},{}],228:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS currentColor value" };
},{}],229:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "8": "B A" }, B: { "8": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB", "194": "S T U V W u Y", "200": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V", "66": "W u Y Z a b" }, E: { "2": "7 F I CB EB", "8": "J C G E B A FB GB HB IB JB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "66": "H L M N O" }, G: { "2": "3 7 9 UB VB", "8": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "200": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Custom Elements v0" };
},{}],230:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "8": "B A" }, B: { "8": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB", "8": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v", "8": "0 z", "132": "2 4 8 t s DB AB SB BB" }, E: { "2": "7 F I J C CB EB FB GB", "8": "G E B HB", "132": "A IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j KB LB MB NB QB y", "132": "k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB YB ZB aB", "132": "A bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "132": "8" }, M: { "8": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "132": "I" }, Q: { "8": "kB" }, R: { "132": "lB" } }, B: 1, C: "Custom Elements v1" };
},{}],231:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB", "132": "J C G E B" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F", "16": "I J C G X g", "388": "E B A D" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F CB", "16": "I J", "388": "EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB", "132": "5 6 A" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "9", "16": "3 7", "388": "UB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "388": "1 3 F gB" }, J: { "1": "B", "388": "C" }, K: { "1": "D K y", "2": "B", "132": "5 6 A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "CustomEvent" };
},{}],232:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E", "260": "B A" }, B: { "260": "D X g H L" }, C: { "8": "1 RB PB OB", "516": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "8": "F I J C G E B A D X g H L M N O", "132": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "8": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "8": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "iB", "8": "1 3 F dB eB fB gB hB", "132": "s" }, J: { "1": "B", "8": "C" }, K: { "1": "5 6 B A D y", "8": "K" }, L: { "1": "8" }, M: { "516": "t" }, N: { "8": "B A" }, O: { "8": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Datalist element" };
},{}],233:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "4": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "4": "1 RB F I PB OB", "129": "0 2 4 v z t s" }, D: { "1": "0 o p q r w x v z t", "4": "F I J", "129": "2 4 8 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n s DB AB SB BB" }, E: { "4": "7 F I CB", "129": "J C G E B A EB FB GB HB IB JB" }, F: { "1": "5 6 D b c d e f K h i j k QB y", "4": "E A KB LB MB NB", "129": "H L M N O P Q R S T U V W u Y Z a l m n o p q r" }, G: { "4": "3 7 9", "129": "G A UB VB WB XB YB ZB aB bB" }, H: { "4": "cB" }, I: { "4": "dB eB fB", "129": "1 3 F s gB hB iB" }, J: { "129": "C B" }, K: { "1": "5 6 D y", "4": "B A", "129": "K" }, L: { "129": "8" }, M: { "129": "t" }, N: { "1": "A", "4": "B" }, O: { "129": "jB" }, P: { "129": "F I" }, Q: { "1": "kB" }, R: { "129": "lB" } }, B: 1, C: "dataset & data-* attributes" };
},{}],234:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "132": "G", "260": "E B A" }, B: { "260": "D X H L", "772": "g" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Data URIs" };
},{}],235:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "E B A TB", "8": "J C G" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "RB", "8": "1 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB", "194": "q r" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F I J C G E B A", "257": "O P Q R S T U V W u Y Z a b c d e", "769": "D X g H L M N" }, E: { "1": "A IB JB", "8": "7 F I CB EB", "257": "J C G E B FB GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 D QB y", "8": "E A KB LB MB NB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "8": "3 7 9 UB" }, H: { "8": "cB" }, I: { "1": "3 F s gB hB iB", "8": "1 dB eB fB" }, J: { "1": "B", "8": "C" }, K: { "1": "K", "8": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "769": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Details & Summary elements" };
},{}],236:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "132": "A" }, B: { "1": "D X g H L" }, C: { "2": "1 RB PB", "4": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "F I OB" }, D: { "2": "F I J", "4": "0 2 4 8 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "4": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "7 9", "4": "3 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "dB eB fB", "4": "1 3 F s gB hB iB" }, J: { "2": "C", "4": "B" }, K: { "1": "D y", "2": "5 6 B A", "4": "K" }, L: { "4": "8" }, M: { "4": "t" }, N: { "1": "A", "2": "B" }, O: { "4": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 4, C: "DeviceOrientation & DeviceMotion events" };
},{}],237:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Window.devicePixelRatio" };
},{}],238:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "194": "0 2 4 t s" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a", "322": "b c d e f" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N KB LB MB NB QB y", "578": "O P Q R S" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Dialog element" };
},{}],239:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "16": "TB", "129": "E B", "130": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "129": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "EventTarget.dispatchEvent" };
},{}],240:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "document.currentScript" };
},{}],241:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "16": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "document.evaluate & XPath" };
},{}],242:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A FB GB HB IB JB", "16": "7 F I CB EB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "16": "E KB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "7 9", "16": "3 UB VB" }, H: { "2": "cB" }, I: { "1": "3 gB hB iB", "2": "1 F s dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Document.execCommand()" };
},{}],243:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "16": "I" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "document.head" };
},{}],244:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "2 4 8 t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v", "194": "0 z" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y", "194": "j" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "194": "kB" }, R: { "2": "lB" } }, B: 1, C: "DOM manipulation convenience methods" };
},{}],245:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Document Object Model Range" };
},{}],246:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "DOMContentLoaded" };
},{}],247:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "16": "I" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "5 6 E A KB LB MB NB" }, G: { "1": "G A WB XB YB ZB aB bB", "16": "3 7 9 UB VB" }, H: { "16": "cB" }, I: { "1": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "DOMFocusIn & DOMFocusOut events" };
},{}],248:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "516": "c d e f K h i j k l m n o p q r" }, D: { "16": "F I J C", "132": "0 2 4 8 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "388": "G" }, E: { "1": "A JB", "16": "7 F CB", "132": "I J C G E B EB FB GB HB IB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "3 7 9", "132": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "132": "3 F s gB hB iB", "292": "1 dB eB fB" }, J: { "16": "C", "132": "B" }, K: { "2": "5 6 B A D y", "132": "K" }, L: { "132": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "132": "jB" }, P: { "132": "F I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 4, C: "DOMMatrix" };
},{}],249:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O PB OB" }, D: { "1": "0 2 4 8 g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Download attribute" };
},{}],250:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "644": "J C G E TB", "772": "B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "8": "5 6 E A KB LB MB NB QB" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "y", "2": "K", "8": "5 6 B A D" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Drag and Drop" };
},{}],251:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 1, C: "Element.closest()" };
},{}],252:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "16": "RB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "16": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "E KB LB MB NB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "D K y", "16": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "document.elementFromPoint()" };
},{}],253:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "164": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "1": "0 2 4 8 l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d", "132": "e f K h i j k" }, E: { "2": "7 F I J CB EB FB", "164": "C G E B A GB HB IB JB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q KB LB MB NB QB y", "132": "R S T U V W u" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 3, C: "Encrypted Media Extensions" };
},{}],254:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "2": "TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "EOT - Embedded OpenType fonts" };
},{}],255:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C TB", "260": "E", "1026": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "4": "1 RB PB OB", "132": "F I J C G E B A D X g H L M N O P" }, D: { "1": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F I J C G E B A D X g H L M N", "132": "O P Q R" }, E: { "1": "J C G E B A FB GB HB IB JB", "4": "7 F I CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "4": "5 6 E A D KB LB MB NB QB", "132": "y" }, G: { "1": "G A VB WB XB YB ZB aB bB", "4": "3 7 9 UB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "4": "1 dB eB fB", "132": "3 gB", "900": "F" }, J: { "1": "B", "4": "C" }, K: { "1": "K", "4": "5 6 B A D", "132": "y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "ECMAScript 5" };
},{}],256:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k", "132": "l m n o p q r" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u KB LB MB NB QB y", "132": "Y Z a b c d e" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "ES6 classes" };
},{}],257:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "194": "H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "322": "2 4 t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "194": "AB SB BB" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB y", "194": "q r" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "ES6 module" };
},{}],258:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H PB OB", "132": "L M N O P Q R S T", "260": "U V W u Y Z", "516": "a" }, D: { "1": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N", "1028": "O P Q R S T U V W u Y Z a b c" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "1": "Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "1028": "H L M N O P" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 F dB eB fB", "1028": "3 gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "ES6 Number" };
},{}],259:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "4": "E KB LB MB NB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 D K y", "4": "B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Server-sent events" };
},{}],260:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c PB OB", "1025": "i", "1218": "d e f K h" }, D: { "1": "0 2 4 8 l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i", "260": "j", "772": "k" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y", "260": "W", "772": "u" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Fetch" };
},{}],261:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "TB", "132": "G E", "388": "J C B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H", "16": "L M N O" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "16": "E KB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "388": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B", "260": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "disabled attribute of the fieldset element" };
},{}],262:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "260": "B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "260": "F I J C G E B A D X g H L M N O P Q R S T U V W OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I", "260": "X g H L M N O P Q R S T U V W u Y Z a b c d e f K", "388": "J C G E B A D" }, E: { "1": "B A IB JB", "2": "7 F I CB", "260": "J C G E FB GB HB", "388": "EB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E A KB LB MB NB", "260": "5 6 D H L M N O P Q R S T QB y" }, G: { "1": "A aB bB", "2": "3 7 9 UB", "260": "G VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "dB eB fB", "260": "hB", "388": "1 3 F gB" }, J: { "260": "B", "388": "C" }, K: { "1": "K", "2": "B A", "260": "5 6 D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B", "260": "A" }, O: { "260": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "File API" };
},{}],263:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E A KB LB MB NB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 D K y", "2": "B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "FileReader API" };
},{}],264:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB", "16": "5 6 A MB NB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 D K y", "2": "B", "16": "6 A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "FileReaderSync" };
},{}],265:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C", "33": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "36": "G E B A D" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "33": "B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "33": "I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Filesystem & FileWriter API" };
},{}],266:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB" }, D: { "1": "4 8 s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m", "16": "n o p", "388": "0 2 q r w x v z t" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB fB", "16": "1 3 F gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "y", "16": "5 6 B A D", "129": "K" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "129": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "FLAC audio format" };
},{}],267:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "1028": "A", "1316": "B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "164": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "516": "R S T U V W" }, D: { "1": "0 2 4 8 Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "Q R S T U V W u", "164": "F I J C G E B A D X g H L M N O P" }, E: { "1": "E B A HB IB JB", "33": "C G FB GB", "164": "7 F I J CB EB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB", "33": "H L" }, G: { "1": "A YB ZB aB bB", "33": "G WB XB", "164": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "164": "1 3 F dB eB fB gB" }, J: { "1": "B", "164": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "292": "B" }, O: { "164": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Flexible Box Layout Module" };
},{}],268:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB" }, D: { "1": "8 DB AB SB BB", "2": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "display: flow-root" };
},{}],269:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "2": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB", "16": "5 6 A" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "3 F s gB hB iB", "2": "dB eB fB", "16": "1" }, J: { "1": "C B" }, K: { "1": "D K y", "2": "B", "16": "5 6 A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "focusin & focusout events" };
},{}],270:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "H L M N O P Q R S T U V W u Y Z a b c", "164": "F I J C G E B A D X g" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H", "33": "Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q", "292": "L M N O P" }, E: { "1": "B A HB IB JB", "2": "7 C G E CB FB GB", "4": "F I J EB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d" }, G: { "1": "A ZB aB bB", "2": "G WB XB YB", "4": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "33": "hB iB" }, J: { "2": "C", "33": "B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "33": "jB" }, P: { "1": "I", "33": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS font-feature-settings" };
},{}],271:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S PB OB", "194": "T U V W u Y Z a b c" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u", "33": "Y Z a b" }, E: { "1": "B A HB IB JB", "2": "7 F I J CB EB FB", "33": "C G E GB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H KB LB MB NB QB y", "33": "L M N O" }, G: { "2": "3 7 9 UB VB WB", "33": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB", "33": "hB" }, J: { "2": "C", "33": "B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 font-kerning" };
},{}],272:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB", "194": "e f K h i j" }, D: { "1": "0 2 4 8 e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS Font Loading" };
},{}],273:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "194": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y", "194": "Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "258": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "194": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS font-size-adjust" };
},{}],274:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB", "804": "0 2 4 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F", "676": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "676": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "676": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS font-smooth" };
},{}],275:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "4": "E B A" }, B: { "4": "D X g H L" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB", "194": "f K h i j k l m" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "1": "B A IB JB", "4": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "4": "H L M N O P Q R" }, G: { "1": "A aB bB", "4": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "4": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C", "4": "B" }, K: { "2": "5 6 B A D y", "4": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "4": "B A" }, O: { "4": "jB" }, P: { "1": "I", "4": "F" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 4, C: "Font unicode-range subsetting" };
},{}],276:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "130": "B A" }, B: { "130": "D X g H L" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "130": "F I J C G E B A D X g H L M N O P Q R S", "322": "T U V W u Y Z a b c" }, D: { "2": "F I J C G E B A D X g H", "130": "0 2 4 8 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A HB IB JB", "2": "7 C G E CB FB GB", "130": "F I J EB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "130": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "A ZB aB bB", "2": "7 G WB XB YB", "130": "3 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "130": "s hB iB" }, J: { "2": "C", "130": "B" }, K: { "2": "5 6 B A D y", "130": "K" }, L: { "130": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "130": "jB" }, P: { "130": "F I" }, Q: { "130": "kB" }, R: { "130": "lB" } }, B: 4, C: "CSS font-variant-alternates" };
},{}],277:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "132": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "2": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "2": "E KB" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "260": "7 9" }, H: { "2": "cB" }, I: { "1": "3 F s gB hB iB", "2": "dB", "4": "1 eB fB" }, J: { "1": "B", "4": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "@font-face Web fonts" };
},{}],278:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "16": "I" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Form attribute" };
},{}],279:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB", "16": "LB MB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "3 F s gB hB iB", "2": "dB eB fB", "16": "1" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 A D K y", "16": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Attributes for form submission" };
},{}],280:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E" }, E: { "1": "A IB JB", "2": "7 F CB", "132": "I J C G E B EB FB GB HB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "2": "E KB" }, G: { "1": "A bB", "2": "7", "132": "3 9 G UB VB WB XB YB ZB aB" }, H: { "516": "cB" }, I: { "1": "s iB", "2": "1 dB eB fB", "132": "3 F gB hB" }, J: { "1": "B", "132": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Form validation" };
},{}],281:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "4": "B A", "8": "J C G E" }, B: { "4": "D X g H L" }, C: { "4": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB PB OB" }, D: { "4": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "4": "F I J C G E B A EB FB GB HB IB JB", "8": "7 CB" }, F: { "1": "5 6 E A D KB LB MB NB QB y", "4": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "7", "4": "3 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "4": "s hB iB" }, J: { "2": "C", "4": "B" }, K: { "1": "5 6 B A D y", "4": "K" }, L: { "4": "8" }, M: { "4": "t" }, N: { "4": "B A" }, O: { "1": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 1, C: "HTML5 form features" };
},{}],282:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "548": "A" }, B: { "516": "D X g H L" }, C: { "2": "1 RB F I J C G E PB OB", "676": "B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p", "1700": "0 2 4 q r w x v z t s" }, D: { "2": "F I J C G E B A D X g", "676": "H L M N O", "804": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I CB", "676": "EB", "804": "J C G E B A FB GB HB IB JB" }, F: { "1": "y", "2": "5 6 E A D KB LB MB NB QB", "804": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "292": "B" }, K: { "2": "5 6 B A D y", "804": "K" }, L: { "804": "8" }, M: { "1700": "t" }, N: { "2": "B", "548": "A" }, O: { "804": "jB" }, P: { "804": "F I" }, Q: { "804": "kB" }, R: { "804": "lB" } }, B: 1, C: "Full Screen API" };
},{}],283:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P", "33": "Q R S T" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Gamepad API" };
},{}],284:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t PB OB", "8": "1 RB", "129": "2 4 s" }, D: { "1": "I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "4": "F", "129": "0 2 4 8 x v z t s DB AB SB BB" }, E: { "1": "I J C G E A EB FB GB HB IB JB", "8": "7 F CB", "129": "B" }, F: { "1": "5 6 A D L M N O P Q R S T U V W u Y Z a b c d e f K h NB QB y", "2": "E H KB", "8": "LB MB", "129": "i j k l m n o p q r" }, G: { "1": "3 7 9 G UB VB WB XB YB ZB", "129": "A aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F dB eB fB gB hB iB", "129": "s" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "8": "B" }, L: { "129": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F", "129": "I" }, Q: { "129": "kB" }, R: { "129": "lB" } }, B: 2, C: "Geolocation" };
},{}],285:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "644": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "RB", "260": "F I J C G E B A", "1156": "1", "1284": "PB", "1796": "OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "16": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "16": "E KB", "132": "LB MB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "132": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Element.getBoundingClientRect()" };
},{}],286:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "RB", "132": "1 PB OB" }, D: { "1": "0 2 4 8 A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "260": "F I J C G E B" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "260": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "260": "E KB LB MB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "260": "3 7 9" }, H: { "260": "cB" }, I: { "1": "3 F s gB hB iB", "260": "1 dB eB fB" }, J: { "1": "B", "260": "C" }, K: { "1": "5 6 A D K y", "260": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "getComputedStyle" };
},{}],287:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "getElementsByClassName" };
},{}],288:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "33": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P PB OB" }, D: { "1": "0 2 4 8 A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B", "33": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "crypto.getRandomValues()" };
},{}],289:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q PB OB" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, E: { "2": "7 F I J C CB EB FB GB", "129": "A IB JB", "194": "G E B HB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "2": "3 7 9 UB VB WB", "129": "A bB", "194": "G XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "navigator.hardwareConcurrency" };
},{}],290:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "8": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "8": "1 RB PB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "8": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "8": "E KB LB MB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "2": "dB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "8": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Hashchange event" };
},{}],291:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B CB EB FB GB HB IB", "129": "A JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB YB ZB aB bB", "129": "A" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "HEIF/ISO Base Media File Format" };
},{}],292:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "132": "A" }, B: { "132": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B CB EB FB GB HB IB", "513": "A JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "258": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "258": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "258": "I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "HEVC/H.265 video format" };
},{}],293:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "3 F s gB hB iB", "2": "1 dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 D K y", "2": "B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "hidden attribute" };
},{}],294:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O", "33": "P Q R S" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A YB ZB aB bB", "2": "3 7 9 UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "High Resolution Time API" };
},{}],295:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F CB", "4": "I EB" }, F: { "1": "5 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "6 E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "7 9", "4": "3" }, H: { "2": "cB" }, I: { "1": "3 s eB fB hB iB", "2": "1 F dB gB" }, J: { "1": "C B" }, K: { "1": "5 6 D K y", "2": "B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Session history management" };
},{}],296:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 UB", "129": "G A VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB", "257": "eB fB" }, J: { "1": "B", "16": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "516": "jB" }, P: { "1": "F I" }, Q: { "16": "kB" }, R: { "1": "lB" } }, B: 4, C: "HTML Media Capture" };
},{}],297:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G", "260": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "RB", "132": "1 PB OB", "260": "F I J C G E B A D X g H L M N O P" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I", "260": "J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "132": "7 F CB", "260": "I J EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "132": "E A KB LB MB NB", "260": "5 6 D QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "132": "7", "260": "3 9 UB VB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "132": "dB", "260": "1 3 F eB fB gB" }, J: { "260": "C B" }, K: { "1": "K", "132": "B", "260": "5 6 A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "260": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "New semantic elements" };
},{}],298:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "HTTP Live Streaming (HLS)" };
},{}],299:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "388": "A" }, B: { "257": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB", "257": "0 2 4 f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "257": "k l m n o p q r w x", "1281": "0 2 4 8 v z t s DB AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "772": "E B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y", "257": "u Y Z a b c d e f K", "1281": "h i j k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB", "257": "A YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "257": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "257": "K" }, L: { "1281": "8" }, M: { "257": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "257": "F", "1281": "I" }, Q: { "1281": "kB" }, R: { "257": "lB" } }, B: 6, C: "HTTP/2 protocol" };
},{}],300:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L PB OB", "4": "M N O P Q R S T U V W" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "2": "7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "2": "dB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "sandbox attribute for iframes" };
},{}],301:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "16": "0 2 4 z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "66": "P Q R S T U V" }, E: { "2": "7 F I J G E B A CB EB FB HB IB JB", "130": "C GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB XB YB ZB aB bB", "130": "WB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "seamless attribute for iframes" };
},{}],302:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E B A" }, B: { "8": "D X g H L" }, C: { "1": "0 2 4 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "RB", "8": "1 F I J C G E B A D X g H L M N O P Q R S T PB OB" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X", "8": "g H L M N O" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 CB", "8": "F I EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E A KB LB MB NB", "8": "5 6 D QB y" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "7", "8": "3 9 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "8": "1 3 F dB eB fB gB" }, J: { "1": "B", "8": "C" }, K: { "1": "K", "2": "B A", "8": "5 6 D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "srcdoc attribute for iframes" };
},{}],303:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB", "194": "0 2 4 e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "322": "0 2 4 8 t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y", "322": "j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "322": "kB" }, R: { "1": "lB" } }, B: 5, C: "ImageCapture API" };
},{}],304:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "161": "A" }, B: { "161": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B", "161": "A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "Input Method Editor API" };
},{}],305:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "naturalWidth & naturalHeight image properties" };
},{}],306:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "8": "B A" }, B: { "8": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB", "8": "Z a", "200": "0 2 4 b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y", "322": "Z a b c d", "584": "e" }, E: { "2": "7 F I CB EB", "8": "J C G E B A FB GB HB IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L KB LB MB NB QB y", "1090": "M N O P Q", "2120": "R" }, G: { "2": "3 7 9 UB VB", "8": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "8": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "HTML Imports" };
},{}],307:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB", "16": "PB" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "indeterminate checkbox" };
},{}],308:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "B A D X g H", "36": "F I J C G E" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "B", "8": "F I J C G E", "33": "S", "36": "A D X g H L M N O P Q R" }, E: { "1": "B A IB JB", "8": "7 F I J C CB EB FB", "260": "G E GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E KB LB", "8": "5 6 A D MB NB QB y" }, G: { "1": "A aB bB", "8": "3 7 9 UB VB WB", "260": "G XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "8": "1 3 F dB eB fB gB" }, J: { "1": "B", "8": "C" }, K: { "1": "K", "2": "B", "8": "5 6 A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "IndexedDB" };
},{}],309:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m PB OB", "132": "n o p", "260": "q r w x" }, D: { "1": "8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q", "132": "r w x v", "260": "0 2 4 z t s" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y", "132": "e f K h", "260": "i j k l m n" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB", "16": "aB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "260": "s" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D y", "132": "K" }, L: { "260": "8" }, M: { "16": "t" }, N: { "2": "B A" }, O: { "16": "jB" }, P: { "16": "F", "260": "I" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 5, C: "IndexedDB 2.0" };
},{}],310:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "4": "TB", "132": "J C" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "36": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS inline-block" };
},{}],311:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.innerText" };
},{}],312:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B TB", "132": "A" }, B: { "132": "D X g H L" }, C: { "1": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB", "516": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "M N O P Q R S T U V", "2": "F I J C G E B A D X g H L", "132": "W u Y Z a b c d e f K h i j", "260": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J EB FB", "2": "7 F I CB", "2052": "C G E B A GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9", "1025": "G A UB VB WB XB YB ZB aB bB" }, H: { "1025": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2052": "B A" }, O: { "1025": "jB" }, P: { "1": "F I" }, Q: { "260": "kB" }, R: { "1": "lB" } }, B: 1, C: "autocomplete attribute: on & off values" };
},{}],313:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "5 6 A D M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E H L KB LB MB NB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Color input type" };
},{}],314:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "132": "D" }, C: { "1": "4 s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "1090": "0 2 t" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9", "260": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 dB eB fB", "514": "3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Date and time input types" };
},{}],315:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "132": "dB eB fB" }, J: { "1": "B", "132": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Email, telephone & URL input types" };
},{}],316:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "2561": "B A", "2692": "E" }, B: { "2561": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "16": "RB", "1537": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r OB", "1796": "1 PB" }, D: { "16": "F I J C G E B A D X g", "1025": "0 2 4 8 e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "1537": "H L M N O P Q R S T U V W u Y Z a b c d" }, E: { "16": "7 F I J CB", "1025": "C G E B A FB GB HB IB JB", "1537": "EB" }, F: { "1": "y", "16": "5 6 E A D KB LB MB NB", "260": "QB", "1025": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "1537": "H L M N O P Q" }, G: { "16": "3 7 9", "1025": "G A XB YB ZB aB bB", "1537": "UB VB WB" }, H: { "2": "cB" }, I: { "16": "dB eB", "1025": "s iB", "1537": "1 3 F fB gB hB" }, J: { "1025": "B", "1537": "C" }, K: { "1": "5 6 B A D y", "1025": "K" }, L: { "1025": "8" }, M: { "1537": "t" }, N: { "2561": "B A" }, O: { "1537": "jB" }, P: { "1025": "F I" }, Q: { "1025": "kB" }, R: { "1025": "lB" } }, B: 1, C: "input event" };
},{}],317:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F", "16": "I J C G Q R S T U", "132": "E B A D X g H L M N O P" }, E: { "2": "7 F I CB EB", "132": "J C G E B A FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "VB WB", "132": "G A XB YB ZB aB bB", "514": "3 7 9 UB" }, H: { "2": "cB" }, I: { "2": "dB eB fB", "260": "1 3 F gB", "514": "s hB iB" }, J: { "132": "B", "260": "C" }, K: { "2": "5 6 B A D y", "260": "K" }, L: { "260": "8" }, M: { "2": "t" }, N: { "514": "B", "1028": "A" }, O: { "2": "jB" }, P: { "260": "F I" }, Q: { "1": "kB" }, R: { "260": "lB" } }, B: 1, C: "accept attribute for file input" };
},{}],318:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB LB MB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "130": "cB" }, I: { "130": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "130": "5 6 B A D K y" }, L: { "132": "8" }, M: { "130": "t" }, N: { "2": "B A" }, O: { "130": "jB" }, P: { "130": "F", "132": "I" }, Q: { "1": "kB" }, R: { "132": "lB" } }, B: 1, C: "Multiple file selection" };
},{}],319:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L PB OB", "4": "M N O P", "194": "0 2 4 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "194": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "inputmode attribute" };
},{}],320:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB" }, D: { "1": "0 2 4 8 j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 1, C: "Minimum length attribute for input fields" };
},{}],321:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "129": "B A" }, B: { "129": "D X", "1025": "g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "513": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "388": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 dB eB fB", "388": "3 F s gB hB iB" }, J: { "2": "C", "388": "B" }, K: { "1": "5 6 B A D y", "388": "K" }, L: { "388": "8" }, M: { "641": "t" }, N: { "388": "B A" }, O: { "388": "jB" }, P: { "388": "F I" }, Q: { "1": "kB" }, R: { "388": "lB" } }, B: 1, C: "Number input type" };
},{}],322:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E" }, E: { "1": "A IB JB", "2": "7 F CB", "16": "I", "388": "J C G E B EB FB GB HB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "A bB", "16": "3 7 9", "388": "G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D y", "132": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Pattern attribute for input fields" };
},{}],323:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "132": "7 F CB" }, F: { "1": "5 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB", "132": "6 A" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 s dB eB fB hB iB", "4": "F gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "input placeholder attribute" };
},{}],324:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "3 s hB iB", "4": "1 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Range input type" };
},{}],325:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "129": "B A" }, B: { "129": "D X g H L" }, C: { "2": "1 RB PB OB", "129": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g Q R S T U", "129": "H L M N O P" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB", "16": "5 6 A" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "129": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "129": "1 3 F fB gB" }, J: { "1": "C", "129": "B" }, K: { "1": "D", "2": "B", "16": "5 6 A", "129": "K y" }, L: { "1": "8" }, M: { "129": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Search input type" };
},{}],326:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Element.insertAdjacentElement() & Element.insertAdjacentText()" };
},{}],327:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "16": "TB", "132": "J C G E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "16": "E KB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Element.insertAdjacentHTML()" };
},{}],328:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Internationalization API" };
},{}],329:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB", "194": "0 2 4 z t s" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "IntersectionObserver" };
},{}],330:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "RB", "932": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q", "545": "R S T U V W u Y Z a b c d e f K h i j k l m n o", "1537": "0 2 4 8 p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J CB EB", "516": "A JB", "548": "E B HB IB", "676": "C G FB GB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "513": "d", "545": "H L M N O P Q R S T U V W u Y Z a b", "1537": "c e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 UB VB", "548": "A YB ZB aB bB", "676": "G WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "545": "hB iB", "1537": "s" }, J: { "2": "C", "545": "B" }, K: { "2": "5 6 B A D y", "1537": "K" }, L: { "1537": "8" }, M: { "932": "t" }, N: { "2": "B A" }, O: { "545": "jB" }, P: { "545": "F", "1537": "I" }, Q: { "545": "kB" }, R: { "1537": "lB" } }, B: 5, C: "Intrinsic & Extrinsic Sizing" };
},{}],331:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F CB", "129": "I EB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "JPEG 2000 image format" };
},{}],332:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "JPEG XR image format" };
},{}],333:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C TB", "129": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "JSON parsing" };
},{}],334:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "16": "7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "132": "1 3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Improved kerning pairs & ligatures" };
},{}],335:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "16": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "16": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "16": "D" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "y", "2": "5 6 B A", "16": "D", "130": "K" }, L: { "1": "8" }, M: { "130": "t" }, N: { "130": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "KeyboardEvent.charCode" };
},{}],336:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "1": "0 2 4 8 r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k", "194": "l m n o p q" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u KB LB MB NB QB y", "194": "Y Z a b c d" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "194": "K" }, L: { "194": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "194": "I" }, Q: { "2": "kB" }, R: { "194": "lB" } }, B: 5, C: "KeyboardEvent.code" };
},{}],337:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A H L KB LB MB NB QB", "16": "D" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K y", "2": "5 6 B A", "16": "D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "KeyboardEvent.getModifierState()" };
},{}],338:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "260": "E B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB", "132": "S T U V W u" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "h i j k l m n o p q r y", "2": "5 6 E A H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB", "16": "D" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "y", "2": "5 6 B A K", "16": "D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "KeyboardEvent.key" };
},{}],339:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "C G E B A FB GB HB IB JB", "16": "7 J CB", "132": "F I EB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "16": "D", "132": "H L" }, G: { "1": "G A XB YB ZB aB bB", "16": "3 7 9", "132": "UB VB WB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "16": "dB eB", "132": "1 3 F fB gB" }, J: { "132": "C B" }, K: { "1": "K y", "2": "5 6 B A", "16": "D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "KeyboardEvent.location" };
},{}],340:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "16": "I" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "16": "E KB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB", "16": "dB eB", "132": "hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D y", "132": "K" }, L: { "132": "8" }, M: { "132": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "2": "F", "132": "I" }, Q: { "1": "kB" }, R: { "132": "lB" } }, B: 7, C: "KeyboardEvent.which" };
},{}],341:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Resource Hints: Lazyload" };
},{}],342:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 n o p q r w x v z t s", "194": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N", "322": "O P Q R S T U V W u Y Z a b c d e f K h i j", "516": "k l m n o p q r" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "322": "H L M N O P Q R S T U V W", "516": "u Y Z a b c d e" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "I", "516": "F" }, Q: { "2": "kB" }, R: { "516": "lB" } }, B: 6, C: "let" };
},{}],343:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "129": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "257": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "129": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "513": "5 6 E A D KB LB MB NB QB y" }, G: { "1026": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1026": "cB" }, I: { "1": "1 3 F dB eB fB gB", "513": "s hB iB" }, J: { "1": "C", "1026": "B" }, K: { "1026": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1026": "B A" }, O: { "257": "jB" }, P: { "1": "I", "513": "F" }, Q: { "129": "kB" }, R: { "1": "lB" } }, B: 1, C: "PNG favicons" };
},{}],344:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB PB OB", "260": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "1025": "0 2 4 k l m n o p q r w x v z t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "516": "E B A HB IB JB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m KB LB MB NB QB y" }, G: { "130": "3 7 9 G UB VB WB XB", "516": "A YB ZB aB bB" }, H: { "130": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "130": "B" }, K: { "130": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "130": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "SVG favicons" };
},{}],345:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G TB", "132": "E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "16": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Resource Hints: dns-prefetch" };
},{}],346:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h PB OB", "129": "i" }, D: { "1": "0 2 4 8 p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "16": "t" }, N: { "2": "B A" }, O: { "16": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Resource Hints: preconnect" };
},{}],347:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "F s hB iB", "2": "1 3 dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Resource Hints: prefetch" };
},{}],348:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "Resource Hints: preload" };
},{}],349:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "8 F I J C G E B A D DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Resource Hints: prerender" };
},{}],350:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "16": "TB", "132": "J C G E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "132": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S" }, E: { "1": "B A IB JB", "132": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "5 6 E A D KB LB MB NB QB", "132": "y" }, G: { "1": "A aB bB", "132": "3 7 9 G UB VB WB XB YB ZB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "132": "1 3 F dB eB fB gB" }, J: { "132": "C B" }, K: { "1": "K", "16": "5 6 B A D", "132": "y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "132": "B" }, O: { "132": "jB" }, P: { "1": "I", "132": "F" }, Q: { "132": "kB" }, R: { "1": "lB" } }, B: 6, C: "localeCompare()" };
},{}],351:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "36": "E B A" }, B: { "1": "H L", "36": "D X g" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB", "36": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c OB" }, D: { "1": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "36": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c" }, E: { "1": "G E B A GB HB IB JB", "2": "7 F CB", "36": "I J C EB FB" }, F: { "1": "Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "6 E A KB LB MB NB", "36": "5 D H L M N O P QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "7", "36": "3 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB", "36": "1 3 F eB fB gB hB iB" }, J: { "36": "C B" }, K: { "1": "K", "2": "B A", "36": "5 6 D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "36": "B A" }, O: { "36": "jB" }, P: { "1": "I", "36": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "matches() DOM method" };
},{}],352:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB" }, D: { "1": "0 2 4 8 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "matchMedia" };
},{}],353:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "E B A TB", "8": "J C G" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "129": "1 RB PB OB" }, D: { "1": "T", "8": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "B A IB JB", "260": "7 F I J C G E CB EB FB GB HB" }, F: { "2": "E", "4": "5 6 A D KB LB MB NB QB y", "8": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "8": "3 7 9" }, H: { "8": "cB" }, I: { "8": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "B", "8": "C" }, K: { "8": "5 6 B A D K y" }, L: { "8": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "4": "jB" }, P: { "8": "F I" }, Q: { "8": "kB" }, R: { "8": "lB" } }, B: 2, C: "MathML" };
},{}],354:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "16": "TB", "900": "J C G E" }, B: { "1025": "D X g H L" }, C: { "1": "0 2 4 v z t s", "900": "1 RB PB OB", "1025": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "I CB", "900": "7 F" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E", "132": "5 6 A D KB LB MB NB QB y" }, G: { "1": "3 9 A UB VB WB YB ZB aB bB", "16": "7", "2052": "G XB" }, H: { "132": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "132": "5 6 B A D y", "4100": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "4100": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "maxlength attribute for input and textarea elements" };
},{}],355:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c", "2": "0 2 4 8 d e f K h i j k l m n o p q r w x v z t s DB", "16": "AB SB BB" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 A D H L M N O P Q R S T LB MB NB QB y", "2": "E U V W u Y Z a b c d e f K h i j k l m n o p q r KB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "16": "cB" }, I: { "1": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "16": "C B" }, K: { "1": "D K y", "16": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 1, C: "Media attribute" };
},{}],356:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "4 8 DB AB SB BB", "2": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "2": "7 F I J C G E B CB EB FB GB HB IB", "16": "A JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB y", "16": "q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Media Session API" };
},{}],357:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "193": "0 2 4 8 v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Media Capture from DOM Elements API" };
},{}],358:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p", "194": "q r" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c KB LB MB NB QB y", "194": "d e" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 5, C: "MediaRecorder API" };
},{}],359:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "260": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB", "194": "U V W u Y Z a b c d e f K h i j k" }, D: { "1": "0 2 4 8 a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L", "33": "S T U V W u Y Z", "66": "M N O P Q R" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "I", "514": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "Media Source Extensions" };
},{}],360:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C PB OB", "132": "0 2 4 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "322": "r w x v", "578": "k l m n o p q", "2114": "0 2 4 8 z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y", "322": "e f K h", "2114": "i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1156": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2114": "kB" }, R: { "2": "lB" } }, B: 1, C: "Toolbar/context menu" };
},{}],361:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H PB OB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "meter element" };
},{}],362:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Web MIDI API" };
},{}],363:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "8": "J TB", "129": "C", "257": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "CSS min/max-width/height" };
},{}],364:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "132": "F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "2": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "MP3 audio format" };
},{}],365:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P PB OB", "4": "Q R S T U V W u Y Z a b c d" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "2": "CB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "4": "1 3 F dB eB gB", "132": "fB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "260": "t" }, N: { "1": "B A" }, O: { "4": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "MPEG-4/H.264 video format" };
},{}],366:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Multiple backgrounds" };
},{}],367:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "132": "0 2 4 z t s", "164": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "132": "0 2 4 8 x v z t s DB AB SB BB", "420": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w" }, E: { "132": "E B A HB IB JB", "164": "C G GB", "420": "7 F I J CB EB FB" }, F: { "1": "5 6 D QB y", "2": "E A KB LB MB NB", "132": "K h i j k l m n o p q r", "420": "H L M N O P Q R S T U V W u Y Z a b c d e f" }, G: { "132": "A YB ZB aB bB", "164": "G WB XB", "420": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "132": "s", "420": "1 3 F dB eB fB gB hB iB" }, J: { "420": "C B" }, K: { "1": "5 6 D y", "2": "B A", "132": "K" }, L: { "132": "8" }, M: { "132": "t" }, N: { "1": "B A" }, O: { "420": "jB" }, P: { "132": "I", "420": "F" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 4, C: "CSS3 Multiple column layout" };
},{}],368:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "260": "E B A" }, B: { "260": "D X g H L" }, C: { "2": "1 RB F I PB OB", "260": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "16": "F I J C G E B A D X g", "132": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "16": "7 CB", "132": "F I J C G E B A EB FB GB HB IB JB" }, F: { "1": "D QB y", "2": "E KB LB MB NB", "16": "5 6 A", "132": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "16": "7 9", "132": "3 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "dB eB", "132": "1 3 F s fB gB hB iB" }, J: { "132": "C B" }, K: { "1": "D y", "2": "B", "16": "5 6 A", "132": "K" }, L: { "132": "8" }, M: { "260": "t" }, N: { "260": "B A" }, O: { "132": "jB" }, P: { "132": "F I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 5, C: "Mutation events" };
},{}],369:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G TB", "8": "E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X PB OB" }, D: { "1": "0 2 4 8 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M", "33": "N O P Q R S T U V" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "33": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB", "33": "VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 dB eB fB", "8": "3 F gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "8": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Mutation Observer" };
},{}],370:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "TB", "8": "J C" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "4": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Web Storage - name/value pairs" };
},{}],371:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J PB OB" }, D: { "1": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I", "33": "J C G E B A D" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A YB ZB aB bB", "2": "3 7 9 UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "3 F s gB hB iB", "2": "1 dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Navigation Timing API" };
},{}],372:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB hB iB", "132": "1 3 F eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "132": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 7, C: "Network Information API" };
},{}],373:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "TB", "644": "E B A", "2308": "J C G" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "16": "7 F I J CB", "1668": "EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "16": "5 6 E A D KB LB MB NB", "132": "QB" }, G: { "1": "G A WB XB YB ZB aB bB", "16": "3 7 9 UB VB" }, H: { "16": "cB" }, I: { "1": "s hB iB", "16": "1 dB eB fB", "1668": "3 F gB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.contains()" };
},{}],374:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "16": "TB", "132": "E B A", "260": "J C G" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "5 6 E A KB LB MB NB", "132": "D QB y" }, G: { "1": "G A VB WB XB YB ZB aB bB", "16": "3 7 9 UB" }, H: { "16": "cB" }, I: { "1": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.parentElement" };
},{}],375:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F", "36": "I J C G E B A D X g H L M N O P Q" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "36": "s hB iB" }, J: { "1": "B", "2": "C" }, K: { "2": "5 6 B A D y", "36": "K" }, L: { "258": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "36": "F", "258": "I" }, Q: { "2": "kB" }, R: { "258": "lB" } }, B: 1, C: "Web Notifications" };
},{}],376:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "L", "2": "D X g H" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB" }, D: { "1": "0 2 4 8 a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z" }, E: { "1": "B A IB JB", "2": "7 F I J C CB EB FB", "132": "G E GB HB" }, F: { "1": "O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E H L M N KB LB MB", "33": "5 6 A D NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 UB VB WB", "132": "G XB YB ZB" }, H: { "33": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB hB" }, J: { "2": "C B" }, K: { "1": "K", "2": "B", "33": "5 6 A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 object-fit/object-position" };
},{}],377:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "f K h i j k l m n o p q r w", "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f", "2": "5 6 E A D H L M N O P Q R K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F", "2": "I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Object.observe data binding" };
},{}],378:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "130": "B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Object RTC (ORTC) API for WebRTC" };
},{}],379:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "E TB", "8": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "4": "1", "8": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "8": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB", "8": "LB MB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Offline web applications" };
},{}],380:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Ogg Vorbis audio format" };
},{}],381:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "8": "E B A" }, B: { "8": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Ogg/Theora video format" };
},{}],382:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M PB OB" }, D: { "1": "0 2 4 8 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H", "16": "L M N O" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "16": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "16": "D" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Reversed attribute of ordered lists" };
},{}],383:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "L", "2": "D X g H" }, C: { "1": "0 2 4 x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w PB OB" }, D: { "1": "2 4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "\"once\" event listener option" };
},{}],384:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C TB", "260": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s PB OB", "2": "1 RB", "516": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, D: { "1": "0 2 4 8 g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB", "4": "y" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "16": "7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "B", "132": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "132": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Online/offline status" };
},{}],385:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Opus" };
},{}],386:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "260": "G", "388": "E B A" }, B: { "1": "H L", "388": "D X g" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB", "129": "y", "260": "5 6 E A KB LB MB NB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "D K y", "260": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "388": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS outline properties" };
},{}],387:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q PB OB" }, D: { "1": "4 8 DB AB SB BB", "2": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "16": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "16": "s" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D y", "16": "K" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "String.prototype.padStart(), String.prototype.padEnd()" };
},{}],388:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "PageTransitionEvent" };
},{}],389:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E PB OB", "33": "B A D X g H L M" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X", "33": "g H L M N O P Q R S T U V W u Y Z a b" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB", "33": "H L M N O" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "33": "hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "I", "33": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Page Visibility" };
},{}],390:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "L", "2": "D X g H" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Passive event listeners" };
},{}],391:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X", "322": "g" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t PB OB", "4162": "2 4 s" }, D: { "1": "AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "194": "0 2 4 t s DB", "1090": "8" }, E: { "2": "7 F I J C G E CB EB FB GB HB", "514": "B A IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y", "194": "j k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB YB ZB", "514": "A aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2049": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "194": "kB" }, R: { "2": "lB" } }, B: 5, C: "Payment Request API" };
},{}],392:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o PB OB" }, D: { "1": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Permissions API" };
},{}],393:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c PB OB", "578": "d e f K" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f", "194": "K" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y", "322": "T" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Picture element" };
},{}],394:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "RB", "194": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "194": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Ping attribute" };
},{}],395:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "C G E B A", "2": "TB", "8": "J" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "PNG alpha transparency" };
},{}],396:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "CSS pointer-events (for HTML)" };
},{}],397:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E TB", "164": "B" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I PB OB", "8": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j", "328": "0 2 4 k l m n o p q r w x v z t s" }, D: { "1": "2 4 8 s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q", "8": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v", "584": "0 z t" }, E: { "2": "7 F I J CB EB", "8": "C G E B A FB GB HB IB JB" }, F: { "1": "l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "8": "H L M N O P Q R S T U V W u Y Z a b c d e f K h", "584": "i j k" }, G: { "8": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "8": "1 3 F dB eB fB gB hB iB" }, J: { "8": "C B" }, K: { "2": "B", "8": "5 6 A D K y" }, L: { "1": "8" }, M: { "328": "t" }, N: { "1": "A", "36": "B" }, O: { "8": "jB" }, P: { "2": "I", "8": "F" }, Q: { "584": "kB" }, R: { "2": "lB" } }, B: 2, C: "Pointer events" };
},{}],398:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "2": "D" }, C: { "1": "0 2 4 k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X PB OB", "33": "g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, D: { "1": "0 2 4 8 K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H", "33": "R S T U V W u Y Z a b c d e f", "66": "L M N O P Q" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "PointerLock API" };
},{}],399:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I PB OB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E KB LB MB NB" }, G: { "2": "3 7 9 UB VB", "132": "G A WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "progress element" };
},{}],400:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "8": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "4": "W u", "8": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V PB OB" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "b", "8": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a" }, E: { "1": "G E B A GB HB IB JB", "8": "7 F I J C CB EB FB" }, F: { "1": "P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "4": "O", "8": "5 6 E A D H L M N KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "8": "3 7 9 UB VB WB" }, H: { "8": "cB" }, I: { "1": "s iB", "8": "1 3 F dB eB fB gB hB" }, J: { "8": "C B" }, K: { "1": "K", "8": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Promises" };
},{}],401:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 4, C: "Proximity API" };
},{}],402:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N h i j k l m n o p q r", "66": "O P Q R S T U V W u Y Z a b c d e f K" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D U V W u Y Z a b c d e KB LB MB NB QB y", "66": "H L M N O P Q R S T" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "Proxy object" };
},{}],403:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d PB OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O KB LB MB NB QB y", "4": "S", "16": "P Q R T" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Public Key Pinning" };
},{}],404:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m PB OB", "257": "0 2 4 n p q r w x v t s", "1281": "o z" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m", "257": "0 2 4 8 x v z t s DB AB SB BB", "388": "n o p q r w" }, E: { "2": "7 F I J C G E CB EB FB GB", "514": "B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f KB LB MB NB QB y", "16": "K h i j k", "257": "l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 5, C: "Push API" };
},{}],405:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "TB", "8": "J C", "132": "G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "8": "E KB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "querySelector/querySelectorAll" };
},{}],406:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "16": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "16": "1 RB PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E KB", "132": "5 6 A D LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "16": "3 7 9 UB VB" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "132": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "257": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "readonly attribute of input and textarea elements" };
},{}],407:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB" }, D: { "1": "AB SB BB", "2": "F I J C G E B A D X g H L M N O P", "260": "0 2 4 8 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB" }, E: { "2": "7 F I J C CB EB FB", "132": "G E B A GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 UB VB WB", "132": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Referrer Policy" };
},{}],408:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "2": "F I J C G E B A D", "129": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A KB LB MB NB", "129": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C", "129": "B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Custom protocol handling" };
},{}],409:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "rel=noopener" };
},{}],410:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "132": "A" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB" }, D: { "1": "0 2 4 8 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Link type \"noreferrer\"" };
},{}],411:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w", "132": "0 2 4 8 x v z t s DB AB SB BB" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C G CB EB FB GB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f KB LB MB NB QB y", "132": "K h i j k l m n o p q r" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "132": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "132": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "132": "I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "relList (DOMTokenList)" };
},{}],412:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G TB", "132": "E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "1": "3 9 G A VB WB XB YB ZB aB bB", "2": "7", "260": "UB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "rem (root em) units" };
},{}],413:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "33": "A D X g H L M N O P Q R", "164": "F I J C G E B" }, D: { "1": "0 2 4 8 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E", "33": "R S", "164": "N O P Q", "420": "B A D X g H L M" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "33": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB", "33": "VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "requestAnimationFrame" };
},{}],414:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v PB OB" }, D: { "1": "0 2 4 8 q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "requestIdleCallback" };
},{}],415:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "194": "2 4 8 t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j KB LB MB NB QB y", "194": "k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "194": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Resize Observer" };
},{}],416:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB", "194": "a b c d" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Resource Timing" };
},{}],417:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m", "194": "n o p" }, E: { "1": "B A IB JB", "2": "7 F I J C G E CB EB FB GB HB" }, F: { "1": "d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z KB LB MB NB QB y", "194": "a b c" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "Rest parameters" };
},{}],418:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "H L", "2": "D X g" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "33": "R S T U V W u Y Z a b c d e f K h i j k l m" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R", "33": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "2": "5 6 E A D H L M KB LB MB NB QB y", "33": "N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "33": "s" }, J: { "2": "C", "130": "B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 5, C: "WebRTC Peer-to-peer connections" };
},{}],419:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "4": "J C G E B A TB" }, B: { "4": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "8": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "4": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F" }, E: { "4": "I J C G E B A EB FB GB HB IB JB", "8": "7 F CB" }, F: { "4": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "8": "5 6 E A D KB LB MB NB QB y" }, G: { "4": "G A UB VB WB XB YB ZB aB bB", "8": "3 7 9" }, H: { "8": "cB" }, I: { "4": "1 3 F s gB hB iB", "8": "dB eB fB" }, J: { "4": "B", "8": "C" }, K: { "4": "K", "8": "5 6 B A D y" }, L: { "4": "8" }, M: { "1": "t" }, N: { "4": "B A" }, O: { "4": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 1, C: "Ruby annotation" };
},{}],420:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "'SameSite' cookie attribute" };
},{}],421:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "36": "A" }, B: { "36": "D X g H L" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M PB OB", "36": "N O P Q R S T U V W u Y Z a b c d e f K h i j k l m" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B", "36": "A" }, O: { "1": "jB" }, P: { "1": "I", "16": "F" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 5, C: "Screen Orientation" };
},{}],422:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F CB", "132": "I" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "async attribute for external scripts" };
},{}],423:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "132": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "257": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "7 F CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "defer attribute for external scripts" };
},{}],424:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "132": "G E B A" }, B: { "132": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "132": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e PB OB" }, D: { "132": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I CB", "132": "J C G E B A EB FB GB HB IB JB" }, F: { "2": "E KB LB MB NB", "16": "5 6 A", "132": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y" }, G: { "16": "3 7 9", "132": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "16": "dB eB", "132": "1 3 F s fB gB hB iB" }, J: { "132": "C B" }, K: { "132": "5 6 B A D K y" }, L: { "132": "8" }, M: { "132": "t" }, N: { "132": "B A" }, O: { "132": "jB" }, P: { "132": "F I" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 5, C: "scrollIntoView" };
},{}],425:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Element.scrollIntoViewIfNeeded()" };
},{}],426:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "2": "8 AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "SDCH Accept-Encoding/Content-Encoding" };
},{}],427:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "16": "TB", "260": "J C G" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 z t s", "132": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l PB OB", "2180": "m n o p q r w x v" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "132": "5 6 E A D KB LB MB NB QB y" }, G: { "16": "3", "132": "7 9", "516": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "16": "1 F dB eB fB gB", "1025": "3" }, J: { "1": "B", "16": "C" }, K: { "1": "K", "16": "5 6 B A D", "132": "y" }, L: { "1": "8" }, M: { "132": "t" }, N: { "1": "A", "16": "B" }, O: { "1025": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Selection API" };
},{}],428:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "322": "H L" }, C: { "1": "0 2 4 n p q r w x v t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "194": "c d e f K h i j k l m", "513": "o z" }, D: { "1": "0 2 4 8 o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i", "4": "j k l m n" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y", "4": "W u Y Z a" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "4": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "4": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "4": "jB" }, P: { "1": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 5, C: "Service Workers" };
},{}],429:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Efficient Script Yielding: setImmediate()" };
},{}],430:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "2": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "260": "dB" }, J: { "1": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "16": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "SHA-2 SSL certificates" };
},{}],431:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "194": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T", "33": "U V W u Y Z a b c d" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB", "33": "hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "I", "33": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Shadow DOM v0" };
},{}],432:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, E: { "2": "7 F I J C G E CB EB FB GB HB", "132": "B A IB JB" }, F: { "1": "j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i KB LB MB NB QB y" }, G: { "2": "3 7 9 G UB VB WB XB YB ZB", "132": "A aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "4": "I" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 5, C: "Shadow DOM v1" };
},{}],433:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "I J EB", "2": "7 F C G E B A CB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB LB MB" }, G: { "1": "UB VB", "2": "3 7 9 G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D y", "2": "K", "16": "B" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F", "2": "I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Shared Web Workers" };
},{}],434:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J TB", "132": "C G" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "2": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Server Name Indication" };
},{}],435:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E B TB" }, B: { "2": "D X g H L" }, C: { "1": "X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "2": "0 1 2 4 RB F I J C G E B A D v z t s PB OB" }, D: { "1": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "2": "0 2 4 8 v z t s DB AB SB BB" }, E: { "1": "G E B A HB IB JB", "2": "7 F I J C CB EB FB GB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i l n y", "2": "5 6 E A D j k m o p q r KB LB MB NB QB" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "1 3 F gB hB iB", "2": "s dB eB fB" }, J: { "2": "C B" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "2": "8" }, M: { "2": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F", "2": "I" }, Q: { "2": "kB" }, R: { "16": "lB" } }, B: 7, C: "SPDY protocol" };
},{}],436:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB", "322": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T", "164": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y", "164": "W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "164": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 7, C: "Speech Recognition API" };
},{}],437:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z PB OB", "194": "a b c d e f K h i j k l m n o p q r" }, D: { "1": "0 c d e f K h i j k l m n o p q r w x v z t", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b", "257": "2 4 8 s DB AB SB BB" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 7, C: "Speech Synthesis API" };
},{}],438:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "4": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "4": "cB" }, I: { "4": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "B", "4": "C" }, K: { "4": "5 6 B A D K y" }, L: { "4": "8" }, M: { "4": "t" }, N: { "4": "B A" }, O: { "4": "jB" }, P: { "4": "F I" }, Q: { "1": "kB" }, R: { "4": "lB" } }, B: 1, C: "Spellcheck attribute" };
},{}],439:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "Web SQL Database" };
},{}],440:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "260": "D", "514": "X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a PB OB", "194": "b c d e f K" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c", "260": "d e f K" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C CB EB FB", "260": "G GB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P KB LB MB NB QB y", "260": "Q R S T" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 UB VB WB", "260": "G XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Srcset and sizes attributes" };
},{}],441:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "16": "D" }, G: { "1": "G A VB WB XB YB ZB aB bB", "16": "3 7 9 UB" }, H: { "16": "cB" }, I: { "1": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "1": "I", "16": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Event.stopImmediatePropagation()" };
},{}],442:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L PB OB", "33": "0 2 4 M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "2": "F I J C G E B A D X g H L M N O P", "164": "0 2 4 8 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "A", "2": "7 F I J C G E B CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A H L M KB LB MB NB QB", "164": "D N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "164": "s" }, J: { "2": "C", "164": "B" }, K: { "2": "5 6 B A", "164": "D K y" }, L: { "164": "8" }, M: { "33": "t" }, N: { "2": "B A" }, O: { "164": "jB" }, P: { "16": "F", "164": "I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 4, C: "getUserMedia/Stream API" };
},{}],443:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B TB", "129": "A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Strict Transport Security" };
},{}],444:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t", "2": "1 4 RB F I J C G E B A D X g H L M N O P s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O K h i j k l m n o p q r w x v z t s DB AB SB BB", "194": "P Q R S T U V W u Y Z a b c d e f" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Scoped CSS" };
},{}],445:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l PB OB" }, D: { "1": "0 2 4 8 o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Subresource Integrity" };
},{}],446:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "260": "F I J C G E B A D X g H L M N O P Q R S" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F" }, E: { "1": "I J C G E B A EB FB GB HB IB JB", "2": "CB", "132": "7 F" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "132": "7 9" }, H: { "260": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "K", "260": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "SVG in CSS backgrounds" };
},{}],447:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F", "4": "I J C" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "3 7 9 UB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "SVG filters" };
},{}],448:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "E B A TB", "8": "J C G" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K", "2": "0 2 4 8 v z t s DB AB SB BB", "130": "h i j k l m n o p q r w x" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "2": "CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y", "2": "K h i j k l m n o p q r", "130": "U V W u Y Z a b c d e f" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "258": "cB" }, I: { "1": "1 3 F gB hB iB", "2": "s dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "130": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F", "130": "I" }, Q: { "1": "kB" }, R: { "130": "lB" } }, B: 7, C: "SVG fonts" };
},{}],449:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e", "132": "f K h i j k l m n o p q r w" }, E: { "2": "7 F I J C E B A CB EB FB HB IB JB", "132": "G GB" }, F: { "1": "K h i j k l m n o p q r y", "2": "H L M N O P Q R", "4": "5 6 A D LB MB NB QB", "16": "E KB", "132": "S T U V W u Y Z a b c d e f" }, G: { "2": "3 7 9 A UB VB WB YB ZB aB bB", "132": "G XB" }, H: { "1": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C", "132": "B" }, K: { "1": "K y", "4": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "132": "jB" }, P: { "1": "I", "132": "F" }, Q: { "132": "kB" }, R: { "132": "lB" } }, B: 2, C: "SVG fragment identifiers" };
},{}],450:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "388": "E B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB", "4": "1" }, D: { "4": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "4": "F I J C G E B A EB FB GB HB IB JB" }, F: { "4": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "4": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "4": "s hB iB" }, J: { "1": "B", "2": "C" }, K: { "4": "5 6 B A D K y" }, L: { "4": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 2, C: "SVG effects for HTML" };
},{}],451:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G", "129": "E B A" }, B: { "129": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB PB OB" }, D: { "1": "0 2 4 8 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "8": "F I J" }, E: { "1": "E B A HB IB JB", "8": "7 F I CB", "129": "J C G EB FB GB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 A NB", "8": "E KB LB MB" }, G: { "1": "A YB ZB aB bB", "8": "3 7 9", "129": "G UB VB WB XB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "129": "1 3 F gB" }, J: { "1": "B", "129": "C" }, K: { "1": "D K y", "8": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "129": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Inline SVG in HTML5" };
},{}],452:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, E: { "1": "E B A HB IB JB", "2": "CB", "4": "7", "132": "F I J C G EB FB GB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "132": "3 7 9 G UB VB WB XB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "132": "1 3 F gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "SVG in HTML img element" };
},{}],453:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E B A" }, B: { "8": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB PB OB" }, D: { "1": "I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n", "4": "F", "257": "0 2 4 8 o p q r w x v z t s DB AB SB BB" }, E: { "1": "J C G E B A FB GB HB IB JB", "8": "7 CB", "132": "F I EB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a KB LB MB NB QB y", "257": "b c d e f K h i j k l m n o p q r" }, G: { "1": "G A VB WB XB YB ZB aB bB", "132": "3 7 9 UB" }, H: { "2": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "257": "kB" }, R: { "1": "lB" } }, B: 2, C: "SVG SMIL animation" };
},{}],454:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G", "257": "E B A" }, B: { "257": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "4": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "4": "CB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "s hB iB", "2": "dB eB fB", "132": "1 3 F gB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "257": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "SVG (basic support)" };
},{}],455:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "C G E B A", "16": "J TB" }, B: { "1": "D X g H L" }, C: { "16": "1 RB PB OB", "129": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g" }, E: { "16": "7 F I CB", "257": "J C G E B A EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "769": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "16": "cB" }, I: { "16": "1 3 F s dB eB fB gB hB iB" }, J: { "16": "C B" }, K: { "16": "5 6 B A D K y" }, L: { "16": "8" }, M: { "16": "t" }, N: { "16": "B A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "2": "kB" }, R: { "16": "lB" } }, B: 1, C: "tabindex global attribute" };
},{}],456:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "X g H L", "16": "D" }, C: { "1": "0 2 4 d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u KB LB MB NB QB y" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 6, C: "ES6 Template Literals (Template Strings)" };
},{}],457:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D", "388": "X g H L" }, C: { "1": "0 2 4 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q PB OB" }, D: { "1": "0 2 4 8 e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U", "132": "V W u Y Z a b c d" }, E: { "1": "E B A HB IB JB", "2": "7 F I J C CB EB", "388": "G GB", "514": "FB" }, F: { "1": "R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "132": "H L M N O P Q" }, G: { "1": "A YB ZB aB bB", "2": "3 7 9 UB VB WB", "388": "G XB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "HTML templates" };
},{}],458:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G B A TB", "16": "E" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "16": "F I" }, D: { "2": "0 2 4 8 F I J C G E B X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "A D" }, E: { "2": "7 F J CB EB", "16": "I C G E B A FB GB HB IB JB" }, F: { "2": "5 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "6" }, G: { "2": "3 7 9 UB VB", "16": "G A WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB gB hB iB", "16": "fB" }, J: { "2": "B", "16": "C" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "Test feature - updated" };
},{}],459:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I PB OB", "1028": "0 2 4 f K h i j k l m n o p q r w x v z t s", "1060": "J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, D: { "1": "4 8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U", "226": "0 2 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, E: { "2": "7 F I J C CB EB FB", "804": "G E B A HB IB JB", "1316": "GB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d KB LB MB NB QB y", "226": "e f K h i j k l m" }, G: { "2": "3 7 9 UB VB WB", "292": "G A XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 4, C: "text-decoration styling" };
},{}],460:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n PB OB", "322": "o" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T", "164": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "G E B A GB HB IB JB", "2": "7 F I J CB EB", "164": "C FB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "164": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB", "164": "s hB iB" }, J: { "2": "C", "164": "B" }, K: { "2": "5 6 B A D y", "164": "K" }, L: { "164": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "164": "jB" }, P: { "164": "F I" }, Q: { "164": "kB" }, R: { "164": "lB" } }, B: 4, C: "text-emphasis styling" };
},{}],461:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A", "2": "TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "8": "1 RB F I J PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "33": "E KB LB MB NB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "K y", "33": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "CSS3 Text-overflow" };
},{}],462:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "2 4 8 t s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "258": "V" }, E: { "2": "7 F I J C G E B A CB FB GB HB IB JB", "258": "EB" }, F: { "1": "m o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l n KB LB MB NB QB y" }, G: { "2": "3 7 9", "33": "G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "33": "t" }, N: { "161": "B A" }, O: { "33": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 7, C: "CSS text-size-adjust" };
},{}],463:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "161": "H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q PB OB", "161": "0 2 4 w x v z t s", "450": "r" }, D: { "33": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "A JB", "33": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "33": "3 9 G A UB VB WB XB YB ZB aB bB", "36": "7" }, H: { "2": "cB" }, I: { "2": "1", "33": "3 F s dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "33": "8" }, M: { "161": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "33": "lB" } }, B: 7, C: "CSS text-stroke and text-fill" };
},{}],464:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "3 9 G A UB VB WB XB YB ZB aB bB", "16": "7" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Node.textContent" };
},{}],465:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB", "132": "O" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "2": "kB" }, R: { "1": "lB" } }, B: 1, C: "TextEncoder & TextDecoder" };
},{}],466:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C TB", "66": "G E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R PB OB", "66": "S" }, D: { "1": "0 2 4 8 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A D KB LB MB NB QB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "66": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "TLS 1.1" };
},{}],467:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C TB", "66": "G E B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S PB OB", "66": "T U V" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F I J CB EB FB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E H L KB", "66": "5 6 A D LB MB NB QB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "K y", "2": "5 6 B A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "66": "B" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "TLS 1.2" };
},{}],468:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x PB OB", "66": "v" }, D: { "1": "4 8 s DB AB SB BB", "2": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z", "66": "2 t" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k KB LB MB NB QB y", "66": "l" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "16": "s" }, J: { "2": "C", "16": "B" }, K: { "2": "5 6 B A D K y" }, L: { "16": "8" }, M: { "16": "t" }, N: { "2": "B", "16": "A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 6, C: "TLS 1.3" };
},{}],469:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "257": "H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t PB OB", "16": "2 4 s" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h", "16": "0 2 4 i j k l m n o p q r w x v z t s", "194": "8 DB AB SB BB" }, E: { "2": "7 F I J C G CB EB FB GB", "16": "E B A HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y", "16": "Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G UB VB WB XB", "16": "A YB ZB aB bB" }, H: { "16": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "16": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "16": "K" }, L: { "16": "8" }, M: { "16": "t" }, N: { "2": "B", "16": "A" }, O: { "16": "jB" }, P: { "16": "F I" }, Q: { "16": "kB" }, R: { "16": "lB" } }, B: 6, C: "Token Binding" };
},{}],470:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "8": "B A" }, B: { "578": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T z t s", "2": "1 RB PB OB", "4": "F I J C G E B A D X g H L M", "194": "U V W u Y Z a b c d e f K h i j k l m n o p q r w x v" }, D: { "1": "0 2 4 8 R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B", "260": "A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Touch events" };
},{}],471:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G", "129": "B A", "161": "E" }, B: { "129": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "33": "F I J C G E B A D X g H PB OB" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "33": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "1": "E B A HB IB JB", "33": "7 F I J C G CB EB FB GB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB", "33": "5 6 A D H L M N O P Q R MB NB QB" }, G: { "1": "A YB ZB aB bB", "33": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "33": "1 3 F dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "33": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 2D Transforms" };
},{}],472:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E PB OB", "33": "B A D X g H" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A", "33": "D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "2": "7 CB", "33": "F I J C G EB FB GB", "257": "E B A HB IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R" }, G: { "1": "A YB ZB aB bB", "33": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB fB", "33": "1 3 F gB hB iB" }, J: { "33": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "33": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 3D Transforms" };
},{}],473:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB QB y", "2": "E KB" }, G: { "1": "3 G A UB VB WB XB YB ZB aB bB", "2": "7 9" }, H: { "2": "cB" }, I: { "1": "1 3 F s eB fB gB hB iB", "2": "dB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "TTF/OTF - TrueType and OpenType font support" };
},{}],474:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "A", "2": "J C G E TB", "132": "B" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB", "260": "EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "7 9", "260": "3" }, H: { "1": "cB" }, I: { "1": "3 F s gB hB iB", "2": "1 dB eB fB" }, J: { "1": "B", "2": "C" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Typed Arrays" };
},{}],475:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K", "130": "h i j" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "j l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i k KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 6, C: "FIDO U2F API" };
},{}],476:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k PB OB" }, D: { "1": "0 2 4 8 m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Upgrade Insecure Requests" };
},{}],477:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U PB OB" }, D: { "1": "0 2 4 8 b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R", "130": "S T U V W u Y Z a" }, E: { "1": "G E B A GB HB IB JB", "2": "7 F I J CB EB FB", "130": "C" }, F: { "1": "O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "130": "H L M N" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB", "130": "WB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "1 3 F dB eB fB gB", "130": "hB" }, J: { "2": "C", "130": "B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "URL API" };
},{}],478:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "132": "Y Z a b c d e f K h i j k l m" }, D: { "1": "0 2 4 8 w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "1": "f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "I", "2": "F" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "URLSearchParams" };
},{}],479:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB" }, D: { "1": "0 2 4 8 X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F CB", "132": "I EB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "5 6 E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s gB hB iB", "2": "dB eB fB" }, J: { "1": "C B" }, K: { "1": "5 D K y", "2": "6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "ECMAScript 5 Strict Mode" };
},{}],480:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "33": "B A" }, B: { "33": "D X g H L" }, C: { "33": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "2 4 8 t s DB AB SB BB", "33": "0 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z" }, E: { "33": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "33": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j" }, G: { "33": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "33": "1 3 F dB eB fB gB hB iB" }, J: { "33": "C B" }, K: { "2": "5 6 B A D y", "33": "K" }, L: { "1": "8" }, M: { "33": "t" }, N: { "33": "B A" }, O: { "33": "jB" }, P: { "33": "F I" }, Q: { "33": "kB" }, R: { "2": "lB" } }, B: 5, C: "CSS user-select: none" };
},{}],481:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K PB OB" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "User Timing API" };
},{}],482:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B PB OB", "33": "A D X g H" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "Vibration API" };
},{}],483:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "260": "F I J C G E B A D X g H L M N O PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "132": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Video element" };
},{}],484:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I J CB EB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "Video Tracks" };
},{}],485:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "132": "E", "260": "B A" }, B: { "260": "D X g H L" }, C: { "1": "0 2 4 O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB" }, D: { "1": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O", "260": "P Q R S T U" }, E: { "1": "C G E B A FB GB HB IB JB", "2": "7 F I CB EB", "260": "J" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB", "516": "WB", "772": "VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "260": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "Viewport units: vw, vh, vmin, vmax" };
},{}],486:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "4": "G E B A" }, B: { "4": "D X g H L" }, C: { "4": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "4": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 CB", "4": "F I J C G E B A EB FB GB HB IB JB" }, F: { "2": "E", "4": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "4": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "4": "cB" }, I: { "2": "1 3 F dB eB fB gB", "4": "s hB iB" }, J: { "2": "C B" }, K: { "4": "5 6 B A D K y" }, L: { "4": "8" }, M: { "4": "t" }, N: { "4": "B A" }, O: { "2": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 2, C: "WAI-ARIA Accessibility features" };
},{}],487:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "578": "H L" }, C: { "1": "0 2 4 t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p PB OB", "194": "q r w x v", "1025": "z" }, D: { "1": "4 8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x", "322": "0 2 v z t s" }, E: { "1": "A JB", "2": "7 F I J C G E B CB EB FB GB HB IB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K KB LB MB NB QB y", "322": "h i j k l m" }, G: { "1": "A", "2": "3 7 9 G UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "322": "kB" }, R: { "2": "lB" } }, B: 6, C: "WebAssembly" };
},{}],488:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "1 RB" }, D: { "1": "0 2 4 8 G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r MB NB QB y", "2": "E KB LB" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "16": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "Wav audio format" };
},{}],489:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C TB", "2": "G E B A" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A EB FB GB HB IB JB", "16": "CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "16": "E" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "16": "3 7 9" }, H: { "1": "cB" }, I: { "1": "1 3 F s fB gB hB iB", "16": "dB eB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "wbr (word break opportunity) element" };
},{}],490:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b PB OB", "516": "0 2 4 q r w x v z t s", "580": "c d e f K h i j k l m n o p" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e", "132": "f K h", "260": "0 2 4 8 i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R KB LB MB NB QB y", "132": "S T U", "260": "V W u Y Z a b c d e f K h i j k l m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "260": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "260": "K" }, L: { "260": "8" }, M: { "516": "t" }, N: { "2": "B A" }, O: { "260": "jB" }, P: { "260": "F I" }, Q: { "260": "kB" }, R: { "260": "lB" } }, B: 5, C: "Web Animations API" };
},{}],491:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "Web App Manifest" };
},{}],492:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n", "194": "o p q r w x v z", "706": "0 2 t", "1025": "4 8 s DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e KB LB MB NB QB y", "450": "f K h i", "706": "j k l", "1025": "m n o p q r" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB iB", "1025": "s" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1025": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "706": "kB" }, R: { "2": "lB" } }, B: 7, C: "Web Bluetooth" };
},{}],493:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "2": "0 F I J C G E B A D X g H L M U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t", "129": "2 4 8 s DB AB SB BB", "258": "N O P Q R S T" }, E: { "2": "7 F I J C G E B A CB EB GB HB IB JB", "16": "FB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F dB eB fB gB hB", "129": "s", "514": "iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "642": "8" }, M: { "514": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F", "642": "I" }, Q: { "2": "kB" }, R: { "16": "lB" } }, B: 5, C: "Web Share Api" };
},{}],494:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "TB", "8": "J C G E B", "129": "A" }, B: { "129": "D X g H L" }, C: { "1": "0 2 4 T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "129": "F I J C G E B A D X g H L M N O P Q R S" }, D: { "1": "0 2 4 8 c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C", "129": "G E B A D X g H L M N O P Q R S T U V W u Y Z a b" }, E: { "1": "G E B A HB IB JB", "2": "7 F I CB", "129": "J C EB FB GB" }, F: { "1": "O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A KB LB MB NB QB", "129": "D H L M N y" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9 UB VB WB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "1": "B", "2": "C" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B", "129": "A" }, O: { "129": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "WebGL - 3D Canvas graphics" };
},{}],495:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T PB OB", "194": "l m n", "450": "U V W u Y Z a b c d e f K h i j k", "2242": "o p q r w x" }, D: { "1": "4 8 s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l", "578": "0 2 m n o p q r w x v z t" }, E: { "2": "7 F I J C G E B CB EB FB GB HB", "1090": "A IB JB" }, F: { "1": "m n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "578": "kB" }, R: { "2": "lB" } }, B: 6, C: "WebGL 2.0" };
},{}],496:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G TB", "8": "E B A" }, B: { "4": "g H L", "8": "D X" }, C: { "1": "0 2 4 u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "4": "F I J C G E B A D X g H L M N O P Q R S T U V W" }, D: { "1": "0 2 4 8 U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I", "4": "J C G E B A D X g H L M N O P Q R S T" }, E: { "2": "CB", "8": "7 F I J C G E B A EB FB GB HB IB JB" }, F: { "1": "L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "E KB LB MB", "4": "5 6 A D H NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "1": "s", "2": "dB eB", "4": "1 3 F fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "4": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "8": "B A" }, O: { "1": "jB" }, P: { "1": "I", "4": "F" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 6, C: "WebM video format" };
},{}],497:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "2": "1 RB PB OB", "8": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I", "8": "J C G", "132": "E B A D X g H L M N O P Q R" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB MB", "8": "A NB", "132": "5 6 QB" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "3 s hB iB", "2": "1 dB eB fB", "132": "F gB" }, J: { "2": "C B" }, K: { "1": "5 6 D K y", "2": "B", "132": "A" }, L: { "1": "8" }, M: { "8": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 7, C: "WebP image format" };
},{}],498:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB PB OB", "132": "F I", "292": "J C G E B" }, D: { "1": "0 2 4 8 L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g", "260": "H" }, E: { "1": "C G E B A GB HB IB JB", "2": "7 F CB", "132": "I EB", "260": "J FB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB MB NB", "132": "5 6 A D QB" }, G: { "1": "G A VB WB XB YB ZB aB bB", "2": "7 9", "132": "3 UB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "129": "C" }, K: { "1": "K y", "2": "B", "132": "5 6 A D" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Web Sockets" };
},{}],499:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "513": "H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "194": "2 4 t s" }, D: { "2": "0 2 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "322": "4 8 DB AB SB BB" }, E: { "2": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "2": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2049": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1025": "F", "1028": "I" }, Q: { "2": "kB" }, R: { "322": "lB" } }, B: 7, C: "WebVR API" };
},{}],500:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "J C G E TB" }, B: { "1": "D X g H L" }, C: { "2": "1 RB F I J C G E B A D X g H L M N O P Q R S PB OB", "66": "T U V W u Y Z", "129": "0 2 4 a b c d e f K h i j k l m n o p q r w x v z t s" }, D: { "1": "0 2 4 8 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M" }, E: { "1": "J C G E B A FB GB HB IB JB", "2": "7 F I CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y" }, G: { "1": "G A WB XB YB ZB aB bB", "2": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 F dB eB fB gB" }, J: { "1": "B", "2": "C" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "A", "2": "B" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "WebVTT - Web Video Text Tracks" };
},{}],501:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "2": "TB", "8": "J C G E" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "8": "1 RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "8": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r NB QB y", "2": "E KB", "8": "LB MB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s dB hB iB", "2": "1 3 F eB fB gB" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "8": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Web Workers" };
},{}],502:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g H L" }, C: { "1": "0 2 4 f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u PB OB", "194": "Y Z a b c d e" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "1": "B A HB IB JB", "2": "7 F I J C G E CB EB FB GB" }, F: { "1": "T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R S KB LB MB NB QB y" }, G: { "1": "A ZB aB bB", "2": "3 7 9 G UB VB WB XB YB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS will-change property" };
},{}],503:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s OB", "2": "1 RB PB" }, D: { "1": "0 2 4 8 I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F" }, E: { "1": "J C G E B A EB FB GB HB IB JB", "2": "7 F I CB" }, F: { "1": "5 6 D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "2": "E A KB LB MB NB" }, G: { "1": "G A UB VB WB XB YB ZB aB bB", "2": "3 7 9" }, H: { "2": "cB" }, I: { "1": "s hB iB", "2": "1 3 dB eB fB gB", "130": "F" }, J: { "1": "C B" }, K: { "1": "5 6 A D K y", "2": "B" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 2, C: "WOFF - Web Open Font Format" };
},{}],504:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "1": "g H L", "2": "D X" }, C: { "1": "0 2 4 i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h PB OB" }, D: { "1": "0 2 4 8 f K h i j k l m n o p q r w x v z t s DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e" }, E: { "2": "7 F I J C G E CB EB FB GB HB", "132": "B A IB JB" }, F: { "1": "S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D H L M N O P Q R KB LB MB NB QB y" }, G: { "1": "A aB bB", "2": "3 7 9 G UB VB WB XB YB ZB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 3 F dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "1": "K", "2": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "WOFF 2.0 - Web Open Font Format" };
},{}],505:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "J C G E B A TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB F I J C G E B A D X g PB OB" }, D: { "1": "0 2 4 8 n o p q r w x v z t s DB AB SB BB", "4": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m" }, E: { "1": "E B A HB IB JB", "4": "7 F I J C G CB EB FB GB" }, F: { "1": "a b c d e f K h i j k l m n o p q r", "2": "5 6 E A D KB LB MB NB QB y", "4": "H L M N O P Q R S T U V W u Y Z" }, G: { "1": "A YB ZB aB bB", "4": "3 7 9 G UB VB WB XB" }, H: { "2": "cB" }, I: { "1": "s", "4": "1 3 F dB eB fB gB hB iB" }, J: { "4": "C B" }, K: { "2": "5 6 B A D y", "4": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "4": "jB" }, P: { "1": "F I" }, Q: { "4": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 word-break" };
},{}],506:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "4": "J C G E B A TB" }, B: { "4": "D X g H L" }, C: { "1": "0 2 4 w x v z t s", "2": "1 RB", "4": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r PB OB" }, D: { "1": "0 2 4 8 S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "4": "F I J C G E B A D X g H L M N O P Q R" }, E: { "1": "C G E B A FB GB HB IB JB", "4": "7 F I J CB EB" }, F: { "1": "H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "E KB LB", "4": "5 6 A D MB NB QB" }, G: { "1": "G A WB XB YB ZB aB bB", "4": "3 7 9 UB VB" }, H: { "4": "cB" }, I: { "1": "s hB iB", "4": "1 3 F dB eB fB gB" }, J: { "1": "B", "4": "C" }, K: { "1": "K", "4": "5 6 B A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "4": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 5, C: "CSS3 Overflow-wrap" };
},{}],507:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C TB", "132": "G E", "260": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB", "2": "RB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "F I J C G E B A EB FB GB HB IB JB", "2": "7 CB" }, F: { "1": "5 6 A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y", "2": "E" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "4": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "Cross-document messaging" };
},{}],508:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "G E B A", "2": "J C TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "4": "F I J C G E B A D X g H L M", "16": "1 RB PB OB" }, D: { "4": "0 2 4 8 V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J C G E B A D X g H L M N O P Q R S T U" }, E: { "4": "J C G E B A EB FB GB HB IB JB", "16": "7 F I CB" }, F: { "4": "D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r QB y", "16": "5 6 E A KB LB MB NB" }, G: { "4": "G A WB XB YB ZB aB bB", "16": "3 7 9 UB VB" }, H: { "2": "cB" }, I: { "4": "3 F s gB hB iB", "16": "1 dB eB fB" }, J: { "4": "C B" }, K: { "4": "K y", "16": "5 6 B A D" }, L: { "4": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "4": "jB" }, P: { "4": "F I" }, Q: { "4": "kB" }, R: { "4": "lB" } }, B: 6, C: "X-Frame-Options HTTP header" };
},{}],509:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "J C G E TB", "132": "B A" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "2": "1 RB", "260": "B A", "388": "J C G E", "900": "F I PB OB" }, D: { "1": "0 2 4 8 a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "16": "F I J", "132": "Y Z", "388": "C G E B A D X g H L M N O P Q R S T U V W u" }, E: { "1": "G E B A GB HB IB JB", "2": "7 F CB", "132": "C FB", "388": "I J EB" }, F: { "1": "D N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r y", "2": "5 6 E A KB LB MB NB QB", "132": "H L M" }, G: { "1": "G A XB YB ZB aB bB", "2": "3 7 9", "132": "WB", "388": "UB VB" }, H: { "2": "cB" }, I: { "1": "s iB", "2": "dB eB fB", "388": "hB", "900": "1 3 F gB" }, J: { "132": "B", "388": "C" }, K: { "1": "D K y", "2": "5 6 B A" }, L: { "1": "8" }, M: { "1": "t" }, N: { "132": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 1, C: "XMLHttpRequest advanced features" };
},{}],510:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "E B A", "2": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "1": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "1": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "1": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "1": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "1": "cB" }, I: { "1": "1 3 F s dB eB fB gB hB iB" }, J: { "1": "C B" }, K: { "1": "5 6 B A D K y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "2": "lB" } }, B: 1, C: "XHTML served as application/xhtml+xml" };
},{}],511:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "2": "E B A TB", "4": "J C G" }, B: { "2": "D X g H L" }, C: { "8": "0 1 2 4 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s PB OB" }, D: { "8": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB" }, E: { "8": "7 F I J C G E B A CB EB FB GB HB IB JB" }, F: { "8": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r KB LB MB NB QB y" }, G: { "8": "3 7 9 G A UB VB WB XB YB ZB aB bB" }, H: { "8": "cB" }, I: { "8": "1 3 F s dB eB fB gB hB iB" }, J: { "8": "C B" }, K: { "8": "5 6 B A D K y" }, L: { "8": "8" }, M: { "8": "t" }, N: { "2": "B A" }, O: { "8": "jB" }, P: { "8": "F I" }, Q: { "8": "kB" }, R: { "8": "lB" } }, B: 7, C: "XHTML+SMIL animation" };
},{}],512:[function(require,module,exports){
"use strict";
module.exports = { A: { A: { "1": "B A", "132": "E", "260": "J C G TB" }, B: { "1": "D X g H L" }, C: { "1": "0 2 4 D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "132": "A", "260": "1 RB F I J C PB OB", "516": "G E B" }, D: { "1": "0 2 4 8 Z a b c d e f K h i j k l m n o p q r w x v z t s DB AB SB BB", "132": "F I J C G E B A D X g H L M N O P Q R S T U V W u Y" }, E: { "1": "G E B A GB HB IB JB", "132": "7 F I J C CB EB FB" }, F: { "1": "M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r", "16": "E KB", "132": "5 6 A D H L LB MB NB QB y" }, G: { "1": "G A XB YB ZB aB bB", "132": "3 7 9 UB VB WB" }, H: { "132": "cB" }, I: { "1": "s hB iB", "132": "1 3 F dB eB fB gB" }, J: { "132": "C B" }, K: { "1": "K", "16": "B", "132": "5 6 A D y" }, L: { "1": "8" }, M: { "1": "t" }, N: { "1": "B A" }, O: { "1": "jB" }, P: { "1": "F I" }, Q: { "1": "kB" }, R: { "1": "lB" } }, B: 4, C: "DOM Parsing and Serialization" };
},{}],513:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var browsers = require('../../data/browsers');
var browserVersions = require('../../data/browserVersions');
var agentsData = require('../../data/agents');
function unpackBrowserVersions(versionsData) {
return Object.keys(versionsData).reduce(function (usage, version) {
usage[browserVersions[version]] = versionsData[version];
return usage;
}, {});
}
var agents = Object.keys(agentsData).reduce(function (map, key) {
var versionsData = agentsData[key];
map[browsers[key]] = Object.keys(versionsData).reduce(function (data, entry) {
if (entry === 'A') {
data.usage_global = unpackBrowserVersions(versionsData[entry]);
} else if (entry === 'C') {
data.versions = versionsData[entry].reduce(function (list, version) {
if (version === '') {
list.push(null);
} else {
list.push(browserVersions[version]);
}
return list;
}, []);
} else if (entry === 'D') {
data.prefix_exceptions = unpackBrowserVersions(versionsData[entry]);
} else if (entry === 'E') {
data.browser = versionsData[entry];
} else {
data.prefix = versionsData[entry];
}
return data;
}, {});
return map;
}, {});
var statuses = {
1: "ls",
2: "rec",
3: "pr",
4: "cr",
5: "wd",
6: "other",
7: "unoff"
};
var supported = {
y: 1 << 0,
n: 1 << 1,
a: 1 << 2,
p: 1 << 3,
u: 1 << 4,
x: 1 << 5,
d: 1 << 6
};
function unpackSupport(cipher) {
var stats = Object.keys(supported).reduce(function (list, support) {
if (cipher & supported[support]) {
list.push(support);
}
return list;
}, []);
var notes = cipher >> 7;
var notesArray = [];
while (notes) {
var note = Math.floor(Math.log2(notes)) + 1;
notesArray.unshift("#" + note);
notes -= Math.pow(2, note - 1);
}
return stats.concat(notesArray).join(' ');
}
function unpackFeature(packed) {
var unpacked = { status: statuses[packed.B], title: packed.C };
unpacked.stats = Object.keys(packed.A).reduce(function (browserStats, key) {
var browser = packed.A[key];
browserStats[browsers[key]] = Object.keys(browser).reduce(function (stats, support) {
var packedVersions = browser[support].split(' ');
var unpacked = unpackSupport(support);
packedVersions.forEach(function (v) {
return stats[browserVersions[v]] = unpacked;
});
return stats;
}, {});
return browserStats;
}, {});
return unpacked;
}
var features = require('../../data/features');
function unpackRegion(packed) {
return Object.keys(packed).reduce(function (list, browser) {
var data = packed[browser];
list[browsers[browser]] = Object.keys(data).reduce(function (memo, key) {
var stats = data[key];
if (key === '_') {
stats.split(' ').forEach(function (version) {
return memo[version] = null;
});
} else {
memo[key] = stats;
}
return memo;
}, {});
return list;
}, {});
}
exports.agents = agents;
exports.feature = unpackFeature;
exports.features = features;
exports.region = unpackRegion;
},{"../../data/agents":67,"../../data/browserVersions":68,"../../data/browsers":69,"../../data/features":70}],514:[function(require,module,exports){
'use strict';
/* MIT license */
var cssKeywords = require('color-name');
// NOTE: conversions should only return primitive values (i.e. arrays, or
// values that give correct `typeof` results).
// do not use box values types (i.e. Number(), String(), etc.)
var reverseKeywords = {};
for (var key in cssKeywords) {
if (cssKeywords.hasOwnProperty(key)) {
reverseKeywords[cssKeywords[key]] = key;
}
}
var convert = module.exports = {
rgb: { channels: 3, labels: 'rgb' },
hsl: { channels: 3, labels: 'hsl' },
hsv: { channels: 3, labels: 'hsv' },
hwb: { channels: 3, labels: 'hwb' },
cmyk: { channels: 4, labels: 'cmyk' },
xyz: { channels: 3, labels: 'xyz' },
lab: { channels: 3, labels: 'lab' },
lch: { channels: 3, labels: 'lch' },
hex: { channels: 1, labels: ['hex'] },
keyword: { channels: 1, labels: ['keyword'] },
ansi16: { channels: 1, labels: ['ansi16'] },
ansi256: { channels: 1, labels: ['ansi256'] },
hcg: { channels: 3, labels: ['h', 'c', 'g'] },
apple: { channels: 3, labels: ['r16', 'g16', 'b16'] },
gray: { channels: 1, labels: ['gray'] }
};
// hide .channels and .labels properties
for (var model in convert) {
if (convert.hasOwnProperty(model)) {
if (!('channels' in convert[model])) {
throw new Error('missing channels property: ' + model);
}
if (!('labels' in convert[model])) {
throw new Error('missing channel labels property: ' + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error('channel and label counts mismatch: ' + model);
}
var channels = convert[model].channels;
var labels = convert[model].labels;
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], 'channels', { value: channels });
Object.defineProperty(convert[model], 'labels', { value: labels });
}
}
convert.rgb.hsl = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var min = Math.min(r, g, b);
var max = Math.max(r, g, b);
var delta = max - min;
var h;
var s;
var l;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function (rgb) {
var r = rgb[0];
var g = rgb[1];
var b = rgb[2];
var min = Math.min(r, g, b);
var max = Math.max(r, g, b);
var delta = max - min;
var h;
var s;
var v;
if (max === 0) {
s = 0;
} else {
s = delta / max * 1000 / 10;
}
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
v = max / 255 * 1000 / 10;
return [h, s, v];
};
convert.rgb.hwb = function (rgb) {
var r = rgb[0];
var g = rgb[1];
var b = rgb[2];
var h = convert.rgb.hsl(rgb)[0];
var w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var c;
var m;
var y;
var k;
k = Math.min(1 - r, 1 - g, 1 - b);
c = (1 - r - k) / (1 - k) || 0;
m = (1 - g - k) / (1 - k) || 0;
y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
/**
* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
* */
function comparativeDistance(x, y) {
return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
}
convert.rgb.keyword = function (rgb) {
var reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
var currentClosestDistance = Infinity;
var currentClosestKeyword;
for (var keyword in cssKeywords) {
if (cssKeywords.hasOwnProperty(keyword)) {
var value = cssKeywords[keyword];
// Compute comparative distance
var distance = comparativeDistance(rgb, value);
// Check if its less, if so set as closest
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function (keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
// assume sRGB
r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function (rgb) {
var xyz = convert.rgb.xyz(rgb);
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var l;
var a;
var b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
l = 116 * y - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function (hsl) {
var h = hsl[0] / 360;
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var t1;
var t2;
var t3;
var rgb;
var val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
t1 = 2 * l - t2;
rgb = [0, 0, 0];
for (var i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function (hsl) {
var h = hsl[0];
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var smin = s;
var lmin = Math.max(l, 0.01);
var sv;
var v;
l *= 2;
s *= l <= 1 ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
v = (l + s) / 2;
sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function (hsv) {
var h = hsv[0] / 60;
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var hi = Math.floor(h) % 6;
var f = h - Math.floor(h);
var p = 255 * v * (1 - s);
var q = 255 * v * (1 - s * f);
var t = 255 * v * (1 - s * (1 - f));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function (hsv) {
var h = hsv[0];
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var vmin = Math.max(v, 0.01);
var lmin;
var sl;
var l;
l = (2 - s) * v;
lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= lmin <= 1 ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
convert.hwb.rgb = function (hwb) {
var h = hwb[0] / 360;
var wh = hwb[1] / 100;
var bl = hwb[2] / 100;
var ratio = wh + bl;
var i;
var v;
var f;
var n;
// wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
i = Math.floor(6 * h);
v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) !== 0) {
f = 1 - f;
}
n = wh + f * (v - wh); // linear interpolation
var r;
var g;
var b;
switch (i) {
default:
case 6:
case 0:
r = v;g = n;b = wh;break;
case 1:
r = n;g = v;b = wh;break;
case 2:
r = wh;g = v;b = n;break;
case 3:
r = wh;g = n;b = v;break;
case 4:
r = n;g = wh;b = v;break;
case 5:
r = v;g = wh;b = n;break;
}
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function (cmyk) {
var c = cmyk[0] / 100;
var m = cmyk[1] / 100;
var y = cmyk[2] / 100;
var k = cmyk[3] / 100;
var r;
var g;
var b;
r = 1 - Math.min(1, c * (1 - k) + k);
g = 1 - Math.min(1, m * (1 - k) + k);
b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function (xyz) {
var x = xyz[0] / 100;
var y = xyz[1] / 100;
var z = xyz[2] / 100;
var r;
var g;
var b;
r = x * 3.2406 + y * -1.5372 + z * -0.4986;
g = x * -0.9689 + y * 1.8758 + z * 0.0415;
b = x * 0.0557 + y * -0.2040 + z * 1.0570;
// assume sRGB
r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function (xyz) {
var x = xyz[0];
var y = xyz[1];
var z = xyz[2];
var l;
var a;
var b;
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
l = 116 * y - 16;
a = 500 * (x - y);
b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function (lab) {
var l = lab[0];
var a = lab[1];
var b = lab[2];
var x;
var y;
var z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
var y2 = Math.pow(y, 3);
var x2 = Math.pow(x, 3);
var z2 = Math.pow(z, 3);
y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function (lab) {
var l = lab[0];
var a = lab[1];
var b = lab[2];
var hr;
var h;
var c;
hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function (lch) {
var l = lch[0];
var c = lch[1];
var h = lch[2];
var a;
var b;
var hr;
hr = h / 360 * 2 * Math.PI;
a = c * Math.cos(hr);
b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function (args) {
var r = args[0];
var g = args[1];
var b = args[2];
var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function (args) {
// optimization here; we already know the value and don't need to get
// it converted for us.
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function (args) {
var r = args[0];
var g = args[1];
var b = args[2];
// we use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round((r - 8) / 247 * 24) + 232;
}
var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function (args) {
var color = args % 10;
// handle greyscale
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
var mult = (~~(args > 50) + 1) * 0.5;
var r = (color & 1) * mult * 255;
var g = (color >> 1 & 1) * mult * 255;
var b = (color >> 2 & 1) * mult * 255;
return [r, g, b];
};
convert.ansi256.rgb = function (args) {
// handle greyscale
if (args >= 232) {
var c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
var rem;
var r = Math.floor(args / 36) / 5 * 255;
var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
var b = rem % 6 / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function (args) {
var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
var string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.hex.rgb = function (args) {
var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
var colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split('').map(function (char) {
return char + char;
}).join('');
}
var integer = parseInt(colorString, 16);
var r = integer >> 16 & 0xFF;
var g = integer >> 8 & 0xFF;
var b = integer & 0xFF;
return [r, g, b];
};
convert.rgb.hcg = function (rgb) {
var r = rgb[0] / 255;
var g = rgb[1] / 255;
var b = rgb[2] / 255;
var max = Math.max(Math.max(r, g), b);
var min = Math.min(Math.min(r, g), b);
var chroma = max - min;
var grayscale;
var hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else if (max === r) {
hue = (g - b) / chroma % 6;
} else if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma + 4;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function (hsl) {
var s = hsl[1] / 100;
var l = hsl[2] / 100;
var c = 1;
var f = 0;
if (l < 0.5) {
c = 2.0 * s * l;
} else {
c = 2.0 * s * (1.0 - l);
}
if (c < 1.0) {
f = (l - 0.5 * c) / (1.0 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function (hsv) {
var s = hsv[1] / 100;
var v = hsv[2] / 100;
var c = s * v;
var f = 0;
if (c < 1.0) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function (hcg) {
var h = hcg[0] / 360;
var c = hcg[1] / 100;
var g = hcg[2] / 100;
if (c === 0.0) {
return [g * 255, g * 255, g * 255];
}
var pure = [0, 0, 0];
var hi = h % 1 * 6;
var v = hi % 1;
var w = 1 - v;
var mg = 0;
switch (Math.floor(hi)) {
case 0:
pure[0] = 1;pure[1] = v;pure[2] = 0;break;
case 1:
pure[0] = w;pure[1] = 1;pure[2] = 0;break;
case 2:
pure[0] = 0;pure[1] = 1;pure[2] = v;break;
case 3:
pure[0] = 0;pure[1] = w;pure[2] = 1;break;
case 4:
pure[0] = v;pure[1] = 0;pure[2] = 1;break;
default:
pure[0] = 1;pure[1] = 0;pure[2] = w;
}
mg = (1.0 - c) * g;
return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
};
convert.hcg.hsv = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var v = c + g * (1.0 - c);
var f = 0;
if (v > 0.0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var l = g * (1.0 - c) + 0.5 * c;
var s = 0;
if (l > 0.0 && l < 0.5) {
s = c / (2 * l);
} else if (l >= 0.5 && l < 1.0) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function (hcg) {
var c = hcg[1] / 100;
var g = hcg[2] / 100;
var v = c + g * (1.0 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function (hwb) {
var w = hwb[1] / 100;
var b = hwb[2] / 100;
var v = 1 - b;
var c = v - w;
var g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function (apple) {
return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
};
convert.rgb.apple = function (rgb) {
return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
};
convert.gray.rgb = function (args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = convert.gray.hsv = function (args) {
return [0, 0, args[0]];
};
convert.gray.hwb = function (gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function (gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function (gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function (gray) {
var val = Math.round(gray[0] / 100 * 255) & 0xFF;
var integer = (val << 16) + (val << 8) + val;
var string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.rgb.gray = function (rgb) {
var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};
},{"color-name":517}],515:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var conversions = require('./conversions');
var route = require('./route');
var convert = {};
var models = Object.keys(conversions);
function wrapRaw(fn) {
var wrappedFn = function wrappedFn(args) {
if (args === undefined || args === null) {
return args;
}
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments);
}
return fn(args);
};
// preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
var wrappedFn = function wrappedFn(args) {
if (args === undefined || args === null) {
return args;
}
if (arguments.length > 1) {
args = Array.prototype.slice.call(arguments);
}
var result = fn(args);
// we're assuming the result is an array here.
// see notice in conversions.js; don't use box types
// in conversion functions.
if ((typeof result === 'undefined' ? 'undefined' : _typeof(result)) === 'object') {
for (var len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
// preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach(function (fromModel) {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], 'channels', { value: conversions[fromModel].channels });
Object.defineProperty(convert[fromModel], 'labels', { value: conversions[fromModel].labels });
var routes = route(fromModel);
var routeModels = Object.keys(routes);
routeModels.forEach(function (toModel) {
var fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
module.exports = convert;
},{"./conversions":514,"./route":516}],516:[function(require,module,exports){
'use strict';
var conversions = require('./conversions');
/*
this function routes a model to all other models.
all functions that are routed have a property `.conversion` attached
to the returned synthetic function. This property is an array
of strings, each with the steps in between the 'from' and 'to'
color models (inclusive).
conversions that are not possible simply are not included.
*/
// https://jsperf.com/object-keys-vs-for-in-with-closure/3
var models = Object.keys(conversions);
function buildGraph() {
var graph = {};
for (var len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
// https://en.wikipedia.org/wiki/Breadth-first_search
function deriveBFS(fromModel) {
var graph = buildGraph();
var queue = [fromModel]; // unshift -> queue -> pop
graph[fromModel].distance = 0;
while (queue.length) {
var current = queue.pop();
var adjacents = Object.keys(conversions[current]);
for (var len = adjacents.length, i = 0; i < len; i++) {
var adjacent = adjacents[i];
var node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current].distance + 1;
node.parent = current;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function (args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
var path = [graph[toModel].parent, toModel];
var fn = conversions[graph[toModel].parent][toModel];
var cur = graph[toModel].parent;
while (graph[cur].parent) {
path.unshift(graph[cur].parent);
fn = link(conversions[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path;
return fn;
}
module.exports = function (fromModel) {
var graph = deriveBFS(fromModel);
var conversion = {};
var models = Object.keys(graph);
for (var len = models.length, i = 0; i < len; i++) {
var toModel = models[i];
var node = graph[toModel];
if (node.parent === null) {
// no possible conversion, or this node is the source model.
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};
},{"./conversions":514}],517:[function(require,module,exports){
"use strict";
module.exports = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
},{}],518:[function(require,module,exports){
"use strict";
module.exports = {
"1.7": "58",
"1.6": "56",
"1.3": "52",
"1.4": "53",
"1.5": "54",
"1.2": "51",
"1.1": "50",
"1.0": "49",
"0.37": "49",
"0.36": "47",
"0.35": "45",
"0.34": "45",
"0.33": "45",
"0.32": "45",
"0.31": "44",
"0.30": "44",
"0.29": "43",
"0.28": "43",
"0.27": "42",
"0.26": "42",
"0.25": "42",
"0.24": "41",
"0.23": "41",
"0.22": "41",
"0.21": "40",
"0.20": "39"
};
},{}],519:[function(require,module,exports){
'use strict';
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};
},{}],520:[function(require,module,exports){
"use strict";
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & (1 << -nBits) - 1;
s >>= -nBits;
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : (s ? -1 : 1) * Infinity;
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128;
};
},{}],521:[function(require,module,exports){
'use strict';
module.exports = {
wrap: wrapRange,
limit: limitRange,
validate: validateRange,
test: testRange,
curry: curry,
name: name
};
function wrapRange(min, max, value) {
var maxLessMin = max - min;
return ((value - min) % maxLessMin + maxLessMin) % maxLessMin + min;
}
function limitRange(min, max, value) {
return Math.max(min, Math.min(max, value));
}
function validateRange(min, max, value, minExclusive, maxExclusive) {
if (!testRange(min, max, value, minExclusive, maxExclusive)) {
throw new Error(value + ' is outside of range [' + min + ',' + max + ')');
}
return value;
}
function testRange(min, max, value, minExclusive, maxExclusive) {
return !(value < min || value > max || maxExclusive && value === max || minExclusive && value === min);
}
function name(min, max, minExcl, maxExcl) {
return (minExcl ? '(' : '[') + min + ',' + max + (maxExcl ? ')' : ']');
}
function curry(min, max, minExclusive, maxExclusive) {
var boundNameFn = name.bind(null, min, max, minExclusive, maxExclusive);
return {
wrap: wrapRange.bind(null, min, max),
limit: limitRange.bind(null, min, max),
validate: function validate(value) {
return validateRange(min, max, value, minExclusive, maxExclusive);
},
test: function test(value) {
return testRange(min, max, value, minExclusive, maxExclusive);
},
toString: boundNameFn,
name: boundNameFn
};
}
},{}],522:[function(require,module,exports){
'use strict';
var abs = Math.abs;
var round = Math.round;
function almostEq(a, b) {
return abs(a - b) <= 9.5367432e-7;
}
//最大公约数 Greatest Common Divisor
function GCD(a, b) {
if (almostEq(b, 0)) return a;
return GCD(b, a % b);
}
function findPrecision(n) {
var e = 1;
while (!almostEq(round(n * e) / e, n)) {
e *= 10;
}
return e;
}
function num2fraction(num) {
if (num === 0 || num === '0') return '0';
if (typeof num === 'string') {
num = parseFloat(num);
}
var precision = findPrecision(num); //精确度
var number = num * precision;
var gcd = abs(GCD(number, precision));
//分子
var numerator = number / gcd;
//分母
var denominator = precision / gcd;
//分数
return round(numerator) + '/' + round(denominator);
}
module.exports = num2fraction;
},{}],523:[function(require,module,exports){
(function (process){
'use strict';
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function splitPath(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function () {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = i >= 0 ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function (p) {
return !!p;
}), !resolvedAbsolute).join('/');
return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function (path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function (p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function (path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function () {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function (p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function (from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function (path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function (path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function (path) {
return splitPath(path)[3];
};
function filter(xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) {
return str.substr(start, len);
} : function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
};
}).call(this,require('_process'))
},{"_process":557}],524:[function(require,module,exports){
'use strict';
var parse = require('./parse');
var walk = require('./walk');
var stringify = require('./stringify');
function ValueParser(value) {
if (this instanceof ValueParser) {
this.nodes = parse(value);
return this;
}
return new ValueParser(value);
}
ValueParser.prototype.toString = function () {
return Array.isArray(this.nodes) ? stringify(this.nodes) : '';
};
ValueParser.prototype.walk = function (cb, bubble) {
walk(this.nodes, cb, bubble);
return this;
};
ValueParser.unit = require('./unit');
ValueParser.walk = walk;
ValueParser.stringify = stringify;
module.exports = ValueParser;
},{"./parse":525,"./stringify":526,"./unit":527,"./walk":528}],525:[function(require,module,exports){
'use strict';
var openParentheses = '('.charCodeAt(0);
var closeParentheses = ')'.charCodeAt(0);
var singleQuote = '\''.charCodeAt(0);
var doubleQuote = '"'.charCodeAt(0);
var backslash = '\\'.charCodeAt(0);
var slash = '/'.charCodeAt(0);
var comma = ','.charCodeAt(0);
var colon = ':'.charCodeAt(0);
var star = '*'.charCodeAt(0);
module.exports = function (input) {
var tokens = [];
var value = input;
var next, quote, prev, token, escape, escapePos, whitespacePos;
var pos = 0;
var code = value.charCodeAt(pos);
var max = value.length;
var stack = [{ nodes: tokens }];
var balanced = 0;
var parent;
var name = '';
var before = '';
var after = '';
while (pos < max) {
// Whitespaces
if (code <= 32) {
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = value.slice(pos, next);
prev = tokens[tokens.length - 1];
if (code === closeParentheses && balanced) {
after = token;
} else if (prev && prev.type === 'div') {
prev.after = token;
} else if (code === comma || code === colon || code === slash && value.charCodeAt(next + 1) !== star) {
before = token;
} else {
tokens.push({
type: 'space',
sourceIndex: pos,
value: token
});
}
pos = next;
// Quotes
} else if (code === singleQuote || code === doubleQuote) {
next = pos;
quote = code === singleQuote ? '\'' : '"';
token = {
type: 'string',
sourceIndex: pos,
quote: quote
};
do {
escape = false;
next = value.indexOf(quote, next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += quote;
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
token.value = value.slice(pos + 1, next);
tokens.push(token);
pos = next + 1;
code = value.charCodeAt(pos);
// Comments
} else if (code === slash && value.charCodeAt(pos + 1) === star) {
token = {
type: 'comment',
sourceIndex: pos
};
next = value.indexOf('*/', pos);
if (next === -1) {
token.unclosed = true;
next = value.length;
}
token.value = value.slice(pos + 2, next);
tokens.push(token);
pos = next + 2;
code = value.charCodeAt(pos);
// Dividers
} else if (code === slash || code === comma || code === colon) {
token = value[pos];
tokens.push({
type: 'div',
sourceIndex: pos - before.length,
value: token,
before: before,
after: ''
});
before = '';
pos += 1;
code = value.charCodeAt(pos);
// Open parentheses
} else if (openParentheses === code) {
// Whitespaces after open parentheses
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = {
type: 'function',
sourceIndex: pos - name.length,
value: name,
before: value.slice(pos + 1, next)
};
pos = next;
if (name === 'url' && code !== singleQuote && code !== doubleQuote) {
next -= 1;
do {
escape = false;
next = value.indexOf(')', next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += ')';
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
// Whitespaces before closed
whitespacePos = next;
do {
whitespacePos -= 1;
code = value.charCodeAt(whitespacePos);
} while (code <= 32);
if (pos !== whitespacePos + 1) {
token.nodes = [{
type: 'word',
sourceIndex: pos,
value: value.slice(pos, whitespacePos + 1)
}];
} else {
token.nodes = [];
}
if (token.unclosed && whitespacePos + 1 !== next) {
token.after = '';
token.nodes.push({
type: 'space',
sourceIndex: whitespacePos + 1,
value: value.slice(whitespacePos + 1, next)
});
} else {
token.after = value.slice(whitespacePos + 1, next);
}
pos = next + 1;
code = value.charCodeAt(pos);
tokens.push(token);
} else {
balanced += 1;
token.after = '';
tokens.push(token);
stack.push(token);
tokens = token.nodes = [];
parent = token;
}
name = '';
// Close parentheses
} else if (closeParentheses === code && balanced) {
pos += 1;
code = value.charCodeAt(pos);
parent.after = after;
after = '';
balanced -= 1;
stack.pop();
parent = stack[balanced];
tokens = parent.nodes;
// Words
} else {
next = pos;
do {
if (code === backslash) {
next += 1;
}
next += 1;
code = value.charCodeAt(next);
} while (next < max && !(code <= 32 || code === singleQuote || code === doubleQuote || code === comma || code === colon || code === slash || code === openParentheses || code === closeParentheses && balanced));
token = value.slice(pos, next);
if (openParentheses === code) {
name = token;
} else {
tokens.push({
type: 'word',
sourceIndex: pos,
value: token
});
}
pos = next;
}
}
for (pos = stack.length - 1; pos; pos -= 1) {
stack[pos].unclosed = true;
}
return stack[0].nodes;
};
},{}],526:[function(require,module,exports){
'use strict';
function stringifyNode(node, custom) {
var type = node.type;
var value = node.value;
var buf;
var customResult;
if (custom && (customResult = custom(node)) !== undefined) {
return customResult;
} else if (type === 'word' || type === 'space') {
return value;
} else if (type === 'string') {
buf = node.quote || '';
return buf + value + (node.unclosed ? '' : buf);
} else if (type === 'comment') {
return '/*' + value + (node.unclosed ? '' : '*/');
} else if (type === 'div') {
return (node.before || '') + value + (node.after || '');
} else if (Array.isArray(node.nodes)) {
buf = stringify(node.nodes);
if (type !== 'function') {
return buf;
}
return value + '(' + (node.before || '') + buf + (node.after || '') + (node.unclosed ? '' : ')');
}
return value;
}
function stringify(nodes, custom) {
var result, i;
if (Array.isArray(nodes)) {
result = '';
for (i = nodes.length - 1; ~i; i -= 1) {
result = stringifyNode(nodes[i], custom) + result;
}
return result;
}
return stringifyNode(nodes, custom);
}
module.exports = stringify;
},{}],527:[function(require,module,exports){
'use strict';
var minus = '-'.charCodeAt(0);
var plus = '+'.charCodeAt(0);
var dot = '.'.charCodeAt(0);
module.exports = function (value) {
var pos = 0;
var length = value.length;
var dotted = false;
var containsNumber = false;
var code;
var number = '';
while (pos < length) {
code = value.charCodeAt(pos);
if (code >= 48 && code <= 57) {
number += value[pos];
containsNumber = true;
} else if (code === dot) {
if (dotted) {
break;
}
dotted = true;
number += value[pos];
} else if (code === plus || code === minus) {
if (pos !== 0) {
break;
}
number += value[pos];
} else {
break;
}
pos += 1;
}
return containsNumber ? {
number: number,
unit: value.slice(pos)
} : false;
};
},{}],528:[function(require,module,exports){
'use strict';
module.exports = function walk(nodes, cb, bubble) {
var i, max, node, result;
for (i = 0, max = nodes.length; i < max; i += 1) {
node = nodes[i];
if (!bubble) {
result = cb(node, i, nodes);
}
if (result !== false && node.type === 'function' && Array.isArray(node.nodes)) {
walk(node.nodes, cb, bubble);
}
if (bubble) {
cb(node, i, nodes);
}
}
};
},{}],529:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents an at-rule.
*
* If it’s followed in the CSS by a {} block, this node will have
* a nodes property representing its children.
*
* @extends Container
*
* @example
* const root = postcss.parse('@charset "UTF-8"; @media print {}');
*
* const charset = root.first;
* charset.type //=> 'atrule'
* charset.nodes //=> undefined
*
* const media = root.last;
* media.nodes //=> []
*/
var AtRule = function (_Container) {
_inherits(AtRule, _Container);
function AtRule(defaults) {
_classCallCheck(this, AtRule);
var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));
_this.type = 'atrule';
return _this;
}
AtRule.prototype.append = function append() {
var _Container$prototype$;
if (!this.nodes) this.nodes = [];
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
};
AtRule.prototype.prepend = function prepend() {
var _Container$prototype$2;
if (!this.nodes) this.nodes = [];
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
};
/**
* @memberof AtRule#
* @member {string} name - the at-rule’s name immediately follows the `@`
*
* @example
* const root = postcss.parse('@media print {}');
* media.name //=> 'media'
* const media = root.first;
*/
/**
* @memberof AtRule#
* @member {string} params - the at-rule’s parameters, the values
* that follow the at-rule’s name but precede
* any {} block
*
* @example
* const root = postcss.parse('@media print, screen {}');
* const media = root.first;
* media.params //=> 'print, screen'
*/
/**
* @memberof AtRule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
*
* PostCSS cleans at-rule parameters from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse(' @media\nprint {\n}')
* root.first.first.raws //=> { before: ' ',
* // between: ' ',
* // afterName: '\n',
* // after: '\n' }
*/
return AtRule;
}(_container2.default);
exports.default = AtRule;
module.exports = exports['default'];
},{"./container":531}],530:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*
* @extends Node
*/
var Comment = function (_Node) {
_inherits(Comment, _Node);
function Comment(defaults) {
_classCallCheck(this, Comment);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'comment';
return _this;
}
/**
* @memberof Comment#
* @member {string} text - the comment’s text
*/
/**
* @memberof Comment#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text.
*/
return Comment;
}(_node2.default);
exports.default = Comment;
module.exports = exports['default'];
},{"./node":538}],531:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _comment = require('./comment');
var _comment2 = _interopRequireDefault(_comment);
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function cleanSource(nodes) {
return nodes.map(function (i) {
if (i.nodes) i.nodes = cleanSource(i.nodes);
delete i.source;
return i;
});
}
/**
* The {@link Root}, {@link AtRule}, and {@link Rule} container nodes
* inherit some common methods to help work with their children.
*
* Note that all containers can store any content. If you write a rule inside
* a rule, PostCSS will parse it.
*
* @extends Node
* @abstract
*/
var Container = function (_Node) {
_inherits(Container, _Node);
function Container() {
_classCallCheck(this, Container);
return _possibleConstructorReturn(this, _Node.apply(this, arguments));
}
Container.prototype.push = function push(child) {
child.parent = this;
this.nodes.push(child);
return this;
};
/**
* Iterates through the container’s immediate children,
* calling `callback` for each child.
*
* Returning `false` in the callback will break iteration.
*
* This method only iterates through the container’s immediate children.
* If you need to recursively iterate through all the container’s descendant
* nodes, use {@link Container#walk}.
*
* Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
* if you are mutating the array of child nodes during iteration.
* PostCSS will adjust the current index to match the mutations.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const root = postcss.parse('a { color: black; z-index: 1 }');
* const rule = root.first;
*
* for ( let decl of rule.nodes ) {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Cycle will be infinite, because cloneBefore moves the current node
* // to the next index
* }
*
* rule.each(decl => {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Will be executed only for color and z-index
* });
*/
Container.prototype.each = function each(callback) {
if (!this.lastEach) this.lastEach = 0;
if (!this.indexes) this.indexes = {};
this.lastEach += 1;
var id = this.lastEach;
this.indexes[id] = 0;
if (!this.nodes) return undefined;
var index = void 0,
result = void 0;
while (this.indexes[id] < this.nodes.length) {
index = this.indexes[id];
result = callback(this.nodes[index], index);
if (result === false) break;
this.indexes[id] += 1;
}
delete this.indexes[id];
return result;
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each node.
*
* Like container.each(), this method is safe to use
* if you are mutating arrays during iteration.
*
* If you only need to iterate through the container’s immediate children,
* use {@link Container#each}.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walk(node => {
* // Traverses all descendant nodes.
* });
*/
Container.prototype.walk = function walk(callback) {
return this.each(function (child, i) {
var result = callback(child, i);
if (result !== false && child.walk) {
result = child.walk(callback);
}
return result;
});
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each declaration node.
*
* If you pass a filter, iteration will only happen over declarations
* with matching properties.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [prop] - string or regular expression
* to filter declarations by property name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkDecls(decl => {
* checkPropertySupport(decl.prop);
* });
*
* root.walkDecls('border-radius', decl => {
* decl.remove();
* });
*
* root.walkDecls(/^background/, decl => {
* decl.value = takeFirstColorFromGradient(decl.value);
* });
*/
Container.prototype.walkDecls = function walkDecls(prop, callback) {
if (!callback) {
callback = prop;
return this.walk(function (child, i) {
if (child.type === 'decl') {
return callback(child, i);
}
});
} else if (prop instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'decl' && prop.test(child.prop)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'decl' && child.prop === prop) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each rule node.
*
* If you pass a filter, iteration will only happen over rules
* with matching selectors.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [selector] - string or regular expression
* to filter rules by selector
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const selectors = [];
* root.walkRules(rule => {
* selectors.push(rule.selector);
* });
* console.log(`Your CSS uses ${selectors.length} selectors`);
*/
Container.prototype.walkRules = function walkRules(selector, callback) {
if (!callback) {
callback = selector;
return this.walk(function (child, i) {
if (child.type === 'rule') {
return callback(child, i);
}
});
} else if (selector instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'rule' && selector.test(child.selector)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'rule' && child.selector === selector) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each at-rule node.
*
* If you pass a filter, iteration will only happen over at-rules
* that have matching names.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [name] - string or regular expression
* to filter at-rules by name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkAtRules(rule => {
* if ( isOld(rule.name) ) rule.remove();
* });
*
* let first = false;
* root.walkAtRules('charset', rule => {
* if ( !first ) {
* first = true;
* } else {
* rule.remove();
* }
* });
*/
Container.prototype.walkAtRules = function walkAtRules(name, callback) {
if (!callback) {
callback = name;
return this.walk(function (child, i) {
if (child.type === 'atrule') {
return callback(child, i);
}
});
} else if (name instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'atrule' && name.test(child.name)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'atrule' && child.name === name) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each comment node.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkComments(comment => {
* comment.remove();
* });
*/
Container.prototype.walkComments = function walkComments(callback) {
return this.walk(function (child, i) {
if (child.type === 'comment') {
return callback(child, i);
}
});
};
/**
* Inserts new nodes to the end of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.append(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
Container.prototype.append = function append() {
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
for (var _iterator = children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var child = _ref;
var nodes = this.normalize(child, this.last);
for (var _iterator2 = nodes, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var node = _ref2;
this.nodes.push(node);
}
}
return this;
};
/**
* Inserts new nodes to the start of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.prepend(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
Container.prototype.prepend = function prepend() {
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
children = children.reverse();
for (var _iterator3 = children, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var child = _ref3;
var nodes = this.normalize(child, this.first, 'prepend').reverse();
for (var _iterator4 = nodes, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var node = _ref4;
this.nodes.unshift(node);
}for (var id in this.indexes) {
this.indexes[id] = this.indexes[id] + nodes.length;
}
}
return this;
};
Container.prototype.cleanRaws = function cleanRaws(keepBetween) {
_Node.prototype.cleanRaws.call(this, keepBetween);
if (this.nodes) {
for (var _iterator5 = this.nodes, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) {
var _ref5;
if (_isArray5) {
if (_i5 >= _iterator5.length) break;
_ref5 = _iterator5[_i5++];
} else {
_i5 = _iterator5.next();
if (_i5.done) break;
_ref5 = _i5.value;
}
var node = _ref5;
node.cleanRaws(keepBetween);
}
}
};
/**
* Insert new node before old node within the container.
*
* @param {Node|number} exist - child or child’s index.
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*
* @example
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
*/
Container.prototype.insertBefore = function insertBefore(exist, add) {
exist = this.index(exist);
var type = exist === 0 ? 'prepend' : false;
var nodes = this.normalize(add, this.nodes[exist], type).reverse();
for (var _iterator6 = nodes, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : _iterator6[Symbol.iterator]();;) {
var _ref6;
if (_isArray6) {
if (_i6 >= _iterator6.length) break;
_ref6 = _iterator6[_i6++];
} else {
_i6 = _iterator6.next();
if (_i6.done) break;
_ref6 = _i6.value;
}
var node = _ref6;
this.nodes.splice(exist, 0, node);
}var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist <= index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
/**
* Insert new node after old node within the container.
*
* @param {Node|number} exist - child or child’s index
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*/
Container.prototype.insertAfter = function insertAfter(exist, add) {
exist = this.index(exist);
var nodes = this.normalize(add, this.nodes[exist]).reverse();
for (var _iterator7 = nodes, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : _iterator7[Symbol.iterator]();;) {
var _ref7;
if (_isArray7) {
if (_i7 >= _iterator7.length) break;
_ref7 = _iterator7[_i7++];
} else {
_i7 = _iterator7.next();
if (_i7.done) break;
_ref7 = _i7.value;
}
var node = _ref7;
this.nodes.splice(exist + 1, 0, node);
}var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist < index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
/**
* Removes node from the container and cleans the parent properties
* from the node and its children.
*
* @param {Node|number} child - child or child’s index
*
* @return {Node} this node for methods chain
*
* @example
* rule.nodes.length //=> 5
* rule.removeChild(decl);
* rule.nodes.length //=> 4
* decl.parent //=> undefined
*/
Container.prototype.removeChild = function removeChild(child) {
child = this.index(child);
this.nodes[child].parent = undefined;
this.nodes.splice(child, 1);
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 1;
}
}
return this;
};
/**
* Removes all children from the container
* and cleans their parent properties.
*
* @return {Node} this node for methods chain
*
* @example
* rule.removeAll();
* rule.nodes.length //=> 0
*/
Container.prototype.removeAll = function removeAll() {
for (var _iterator8 = this.nodes, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : _iterator8[Symbol.iterator]();;) {
var _ref8;
if (_isArray8) {
if (_i8 >= _iterator8.length) break;
_ref8 = _iterator8[_i8++];
} else {
_i8 = _iterator8.next();
if (_i8.done) break;
_ref8 = _i8.value;
}
var node = _ref8;
node.parent = undefined;
}this.nodes = [];
return this;
};
/**
* Passes all declaration values within the container that match pattern
* through callback, replacing those values with the returned result
* of callback.
*
* This method is useful if you are using a custom unit or function
* and need to iterate through all values.
*
* @param {string|RegExp} pattern - replace pattern
* @param {object} opts - options to speed up the search
* @param {string|string[]} opts.props - an array of property names
* @param {string} opts.fast - string that’s used
* to narrow down values and speed up
the regexp search
* @param {function|string} callback - string to replace pattern
* or callback that returns a new
* value.
* The callback will receive
* the same arguments as those
* passed to a function parameter
* of `String#replace`.
*
* @return {Node} this node for methods chain
*
* @example
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
* return 15 * parseInt(string) + 'px';
* });
*/
Container.prototype.replaceValues = function replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts;
opts = {};
}
this.walkDecls(function (decl) {
if (opts.props && opts.props.indexOf(decl.prop) === -1) return;
if (opts.fast && decl.value.indexOf(opts.fast) === -1) return;
decl.value = decl.value.replace(pattern, callback);
});
return this;
};
/**
* Returns `true` if callback returns `true`
* for all of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is every child pass condition
*
* @example
* const noPrefixes = rule.every(i => i.prop[0] !== '-');
*/
Container.prototype.every = function every(condition) {
return this.nodes.every(condition);
};
/**
* Returns `true` if callback returns `true` for (at least) one
* of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is some child pass condition
*
* @example
* const hasPrefix = rule.some(i => i.prop[0] === '-');
*/
Container.prototype.some = function some(condition) {
return this.nodes.some(condition);
};
/**
* Returns a `child`’s index within the {@link Container#nodes} array.
*
* @param {Node} child - child of the current container.
*
* @return {number} child index
*
* @example
* rule.index( rule.nodes[2] ) //=> 2
*/
Container.prototype.index = function index(child) {
if (typeof child === 'number') {
return child;
} else {
return this.nodes.indexOf(child);
}
};
/**
* The container’s first child.
*
* @type {Node}
*
* @example
* rule.first == rules.nodes[0];
*/
Container.prototype.normalize = function normalize(nodes, sample) {
var _this2 = this;
if (typeof nodes === 'string') {
var parse = require('./parse');
nodes = cleanSource(parse(nodes).nodes);
} else if (Array.isArray(nodes)) {
nodes = nodes.slice(0);
for (var _iterator9 = nodes, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : _iterator9[Symbol.iterator]();;) {
var _ref9;
if (_isArray9) {
if (_i9 >= _iterator9.length) break;
_ref9 = _iterator9[_i9++];
} else {
_i9 = _iterator9.next();
if (_i9.done) break;
_ref9 = _i9.value;
}
var i = _ref9;
if (i.parent) i.parent.removeChild(i, 'ignore');
}
} else if (nodes.type === 'root') {
nodes = nodes.nodes.slice(0);
for (var _iterator10 = nodes, _isArray10 = Array.isArray(_iterator10), _i11 = 0, _iterator10 = _isArray10 ? _iterator10 : _iterator10[Symbol.iterator]();;) {
var _ref10;
if (_isArray10) {
if (_i11 >= _iterator10.length) break;
_ref10 = _iterator10[_i11++];
} else {
_i11 = _iterator10.next();
if (_i11.done) break;
_ref10 = _i11.value;
}
var _i10 = _ref10;
if (_i10.parent) _i10.parent.removeChild(_i10, 'ignore');
}
} else if (nodes.type) {
nodes = [nodes];
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation');
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value);
}
nodes = [new _declaration2.default(nodes)];
} else if (nodes.selector) {
var Rule = require('./rule');
nodes = [new Rule(nodes)];
} else if (nodes.name) {
var AtRule = require('./at-rule');
nodes = [new AtRule(nodes)];
} else if (nodes.text) {
nodes = [new _comment2.default(nodes)];
} else {
throw new Error('Unknown node type in node creation');
}
var processed = nodes.map(function (i) {
if (typeof i.before !== 'function') i = _this2.rebuild(i);
if (i.parent) i.parent.removeChild(i);
if (typeof i.raws.before === 'undefined') {
if (sample && typeof sample.raws.before !== 'undefined') {
i.raws.before = sample.raws.before.replace(/[^\s]/g, '');
}
}
i.parent = _this2;
return i;
});
return processed;
};
Container.prototype.rebuild = function rebuild(node, parent) {
var _this3 = this;
var fix = void 0;
if (node.type === 'root') {
var Root = require('./root');
fix = new Root();
} else if (node.type === 'atrule') {
var AtRule = require('./at-rule');
fix = new AtRule();
} else if (node.type === 'rule') {
var Rule = require('./rule');
fix = new Rule();
} else if (node.type === 'decl') {
fix = new _declaration2.default();
} else if (node.type === 'comment') {
fix = new _comment2.default();
}
for (var i in node) {
if (i === 'nodes') {
fix.nodes = node.nodes.map(function (j) {
return _this3.rebuild(j, fix);
});
} else if (i === 'parent' && parent) {
fix.parent = parent;
} else if (node.hasOwnProperty(i)) {
fix[i] = node[i];
}
}
return fix;
};
/**
* @memberof Container#
* @member {Node[]} nodes - an array containing the container’s children
*
* @example
* const root = postcss.parse('a { color: black }');
* root.nodes.length //=> 1
* root.nodes[0].selector //=> 'a'
* root.nodes[0].nodes[0].prop //=> 'color'
*/
_createClass(Container, [{
key: 'first',
get: function get() {
if (!this.nodes) return undefined;
return this.nodes[0];
}
/**
* The container’s last child.
*
* @type {Node}
*
* @example
* rule.last == rule.nodes[rule.nodes.length - 1];
*/
}, {
key: 'last',
get: function get() {
if (!this.nodes) return undefined;
return this.nodes[this.nodes.length - 1];
}
}]);
return Container;
}(_node2.default);
exports.default = Container;
/**
* @callback childCondition
* @param {Node} node - container child
* @param {number} index - child index
* @param {Node[]} nodes - all container children
* @return {boolean}
*/
/**
* @callback childIterator
* @param {Node} node - container child
* @param {number} index - child index
* @return {false|undefined} returning `false` will break iteration
*/
module.exports = exports['default'];
},{"./at-rule":529,"./comment":530,"./declaration":533,"./node":538,"./parse":539,"./root":545,"./rule":546}],532:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _supportsColor = require('supports-color');
var _supportsColor2 = _interopRequireDefault(_supportsColor);
var _chalk = require('chalk');
var _chalk2 = _interopRequireDefault(_chalk);
var _terminalHighlight = require('./terminal-highlight');
var _terminalHighlight2 = _interopRequireDefault(_terminalHighlight);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* The CSS parser throws this error for broken CSS.
*
* Custom parsers can throw this error for broken custom syntax using
* the {@link Node#error} method.
*
* PostCSS will use the input source map to detect the original error location.
* If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
* PostCSS will show the original position in the Sass file.
*
* If you need the position in the PostCSS input
* (e.g., to debug the previous compiler), use `error.input.file`.
*
* @example
* // Catching and checking syntax error
* try {
* postcss.parse('a{')
* } catch (error) {
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
* }
*
* @example
* // Raising error from plugin
* throw node.error('Unknown variable', { plugin: 'postcss-vars' });
*/
var CssSyntaxError = function () {
/**
* @param {string} message - error message
* @param {number} [line] - source line of the error
* @param {number} [column] - source column of the error
* @param {string} [source] - source code of the broken file
* @param {string} [file] - absolute path to the broken file
* @param {string} [plugin] - PostCSS plugin name, if error came from plugin
*/
function CssSyntaxError(message, line, column, source, file, plugin) {
_classCallCheck(this, CssSyntaxError);
/**
* @member {string} - Always equal to `'CssSyntaxError'`. You should
* always check error type
* by `error.name === 'CssSyntaxError'` instead of
* `error instanceof CssSyntaxError`, because
* npm could have several PostCSS versions.
*
* @example
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
*/
this.name = 'CssSyntaxError';
/**
* @member {string} - Error message.
*
* @example
* error.message //=> 'Unclosed block'
*/
this.reason = message;
if (file) {
/**
* @member {string} - Absolute path to the broken file.
*
* @example
* error.file //=> 'a.sass'
* error.input.file //=> 'a.css'
*/
this.file = file;
}
if (source) {
/**
* @member {string} - Source code of the broken file.
*
* @example
* error.source //=> 'a { b {} }'
* error.input.column //=> 'a b { }'
*/
this.source = source;
}
if (plugin) {
/**
* @member {string} - Plugin name, if error came from plugin.
*
* @example
* error.plugin //=> 'postcss-vars'
*/
this.plugin = plugin;
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
/**
* @member {number} - Source line of the error.
*
* @example
* error.line //=> 2
* error.input.line //=> 4
*/
this.line = line;
/**
* @member {number} - Source column of the error.
*
* @example
* error.column //=> 1
* error.input.column //=> 4
*/
this.column = column;
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError);
}
}
CssSyntaxError.prototype.setMessage = function setMessage() {
/**
* @member {string} - Full error text in the GNU error format
* with plugin, file, line and column.
*
* @example
* error.message //=> 'a.css:1:1: Unclosed block'
*/
this.message = this.plugin ? this.plugin + ': ' : '';
this.message += this.file ? this.file : '<css input>';
if (typeof this.line !== 'undefined') {
this.message += ':' + this.line + ':' + this.column;
}
this.message += ': ' + this.reason;
};
/**
* Returns a few lines of CSS source that caused the error.
*
* If the CSS has an input source map without `sourceContent`,
* this method will return an empty string.
*
* @param {boolean} [color] whether arrow will be colored red by terminal
* color codes. By default, PostCSS will detect
* color support by `process.stdout.isTTY`
* and `process.env.NODE_DISABLE_COLORS`.
*
* @example
* error.showSourceCode() //=> " 4 | }
* // 5 | a {
* // > 6 | bad
* // | ^
* // 7 | }
* // 8 | b {"
*
* @return {string} few lines of CSS source that caused the error
*/
CssSyntaxError.prototype.showSourceCode = function showSourceCode(color) {
var _this = this;
if (!this.source) return '';
var css = this.source;
if (typeof color === 'undefined') color = _supportsColor2.default;
if (color) css = (0, _terminalHighlight2.default)(css);
var lines = css.split(/\r?\n/);
var start = Math.max(this.line - 3, 0);
var end = Math.min(this.line + 2, lines.length);
var maxWidth = String(end).length;
function mark(text) {
if (color) {
return _chalk2.default.red.bold(text);
} else {
return text;
}
}
function aside(text) {
if (color) {
return _chalk2.default.gray(text);
} else {
return text;
}
}
return lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ';
if (number === _this.line) {
var spacing = aside(gutter.replace(/\d/g, ' ')) + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' ');
return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^');
} else {
return ' ' + aside(gutter) + line;
}
}).join('\n');
};
/**
* Returns error position, message and source code of the broken part.
*
* @example
* error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
* // > 1 | a {
* // | ^"
*
* @return {string} error position, message and source code
*/
CssSyntaxError.prototype.toString = function toString() {
var code = this.showSourceCode();
if (code) {
code = '\n\n' + code + '\n';
}
return this.name + ': ' + this.message + code;
};
/**
* @memberof CssSyntaxError#
* @member {Input} input - Input object with PostCSS internal information
* about input file. If input has source map
* from previous tool, PostCSS will use origin
* (for example, Sass) source. You can use this
* object to get PostCSS input source.
*
* @example
* error.input.file //=> 'a.css'
* error.file //=> 'a.sass'
*/
return CssSyntaxError;
}();
exports.default = CssSyntaxError;
module.exports = exports['default'];
},{"./terminal-highlight":549,"chalk":554,"supports-color":556}],533:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _node = require('./node');
var _node2 = _interopRequireDefault(_node);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents a CSS declaration.
*
* @extends Node
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.type //=> 'decl'
* decl.toString() //=> ' color: black'
*/
var Declaration = function (_Node) {
_inherits(Declaration, _Node);
function Declaration(defaults) {
_classCallCheck(this, Declaration);
var _this = _possibleConstructorReturn(this, _Node.call(this, defaults));
_this.type = 'decl';
return _this;
}
/**
* @memberof Declaration#
* @member {string} prop - the declaration’s property name
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.prop //=> 'color'
*/
/**
* @memberof Declaration#
* @member {string} value - the declaration’s value
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.value //=> 'black'
*/
/**
* @memberof Declaration#
* @member {boolean} important - `true` if the declaration
* has an !important annotation.
*
* @example
* const root = postcss.parse('a { color: black !important; color: red }');
* root.first.first.important //=> true
* root.first.last.important //=> undefined
*/
/**
* @memberof Declaration#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `between`: the symbols between the property and value
* for declarations.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans declaration from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
return Declaration;
}(_node2.default);
exports.default = Declaration;
module.exports = exports['default'];
},{"./node":538}],534:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _cssSyntaxError = require('./css-syntax-error');
var _cssSyntaxError2 = _interopRequireDefault(_cssSyntaxError);
var _previousMap = require('./previous-map');
var _previousMap2 = _interopRequireDefault(_previousMap);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var sequence = 0;
/**
* Represents the source CSS.
*
* @example
* const root = postcss.parse(css, { from: file });
* const input = root.source.input;
*/
var Input = function () {
/**
* @param {string} css - input CSS source
* @param {object} [opts] - {@link Processor#process} options
*/
function Input(css) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Input);
/**
* @member {string} - input CSS source
*
* @example
* const input = postcss.parse('a{}', { from: file }).input;
* input.css //=> "a{}";
*/
this.css = css.toString();
if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
this.css = this.css.slice(1);
}
if (opts.from) {
if (/^\w+:\/\//.test(opts.from)) {
/**
* @member {string} - The absolute path to the CSS source file
* defined with the `from` option.
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.file //=> '/home/ai/a.css'
*/
this.file = opts.from;
} else {
this.file = _path2.default.resolve(opts.from);
}
}
var map = new _previousMap2.default(this.css, opts);
if (map.text) {
/**
* @member {PreviousMap} - The input source map passed from
* a compilation step before PostCSS
* (for example, from Sass compiler).
*
* @example
* root.source.input.map.consumer().sources //=> ['a.sass']
*/
this.map = map;
var file = map.consumer().file;
if (!this.file && file) this.file = this.mapResolve(file);
}
if (!this.file) {
sequence += 1;
/**
* @member {string} - The unique ID of the CSS source. It will be
* created if `from` option is not provided
* (because PostCSS does not know the file path).
*
* @example
* const root = postcss.parse(css);
* root.source.input.file //=> undefined
* root.source.input.id //=> "<input css 1>"
*/
this.id = '<input css ' + sequence + '>';
}
if (this.map) this.map.file = this.from;
}
Input.prototype.error = function error(message, line, column) {
var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var result = void 0;
var origin = this.origin(line, column);
if (origin) {
result = new _cssSyntaxError2.default(message, origin.line, origin.column, origin.source, origin.file, opts.plugin);
} else {
result = new _cssSyntaxError2.default(message, line, column, this.css, this.file, opts.plugin);
}
result.input = { line: line, column: column, source: this.css };
if (this.file) result.input.file = this.file;
return result;
};
/**
* Reads the input source map and returns a symbol position
* in the input source (e.g., in a Sass file that was compiled
* to CSS before being passed to PostCSS).
*
* @param {number} line - line in input CSS
* @param {number} column - column in input CSS
*
* @return {filePosition} position in input source
*
* @example
* root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
*/
Input.prototype.origin = function origin(line, column) {
if (!this.map) return false;
var consumer = this.map.consumer();
var from = consumer.originalPositionFor({ line: line, column: column });
if (!from.source) return false;
var result = {
file: this.mapResolve(from.source),
line: from.line,
column: from.column
};
var source = consumer.sourceContentFor(from.source);
if (source) result.source = source;
return result;
};
Input.prototype.mapResolve = function mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file;
} else {
return _path2.default.resolve(this.map.consumer().sourceRoot || '.', file);
}
};
/**
* The CSS source identifier. Contains {@link Input#file} if the user
* set the `from` option, or {@link Input#id} if they did not.
* @type {string}
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.from //=> "/home/ai/a.css"
*
* const root = postcss.parse(css);
* root.source.input.from //=> "<input css 1>"
*/
_createClass(Input, [{
key: 'from',
get: function get() {
return this.file || this.id;
}
}]);
return Input;
}();
exports.default = Input;
/**
* @typedef {object} filePosition
* @property {string} file - path to file
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
module.exports = exports['default'];
},{"./css-syntax-error":532,"./previous-map":542,"path":523}],535:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var _mapGenerator = require('./map-generator');
var _mapGenerator2 = _interopRequireDefault(_mapGenerator);
var _stringify2 = require('./stringify');
var _stringify3 = _interopRequireDefault(_stringify2);
var _result = require('./result');
var _result2 = _interopRequireDefault(_result);
var _parse = require('./parse');
var _parse2 = _interopRequireDefault(_parse);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function isPromise(obj) {
return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.then === 'function';
}
/**
* A Promise proxy for the result of PostCSS transformations.
*
* A `LazyResult` instance is returned by {@link Processor#process}.
*
* @example
* const lazy = postcss([cssnext]).process(css);
*/
var LazyResult = function () {
function LazyResult(processor, css, opts) {
_classCallCheck(this, LazyResult);
this.stringified = false;
this.processed = false;
var root = void 0;
if ((typeof css === 'undefined' ? 'undefined' : _typeof(css)) === 'object' && css.type === 'root') {
root = css;
} else if (css instanceof LazyResult || css instanceof _result2.default) {
root = css.root;
if (css.map) {
if (typeof opts.map === 'undefined') opts.map = {};
if (!opts.map.inline) opts.map.inline = false;
opts.map.prev = css.map;
}
} else {
var parser = _parse2.default;
if (opts.syntax) parser = opts.syntax.parse;
if (opts.parser) parser = opts.parser;
if (parser.parse) parser = parser.parse;
try {
root = parser(css, opts);
} catch (error) {
this.error = error;
}
}
this.result = new _result2.default(processor, root, opts);
}
/**
* Returns a {@link Processor} instance, which will be used
* for CSS transformations.
* @type {Processor}
*/
/**
* Processes input CSS through synchronous plugins
* and calls {@link Result#warnings()}.
*
* @return {Warning[]} warnings from plugins
*/
LazyResult.prototype.warnings = function warnings() {
return this.sync().warnings();
};
/**
* Alias for the {@link LazyResult#css} property.
*
* @example
* lazy + '' === lazy.css;
*
* @return {string} output CSS
*/
LazyResult.prototype.toString = function toString() {
return this.css;
};
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls `onFulfilled` with a Result instance. If a plugin throws
* an error, the `onRejected` callback will be executed.
*
* It implements standard Promise API.
*
* @param {onFulfilled} onFulfilled - callback will be executed
* when all plugins will finish work
* @param {onRejected} onRejected - callback will be executed on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* });
*/
LazyResult.prototype.then = function then(onFulfilled, onRejected) {
return this.async().then(onFulfilled, onRejected);
};
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls onRejected for each error thrown in any plugin.
*
* It implements standard Promise API.
*
* @param {onRejected} onRejected - callback will be executed on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* }).catch(error => {
* console.error(error);
* });
*/
LazyResult.prototype.catch = function _catch(onRejected) {
return this.async().catch(onRejected);
};
LazyResult.prototype.handleError = function handleError(error, plugin) {
try {
this.error = error;
if (error.name === 'CssSyntaxError' && !error.plugin) {
error.plugin = plugin.postcssPlugin;
error.setMessage();
} else if (plugin.postcssVersion) {
var pluginName = plugin.postcssPlugin;
var pluginVer = plugin.postcssVersion;
var runtimeVer = this.result.processor.version;
var a = pluginVer.split('.');
var b = runtimeVer.split('.');
if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
console.error('Your current PostCSS version ' + 'is ' + runtimeVer + ', but ' + pluginName + ' ' + 'uses ' + pluginVer + '. Perhaps this is ' + 'the source of the error below.');
}
}
} catch (err) {
if (console && console.error) console.error(err);
}
};
LazyResult.prototype.asyncTick = function asyncTick(resolve, reject) {
var _this = this;
if (this.plugin >= this.processor.plugins.length) {
this.processed = true;
return resolve();
}
try {
var plugin = this.processor.plugins[this.plugin];
var promise = this.run(plugin);
this.plugin += 1;
if (isPromise(promise)) {
promise.then(function () {
_this.asyncTick(resolve, reject);
}).catch(function (error) {
_this.handleError(error, plugin);
_this.processed = true;
reject(error);
});
} else {
this.asyncTick(resolve, reject);
}
} catch (error) {
this.processed = true;
reject(error);
}
};
LazyResult.prototype.async = function async() {
var _this2 = this;
if (this.processed) {
return new Promise(function (resolve, reject) {
if (_this2.error) {
reject(_this2.error);
} else {
resolve(_this2.stringify());
}
});
}
if (this.processing) {
return this.processing;
}
this.processing = new Promise(function (resolve, reject) {
if (_this2.error) return reject(_this2.error);
_this2.plugin = 0;
_this2.asyncTick(resolve, reject);
}).then(function () {
_this2.processed = true;
return _this2.stringify();
});
return this.processing;
};
LazyResult.prototype.sync = function sync() {
if (this.processed) return this.result;
this.processed = true;
if (this.processing) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
if (this.error) throw this.error;
for (var _iterator = this.result.processor.plugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var plugin = _ref;
var promise = this.run(plugin);
if (isPromise(promise)) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
}
return this.result;
};
LazyResult.prototype.run = function run(plugin) {
this.result.lastPlugin = plugin;
try {
return plugin(this.result.root, this.result);
} catch (error) {
this.handleError(error, plugin);
throw error;
}
};
LazyResult.prototype.stringify = function stringify() {
if (this.stringified) return this.result;
this.stringified = true;
this.sync();
var opts = this.result.opts;
var str = _stringify3.default;
if (opts.syntax) str = opts.syntax.stringify;
if (opts.stringifier) str = opts.stringifier;
if (str.stringify) str = str.stringify;
var map = new _mapGenerator2.default(str, this.result.root, this.result.opts);
var data = map.generate();
this.result.css = data[0];
this.result.map = data[1];
return this.result;
};
_createClass(LazyResult, [{
key: 'processor',
get: function get() {
return this.result.processor;
}
/**
* Options from the {@link Processor#process} call.
* @type {processOptions}
*/
}, {
key: 'opts',
get: function get() {
return this.result.opts;
}
/**
* Processes input CSS through synchronous plugins, converts `Root`
* to a CSS string and returns {@link Result#css}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#css
*/
}, {
key: 'css',
get: function get() {
return this.stringify().css;
}
/**
* An alias for the `css` property. Use it with syntaxes
* that generate non-CSS output.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#content
*/
}, {
key: 'content',
get: function get() {
return this.stringify().content;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#map}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {SourceMapGenerator}
* @see Result#map
*/
}, {
key: 'map',
get: function get() {
return this.stringify().map;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#root}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Root}
* @see Result#root
*/
}, {
key: 'root',
get: function get() {
return this.sync().root;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#messages}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Message[]}
* @see Result#messages
*/
}, {
key: 'messages',
get: function get() {
return this.sync().messages;
}
}]);
return LazyResult;
}();
exports.default = LazyResult;
/**
* @callback onFulfilled
* @param {Result} result
*/
/**
* @callback onRejected
* @param {Error} error
*/
module.exports = exports['default'];
},{"./map-generator":537,"./parse":539,"./result":544,"./stringify":548}],536:[function(require,module,exports){
'use strict';
exports.__esModule = true;
/**
* Contains helpers for safely splitting lists of CSS values,
* preserving parentheses and quotes.
*
* @example
* const list = postcss.list;
*
* @namespace list
*/
var list = {
split: function split(string, separators, last) {
var array = [];
var current = '';
var split = false;
var func = 0;
var quote = false;
var escape = false;
for (var i = 0; i < string.length; i++) {
var letter = string[i];
if (quote) {
if (escape) {
escape = false;
} else if (letter === '\\') {
escape = true;
} else if (letter === quote) {
quote = false;
}
} else if (letter === '"' || letter === '\'') {
quote = letter;
} else if (letter === '(') {
func += 1;
} else if (letter === ')') {
if (func > 0) func -= 1;
} else if (func === 0) {
if (separators.indexOf(letter) !== -1) split = true;
}
if (split) {
if (current !== '') array.push(current.trim());
current = '';
split = false;
} else {
current += letter;
}
}
if (last || current !== '') array.push(current.trim());
return array;
},
/**
* Safely splits space-separated values (such as those for `background`,
* `border-radius`, and other shorthand properties).
*
* @param {string} string - space-separated values
*
* @return {string[]} split values
*
* @example
* postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
*/
space: function space(string) {
var spaces = [' ', '\n', '\t'];
return list.split(string, spaces);
},
/**
* Safely splits comma-separated values (such as those for `transition-*`
* and `background` properties).
*
* @param {string} string - comma-separated values
*
* @return {string[]} split values
*
* @example
* postcss.list.comma('black, linear-gradient(white, black)')
* //=> ['black', 'linear-gradient(white, black)']
*/
comma: function comma(string) {
var comma = ',';
return list.split(string, [comma], true);
}
};
exports.default = list;
module.exports = exports['default'];
},{}],537:[function(require,module,exports){
(function (Buffer){
'use strict';
exports.__esModule = true;
var _sourceMap = require('source-map');
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var MapGenerator = function () {
function MapGenerator(stringify, root, opts) {
_classCallCheck(this, MapGenerator);
this.stringify = stringify;
this.mapOpts = opts.map || {};
this.root = root;
this.opts = opts;
}
MapGenerator.prototype.isMap = function isMap() {
if (typeof this.opts.map !== 'undefined') {
return !!this.opts.map;
} else {
return this.previous().length > 0;
}
};
MapGenerator.prototype.previous = function previous() {
var _this = this;
if (!this.previousMaps) {
this.previousMaps = [];
this.root.walk(function (node) {
if (node.source && node.source.input.map) {
var map = node.source.input.map;
if (_this.previousMaps.indexOf(map) === -1) {
_this.previousMaps.push(map);
}
}
});
}
return this.previousMaps;
};
MapGenerator.prototype.isInline = function isInline() {
if (typeof this.mapOpts.inline !== 'undefined') {
return this.mapOpts.inline;
}
var annotation = this.mapOpts.annotation;
if (typeof annotation !== 'undefined' && annotation !== true) {
return false;
}
if (this.previous().length) {
return this.previous().some(function (i) {
return i.inline;
});
} else {
return true;
}
};
MapGenerator.prototype.isSourcesContent = function isSourcesContent() {
if (typeof this.mapOpts.sourcesContent !== 'undefined') {
return this.mapOpts.sourcesContent;
}
if (this.previous().length) {
return this.previous().some(function (i) {
return i.withContent();
});
} else {
return true;
}
};
MapGenerator.prototype.clearAnnotation = function clearAnnotation() {
if (this.mapOpts.annotation === false) return;
var node = void 0;
for (var i = this.root.nodes.length - 1; i >= 0; i--) {
node = this.root.nodes[i];
if (node.type !== 'comment') continue;
if (node.text.indexOf('# sourceMappingURL=') === 0) {
this.root.removeChild(i);
}
}
};
MapGenerator.prototype.setSourcesContent = function setSourcesContent() {
var _this2 = this;
var already = {};
this.root.walk(function (node) {
if (node.source) {
var from = node.source.input.from;
if (from && !already[from]) {
already[from] = true;
var relative = _this2.relative(from);
_this2.map.setSourceContent(relative, node.source.input.css);
}
}
});
};
MapGenerator.prototype.applyPrevMaps = function applyPrevMaps() {
for (var _iterator = this.previous(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var prev = _ref;
var from = this.relative(prev.file);
var root = prev.root || _path2.default.dirname(prev.file);
var map = void 0;
if (this.mapOpts.sourcesContent === false) {
map = new _sourceMap2.default.SourceMapConsumer(prev.text);
if (map.sourcesContent) {
map.sourcesContent = map.sourcesContent.map(function () {
return null;
});
}
} else {
map = prev.consumer();
}
this.map.applySourceMap(map, from, this.relative(root));
}
};
MapGenerator.prototype.isAnnotation = function isAnnotation() {
if (this.isInline()) {
return true;
} else if (typeof this.mapOpts.annotation !== 'undefined') {
return this.mapOpts.annotation;
} else if (this.previous().length) {
return this.previous().some(function (i) {
return i.annotation;
});
} else {
return true;
}
};
MapGenerator.prototype.toBase64 = function toBase64(str) {
if (Buffer) {
return Buffer.from ? Buffer.from(str).toString('base64') : new Buffer(str).toString('base64');
} else {
return window.btoa(unescape(encodeURIComponent(str)));
}
};
MapGenerator.prototype.addAnnotation = function addAnnotation() {
var content = void 0;
if (this.isInline()) {
content = 'data:application/json;base64,' + this.toBase64(this.map.toString());
} else if (typeof this.mapOpts.annotation === 'string') {
content = this.mapOpts.annotation;
} else {
content = this.outputFile() + '.map';
}
var eol = '\n';
if (this.css.indexOf('\r\n') !== -1) eol = '\r\n';
this.css += eol + '/*# sourceMappingURL=' + content + ' */';
};
MapGenerator.prototype.outputFile = function outputFile() {
if (this.opts.to) {
return this.relative(this.opts.to);
} else if (this.opts.from) {
return this.relative(this.opts.from);
} else {
return 'to.css';
}
};
MapGenerator.prototype.generateMap = function generateMap() {
this.generateString();
if (this.isSourcesContent()) this.setSourcesContent();
if (this.previous().length > 0) this.applyPrevMaps();
if (this.isAnnotation()) this.addAnnotation();
if (this.isInline()) {
return [this.css];
} else {
return [this.css, this.map];
}
};
MapGenerator.prototype.relative = function relative(file) {
if (file.indexOf('<') === 0) return file;
if (/^\w+:\/\//.test(file)) return file;
var from = this.opts.to ? _path2.default.dirname(this.opts.to) : '.';
if (typeof this.mapOpts.annotation === 'string') {
from = _path2.default.dirname(_path2.default.resolve(from, this.mapOpts.annotation));
}
file = _path2.default.relative(from, file);
if (_path2.default.sep === '\\') {
return file.replace(/\\/g, '/');
} else {
return file;
}
};
MapGenerator.prototype.sourcePath = function sourcePath(node) {
if (this.mapOpts.from) {
return this.mapOpts.from;
} else {
return this.relative(node.source.input.from);
}
};
MapGenerator.prototype.generateString = function generateString() {
var _this3 = this;
this.css = '';
this.map = new _sourceMap2.default.SourceMapGenerator({ file: this.outputFile() });
var line = 1;
var column = 1;
var lines = void 0,
last = void 0;
this.stringify(this.root, function (str, node, type) {
_this3.css += str;
if (node && type !== 'end') {
if (node.source && node.source.start) {
_this3.map.addMapping({
source: _this3.sourcePath(node),
generated: { line: line, column: column - 1 },
original: {
line: node.source.start.line,
column: node.source.start.column - 1
}
});
} else {
_this3.map.addMapping({
source: '<no source>',
original: { line: 1, column: 0 },
generated: { line: line, column: column - 1 }
});
}
}
lines = str.match(/\n/g);
if (lines) {
line += lines.length;
last = str.lastIndexOf('\n');
column = str.length - last;
} else {
column += str.length;
}
if (node && type !== 'start') {
if (node.source && node.source.end) {
_this3.map.addMapping({
source: _this3.sourcePath(node),
generated: { line: line, column: column - 1 },
original: {
line: node.source.end.line,
column: node.source.end.column
}
});
} else {
_this3.map.addMapping({
source: '<no source>',
original: { line: 1, column: 0 },
generated: { line: line, column: column - 1 }
});
}
}
});
};
MapGenerator.prototype.generate = function generate() {
this.clearAnnotation();
if (this.isMap()) {
return this.generateMap();
} else {
var result = '';
this.stringify(this.root, function (i) {
result += i;
});
return [result];
}
};
return MapGenerator;
}();
exports.default = MapGenerator;
module.exports = exports['default'];
}).call(this,require("buffer").Buffer)
},{"buffer":66,"path":523,"source-map":568}],538:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var _cssSyntaxError = require('./css-syntax-error');
var _cssSyntaxError2 = _interopRequireDefault(_cssSyntaxError);
var _stringifier = require('./stringifier');
var _stringifier2 = _interopRequireDefault(_stringifier);
var _stringify = require('./stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _warnOnce = require('./warn-once');
var _warnOnce2 = _interopRequireDefault(_warnOnce);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var cloneNode = function cloneNode(obj, parent) {
var cloned = new obj.constructor();
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
var value = obj[i];
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent;
} else if (i === 'source') {
cloned[i] = value;
} else if (value instanceof Array) {
cloned[i] = value.map(function (j) {
return cloneNode(j, cloned);
});
} else {
if (type === 'object' && value !== null) value = cloneNode(value);
cloned[i] = value;
}
}
return cloned;
};
/**
* All node classes inherit the following common methods.
*
* @abstract
*/
var Node = function () {
/**
* @param {object} [defaults] - value for node properties
*/
function Node() {
var defaults = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Node);
this.raws = {};
if ((typeof defaults === 'undefined' ? 'undefined' : _typeof(defaults)) !== 'object' && typeof defaults !== 'undefined') {
throw new Error('PostCSS nodes constructor accepts object, not ' + JSON.stringify(defaults));
}
for (var name in defaults) {
this[name] = defaults[name];
}
}
/**
* Returns a CssSyntaxError instance containing the original position
* of the node in the source, showing line and column numbers and also
* a small excerpt to facilitate debugging.
*
* If present, an input source map will be used to get the original position
* of the source, even from a previous compilation step
* (e.g., from Sass compilation).
*
* This method produces very useful error messages.
*
* @param {string} message - error description
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this error.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the error
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the error
*
* @return {CssSyntaxError} error object to throw it
*
* @example
* if ( !variables[name] ) {
* throw decl.error('Unknown variable ' + name, { word: name });
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
* // color: $black
* // a
* // ^
* // background: white
* }
*/
Node.prototype.error = function error(message) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (this.source) {
var pos = this.positionBy(opts);
return this.source.input.error(message, pos.line, pos.column, opts);
} else {
return new _cssSyntaxError2.default(message);
}
};
/**
* This method is provided as a convenience wrapper for {@link Result#warn}.
*
* @param {Result} result - the {@link Result} instance
* that will receive the warning
* @param {string} text - warning message
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this warning.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the warning
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the warning
*
* @return {Warning} created warning object
*
* @example
* const plugin = postcss.plugin('postcss-deprecated', () => {
* return (root, result) => {
* root.walkDecls('bad', decl => {
* decl.warn(result, 'Deprecated property bad');
* });
* };
* });
*/
Node.prototype.warn = function warn(result, text, opts) {
var data = { node: this };
for (var i in opts) {
data[i] = opts[i];
}return result.warn(text, data);
};
/**
* Removes the node from its parent and cleans the parent properties
* from the node and its children.
*
* @example
* if ( decl.prop.match(/^-webkit-/) ) {
* decl.remove();
* }
*
* @return {Node} node to make calls chain
*/
Node.prototype.remove = function remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this;
};
/**
* Returns a CSS string representing the node.
*
* @param {stringifier|syntax} [stringifier] - a syntax to use
* in string generation
*
* @return {string} CSS string of this node
*
* @example
* postcss.rule({ selector: 'a' }).toString() //=> "a {}"
*/
Node.prototype.toString = function toString() {
var stringifier = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _stringify2.default;
if (stringifier.stringify) stringifier = stringifier.stringify;
var result = '';
stringifier(this, function (i) {
result += i;
});
return result;
};
/**
* Returns a clone of the node.
*
* The resulting cloned node and its (cloned) children will have
* a clean parent and code style properties.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* const cloned = decl.clone({ prop: '-moz-' + decl.prop });
* cloned.raws.before //=> undefined
* cloned.parent //=> undefined
* cloned.toString() //=> -moz-transform: scale(0)
*
* @return {Node} clone of the node
*/
Node.prototype.clone = function clone() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = cloneNode(this);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
};
/**
* Shortcut to clone the node and insert the resulting cloned node
* before the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* decl.cloneBefore({ prop: '-moz-' + decl.prop });
*
* @return {Node} - new node
*/
Node.prototype.cloneBefore = function cloneBefore() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = this.clone(overrides);
this.parent.insertBefore(this, cloned);
return cloned;
};
/**
* Shortcut to clone the node and insert the resulting cloned node
* after the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @return {Node} - new node
*/
Node.prototype.cloneAfter = function cloneAfter() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = this.clone(overrides);
this.parent.insertAfter(this, cloned);
return cloned;
};
/**
* Inserts node(s) before the current node and removes the current node.
*
* @param {...Node} nodes - node(s) to replace current one
*
* @example
* if ( atrule.name == 'mixin' ) {
* atrule.replaceWith(mixinRules[atrule.params]);
* }
*
* @return {Node} current node to methods chain
*/
Node.prototype.replaceWith = function replaceWith() {
if (this.parent) {
for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) {
nodes[_key] = arguments[_key];
}
for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
this.parent.insertBefore(this, node);
}
this.remove();
}
return this;
};
Node.prototype.moveTo = function moveTo(newParent) {
(0, _warnOnce2.default)('Node#moveTo was deprecated. Use Container#append.');
this.cleanRaws(this.root() === newParent.root());
this.remove();
newParent.append(this);
return this;
};
Node.prototype.moveBefore = function moveBefore(otherNode) {
(0, _warnOnce2.default)('Node#moveBefore was deprecated. Use Node#before.');
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertBefore(otherNode, this);
return this;
};
Node.prototype.moveAfter = function moveAfter(otherNode) {
(0, _warnOnce2.default)('Node#moveAfter was deprecated. Use Node#after.');
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertAfter(otherNode, this);
return this;
};
/**
* Returns the next child of the node’s parent.
* Returns `undefined` if the current node is the last child.
*
* @return {Node|undefined} next node
*
* @example
* if ( comment.text === 'delete next' ) {
* const next = comment.next();
* if ( next ) {
* next.remove();
* }
* }
*/
Node.prototype.next = function next() {
var index = this.parent.index(this);
return this.parent.nodes[index + 1];
};
/**
* Returns the previous child of the node’s parent.
* Returns `undefined` if the current node is the first child.
*
* @return {Node|undefined} previous node
*
* @example
* const annotation = decl.prev();
* if ( annotation.type == 'comment' ) {
* readAnnotation(annotation.text);
* }
*/
Node.prototype.prev = function prev() {
var index = this.parent.index(this);
return this.parent.nodes[index - 1];
};
/**
* Insert new node before current node to current node’s parent.
*
* Just alias for `node.parent.insertBefore(node, add)`.
*
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain.
*
* @example
* decl.before('content: ""');
*/
Node.prototype.before = function before(add) {
this.parent.insertBefore(this, add);
return this;
};
/**
* Insert new node after current node to current node’s parent.
*
* Just alias for `node.parent.insertAfter(node, add)`.
*
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain.
*
* @example
* decl.after('color: black');
*/
Node.prototype.after = function after(add) {
this.parent.insertAfter(this, add);
return this;
};
Node.prototype.toJSON = function toJSON() {
var fixed = {};
for (var name in this) {
if (!this.hasOwnProperty(name)) continue;
if (name === 'parent') continue;
var value = this[name];
if (value instanceof Array) {
fixed[name] = value.map(function (i) {
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && i.toJSON) {
return i.toJSON();
} else {
return i;
}
});
} else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.toJSON) {
fixed[name] = value.toJSON();
} else {
fixed[name] = value;
}
}
return fixed;
};
/**
* Returns a {@link Node#raws} value. If the node is missing
* the code style property (because the node was manually built or cloned),
* PostCSS will try to autodetect the code style property by looking
* at other nodes in the tree.
*
* @param {string} prop - name of code style property
* @param {string} [defaultType] - name of default value, it can be missed
* if the value is the same as prop
*
* @example
* const root = postcss.parse('a { background: white }');
* root.nodes[0].append({ prop: 'color', value: 'black' });
* root.nodes[0].nodes[1].raws.before //=> undefined
* root.nodes[0].nodes[1].raw('before') //=> ' '
*
* @return {string} code style value
*/
Node.prototype.raw = function raw(prop, defaultType) {
var str = new _stringifier2.default();
return str.raw(this, prop, defaultType);
};
/**
* Finds the Root instance of the node’s tree.
*
* @example
* root.nodes[0].nodes[0].root() === root
*
* @return {Root} root parent
*/
Node.prototype.root = function root() {
var result = this;
while (result.parent) {
result = result.parent;
}return result;
};
Node.prototype.cleanRaws = function cleanRaws(keepBetween) {
delete this.raws.before;
delete this.raws.after;
if (!keepBetween) delete this.raws.between;
};
Node.prototype.positionInside = function positionInside(index) {
var string = this.toString();
var column = this.source.start.column;
var line = this.source.start.line;
for (var i = 0; i < index; i++) {
if (string[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return { line: line, column: column };
};
Node.prototype.positionBy = function positionBy(opts) {
var pos = this.source.start;
if (opts.index) {
pos = this.positionInside(opts.index);
} else if (opts.word) {
var index = this.toString().indexOf(opts.word);
if (index !== -1) pos = this.positionInside(index);
}
return pos;
};
/**
* @memberof Node#
* @member {string} type - String representing the node’s type.
* Possible values are `root`, `atrule`, `rule`,
* `decl`, or `comment`.
*
* @example
* postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
*/
/**
* @memberof Node#
* @member {Container} parent - the node’s parent node.
*
* @example
* root.nodes[0].parent == root;
*/
/**
* @memberof Node#
* @member {source} source - the input source of the node
*
* The property is used in source map generation.
*
* If you create a node manually (e.g., with `postcss.decl()`),
* that node will not have a `source` property and will be absent
* from the source map. For this reason, the plugin developer should
* consider cloning nodes to create new ones (in which case the new node’s
* source will reference the original, cloned node) or setting
* the `source` property manually.
*
* ```js
* // Bad
* const prefixed = postcss.decl({
* prop: '-moz-' + decl.prop,
* value: decl.value
* });
*
* // Good
* const prefixed = decl.clone({ prop: '-moz-' + decl.prop });
* ```
*
* ```js
* if ( atrule.name == 'add-link' ) {
* const rule = postcss.rule({ selector: 'a', source: atrule.source });
* atrule.parent.insertBefore(atrule, rule);
* }
* ```
*
* @example
* decl.source.input.from //=> '/home/ai/a.sass'
* decl.source.start //=> { line: 10, column: 2 }
* decl.source.end //=> { line: 10, column: 12 }
*/
/**
* @memberof Node#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text
* and <code>*/</code>.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans selectors, declaration values and at-rule parameters
* from comments and extra spaces, but it stores origin content in raws
* properties. As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
return Node;
}();
exports.default = Node;
/**
* @typedef {object} position
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
/**
* @typedef {object} source
* @property {Input} input - {@link Input} with input file
* @property {position} start - The starting position of the node’s source
* @property {position} end - The ending position of the node’s source
*/
module.exports = exports['default'];
},{"./css-syntax-error":532,"./stringifier":547,"./stringify":548,"./warn-once":552}],539:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.default = parse;
var _parser = require('./parser');
var _parser2 = _interopRequireDefault(_parser);
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function parse(css, opts) {
if (opts && opts.safe) {
throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
}
var input = new _input2.default(css, opts);
var parser = new _parser2.default(input);
try {
parser.parse();
} catch (e) {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
} else if (/\.sass/i.test(opts.from)) {
e.message += '\nYou tried to parse Sass with ' + 'the standard CSS parser; ' + 'try again with the postcss-sass parser';
} else if (/\.less$/i.test(opts.from)) {
e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
}
}
throw e;
}
return parser.root;
}
module.exports = exports['default'];
},{"./input":534,"./parser":540}],540:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _tokenize = require('./tokenize');
var _tokenize2 = _interopRequireDefault(_tokenize);
var _comment = require('./comment');
var _comment2 = _interopRequireDefault(_comment);
var _atRule = require('./at-rule');
var _atRule2 = _interopRequireDefault(_atRule);
var _root = require('./root');
var _root2 = _interopRequireDefault(_root);
var _rule = require('./rule');
var _rule2 = _interopRequireDefault(_rule);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Parser = function () {
function Parser(input) {
_classCallCheck(this, Parser);
this.input = input;
this.root = new _root2.default();
this.current = this.root;
this.spaces = '';
this.semicolon = false;
this.createTokenizer();
this.root.source = { input: input, start: { line: 1, column: 1 } };
}
Parser.prototype.createTokenizer = function createTokenizer() {
this.tokenizer = (0, _tokenize2.default)(this.input);
};
Parser.prototype.parse = function parse() {
var token = void 0;
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken();
switch (token[0]) {
case 'space':
this.spaces += token[1];
break;
case ';':
this.freeSemicolon(token);
break;
case '}':
this.end(token);
break;
case 'comment':
this.comment(token);
break;
case 'at-word':
this.atrule(token);
break;
case '{':
this.emptyRule(token);
break;
default:
this.other(token);
break;
}
}
this.endFile();
};
Parser.prototype.comment = function comment(token) {
var node = new _comment2.default();
this.init(node, token[2], token[3]);
node.source.end = { line: token[4], column: token[5] };
var text = token[1].slice(2, -2);
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
node.raws.left = match[1];
node.raws.right = match[3];
}
};
Parser.prototype.emptyRule = function emptyRule(token) {
var node = new _rule2.default();
this.init(node, token[2], token[3]);
node.selector = '';
node.raws.between = '';
this.current = node;
};
Parser.prototype.other = function other(start) {
var end = false;
var type = null;
var colon = false;
var bracket = null;
var brackets = [];
var tokens = [];
var token = start;
while (token) {
type = token[0];
tokens.push(token);
if (type === '(' || type === '[') {
if (!bracket) bracket = token;
brackets.push(type === '(' ? ')' : ']');
} else if (brackets.length === 0) {
if (type === ';') {
if (colon) {
this.decl(tokens);
return;
} else {
break;
}
} else if (type === '{') {
this.rule(tokens);
return;
} else if (type === '}') {
this.tokenizer.back(tokens.pop());
end = true;
break;
} else if (type === ':') {
colon = true;
}
} else if (type === brackets[brackets.length - 1]) {
brackets.pop();
if (brackets.length === 0) bracket = null;
}
token = this.tokenizer.nextToken();
}
if (this.tokenizer.endOfFile()) end = true;
if (brackets.length > 0) this.unclosedBracket(bracket);
if (end && colon) {
while (tokens.length) {
token = tokens[tokens.length - 1][0];
if (token !== 'space' && token !== 'comment') break;
this.tokenizer.back(tokens.pop());
}
this.decl(tokens);
return;
} else {
this.unknownWord(tokens);
}
};
Parser.prototype.rule = function rule(tokens) {
tokens.pop();
var node = new _rule2.default();
this.init(node, tokens[0][2], tokens[0][3]);
node.raws.between = this.spacesAndCommentsFromEnd(tokens);
this.raw(node, 'selector', tokens);
this.current = node;
};
Parser.prototype.decl = function decl(tokens) {
var node = new _declaration2.default();
this.init(node);
var last = tokens[tokens.length - 1];
if (last[0] === ';') {
this.semicolon = true;
tokens.pop();
}
if (last[4]) {
node.source.end = { line: last[4], column: last[5] };
} else {
node.source.end = { line: last[2], column: last[3] };
}
while (tokens[0][0] !== 'word') {
if (tokens.length === 1) this.unknownWord(tokens);
node.raws.before += tokens.shift()[1];
}
node.source.start = { line: tokens[0][2], column: tokens[0][3] };
node.prop = '';
while (tokens.length) {
var type = tokens[0][0];
if (type === ':' || type === 'space' || type === 'comment') {
break;
}
node.prop += tokens.shift()[1];
}
node.raws.between = '';
var token = void 0;
while (tokens.length) {
token = tokens.shift();
if (token[0] === ':') {
node.raws.between += token[1];
break;
} else {
node.raws.between += token[1];
}
}
if (node.prop[0] === '_' || node.prop[0] === '*') {
node.raws.before += node.prop[0];
node.prop = node.prop.slice(1);
}
node.raws.between += this.spacesAndCommentsFromStart(tokens);
this.precheckMissedSemicolon(tokens);
for (var i = tokens.length - 1; i > 0; i--) {
token = tokens[i];
if (token[1] === '!important') {
node.important = true;
var string = this.stringFrom(tokens, i);
string = this.spacesFromEnd(tokens) + string;
if (string !== ' !important') node.raws.important = string;
break;
} else if (token[1] === 'important') {
var cache = tokens.slice(0);
var str = '';
for (var j = i; j > 0; j--) {
var _type = cache[j][0];
if (str.trim().indexOf('!') === 0 && _type !== 'space') {
break;
}
str = cache.pop()[1] + str;
}
if (str.trim().indexOf('!') === 0) {
node.important = true;
node.raws.important = str;
tokens = cache;
}
}
if (token[0] !== 'space' && token[0] !== 'comment') {
break;
}
}
this.raw(node, 'value', tokens);
if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens);
};
Parser.prototype.atrule = function atrule(token) {
var node = new _atRule2.default();
node.name = token[1].slice(1);
if (node.name === '') {
this.unnamedAtrule(node, token);
}
this.init(node, token[2], token[3]);
var prev = void 0;
var shift = void 0;
var last = false;
var open = false;
var params = [];
while (!this.tokenizer.endOfFile()) {
token = this.tokenizer.nextToken();
if (token[0] === ';') {
node.source.end = { line: token[2], column: token[3] };
this.semicolon = true;
break;
} else if (token[0] === '{') {
open = true;
break;
} else if (token[0] === '}') {
if (params.length > 0) {
shift = params.length - 1;
prev = params[shift];
while (prev && prev[0] === 'space') {
prev = params[--shift];
}
if (prev) {
node.source.end = { line: prev[4], column: prev[5] };
}
}
this.end(token);
break;
} else {
params.push(token);
}
if (this.tokenizer.endOfFile()) {
last = true;
break;
}
}
node.raws.between = this.spacesAndCommentsFromEnd(params);
if (params.length) {
node.raws.afterName = this.spacesAndCommentsFromStart(params);
this.raw(node, 'params', params);
if (last) {
token = params[params.length - 1];
node.source.end = { line: token[4], column: token[5] };
this.spaces = node.raws.between;
node.raws.between = '';
}
} else {
node.raws.afterName = '';
node.params = '';
}
if (open) {
node.nodes = [];
this.current = node;
}
};
Parser.prototype.end = function end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.semicolon = false;
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
this.spaces = '';
if (this.current.parent) {
this.current.source.end = { line: token[2], column: token[3] };
this.current = this.current.parent;
} else {
this.unexpectedClose(token);
}
};
Parser.prototype.endFile = function endFile() {
if (this.current.parent) this.unclosedBlock();
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
};
Parser.prototype.freeSemicolon = function freeSemicolon(token) {
this.spaces += token[1];
if (this.current.nodes) {
var prev = this.current.nodes[this.current.nodes.length - 1];
if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) {
prev.raws.ownSemicolon = this.spaces;
this.spaces = '';
}
}
};
// Helpers
Parser.prototype.init = function init(node, line, column) {
this.current.push(node);
node.source = { start: { line: line, column: column }, input: this.input };
node.raws.before = this.spaces;
this.spaces = '';
if (node.type !== 'comment') this.semicolon = false;
};
Parser.prototype.raw = function raw(node, prop, tokens) {
var token = void 0,
type = void 0;
var length = tokens.length;
var value = '';
var clean = true;
for (var i = 0; i < length; i += 1) {
token = tokens[i];
type = token[0];
if (type === 'comment' || type === 'space' && i === length - 1) {
clean = false;
} else {
value += token[1];
}
}
if (!clean) {
var raw = tokens.reduce(function (all, i) {
return all + i[1];
}, '');
node.raws[prop] = { value: value, raw: raw };
}
node[prop] = value;
};
Parser.prototype.spacesAndCommentsFromEnd = function spacesAndCommentsFromEnd(tokens) {
var lastTokenType = void 0;
var spaces = '';
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== 'space' && lastTokenType !== 'comment') break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
};
Parser.prototype.spacesAndCommentsFromStart = function spacesAndCommentsFromStart(tokens) {
var next = void 0;
var spaces = '';
while (tokens.length) {
next = tokens[0][0];
if (next !== 'space' && next !== 'comment') break;
spaces += tokens.shift()[1];
}
return spaces;
};
Parser.prototype.spacesFromEnd = function spacesFromEnd(tokens) {
var lastTokenType = void 0;
var spaces = '';
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== 'space') break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
};
Parser.prototype.stringFrom = function stringFrom(tokens, from) {
var result = '';
for (var i = from; i < tokens.length; i++) {
result += tokens[i][1];
}
tokens.splice(from, tokens.length - from);
return result;
};
Parser.prototype.colon = function colon(tokens) {
var brackets = 0;
var token = void 0,
type = void 0,
prev = void 0;
for (var i = 0; i < tokens.length; i++) {
token = tokens[i];
type = token[0];
if (type === '(') {
brackets += 1;
} else if (type === ')') {
brackets -= 1;
} else if (brackets === 0 && type === ':') {
if (!prev) {
this.doubleColon(token);
} else if (prev[0] === 'word' && prev[1] === 'progid') {
continue;
} else {
return i;
}
}
prev = token;
}
return false;
};
// Errors
Parser.prototype.unclosedBracket = function unclosedBracket(bracket) {
throw this.input.error('Unclosed bracket', bracket[2], bracket[3]);
};
Parser.prototype.unknownWord = function unknownWord(tokens) {
throw this.input.error('Unknown word', tokens[0][2], tokens[0][3]);
};
Parser.prototype.unexpectedClose = function unexpectedClose(token) {
throw this.input.error('Unexpected }', token[2], token[3]);
};
Parser.prototype.unclosedBlock = function unclosedBlock() {
var pos = this.current.source.start;
throw this.input.error('Unclosed block', pos.line, pos.column);
};
Parser.prototype.doubleColon = function doubleColon(token) {
throw this.input.error('Double colon', token[2], token[3]);
};
Parser.prototype.unnamedAtrule = function unnamedAtrule(node, token) {
throw this.input.error('At-rule without name', token[2], token[3]);
};
Parser.prototype.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
// Hook for Safe Parser
tokens;
};
Parser.prototype.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
var colon = this.colon(tokens);
if (colon === false) return;
var founded = 0;
var token = void 0;
for (var j = colon - 1; j >= 0; j--) {
token = tokens[j];
if (token[0] !== 'space') {
founded += 1;
if (founded === 2) break;
}
}
throw this.input.error('Missed semicolon', token[2], token[3]);
};
return Parser;
}();
exports.default = Parser;
module.exports = exports['default'];
},{"./at-rule":529,"./comment":530,"./declaration":533,"./root":545,"./rule":546,"./tokenize":550}],541:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _processor = require('./processor');
var _processor2 = _interopRequireDefault(_processor);
var _stringify = require('./stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _comment = require('./comment');
var _comment2 = _interopRequireDefault(_comment);
var _atRule = require('./at-rule');
var _atRule2 = _interopRequireDefault(_atRule);
var _vendor = require('./vendor');
var _vendor2 = _interopRequireDefault(_vendor);
var _parse = require('./parse');
var _parse2 = _interopRequireDefault(_parse);
var _list = require('./list');
var _list2 = _interopRequireDefault(_list);
var _rule = require('./rule');
var _rule2 = _interopRequireDefault(_rule);
var _root = require('./root');
var _root2 = _interopRequireDefault(_root);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Create a new {@link Processor} instance that will apply `plugins`
* as CSS processors.
*
* @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
* plugins. See {@link Processor#use} for plugin format.
*
* @return {Processor} Processor to process multiple CSS
*
* @example
* import postcss from 'postcss';
*
* postcss(plugins).process(css, { from, to }).then(result => {
* console.log(result.css);
* });
*
* @namespace postcss
*/
function postcss() {
for (var _len = arguments.length, plugins = Array(_len), _key = 0; _key < _len; _key++) {
plugins[_key] = arguments[_key];
}
if (plugins.length === 1 && Array.isArray(plugins[0])) {
plugins = plugins[0];
}
return new _processor2.default(plugins);
}
/**
* Creates a PostCSS plugin with a standard API.
*
* The newly-wrapped function will provide both the name and PostCSS
* version of the plugin.
*
* ```js
* const processor = postcss([replace]);
* processor.plugins[0].postcssPlugin //=> 'postcss-replace'
* processor.plugins[0].postcssVersion //=> '5.1.0'
* ```
*
* The plugin function receives 2 arguments: {@link Root}
* and {@link Result} instance. The function should mutate the provided
* `Root` node. Alternatively, you can create a new `Root` node
* and override the `result.root` property.
*
* ```js
* const cleaner = postcss.plugin('postcss-cleaner', () => {
* return (root, result) => {
* result.root = postcss.root();
* };
* });
* ```
*
* As a convenience, plugins also expose a `process` method so that you can use
* them as standalone tools.
*
* ```js
* cleaner.process(css, processOpts, pluginOpts);
* // This is equivalent to:
* postcss([ cleaner(pluginOpts) ]).process(css, processOpts);
* ```
*
* Asynchronous plugins should return a `Promise` instance.
*
* ```js
* postcss.plugin('postcss-import', () => {
* return (root, result) => {
* return new Promise( (resolve, reject) => {
* fs.readFile('base.css', (base) => {
* root.prepend(base);
* resolve();
* });
* });
* };
* });
* ```
*
* Add warnings using the {@link Node#warn} method.
* Send data to other plugins using the {@link Result#messages} array.
*
* ```js
* postcss.plugin('postcss-caniuse-test', () => {
* return (root, result) => {
* css.walkDecls(decl => {
* if ( !caniuse.support(decl.prop) ) {
* decl.warn(result, 'Some browsers do not support ' + decl.prop);
* }
* });
* };
* });
* ```
*
* @param {string} name - PostCSS plugin name. Same as in `name`
* property in `package.json`. It will be saved
* in `plugin.postcssPlugin` property.
* @param {function} initializer - will receive plugin options
* and should return {@link pluginFunction}
*
* @return {Plugin} PostCSS plugin
*/
postcss.plugin = function plugin(name, initializer) {
var creator = function creator() {
var transformer = initializer.apply(undefined, arguments);
transformer.postcssPlugin = name;
transformer.postcssVersion = new _processor2.default().version;
return transformer;
};
var cache = void 0;
Object.defineProperty(creator, 'postcss', {
get: function get() {
if (!cache) cache = creator();
return cache;
}
});
creator.process = function (css, processOpts, pluginOpts) {
return postcss([creator(pluginOpts)]).process(css, processOpts);
};
return creator;
};
/**
* Default function to convert a node tree into a CSS string.
*
* @param {Node} node - start node for stringifing. Usually {@link Root}.
* @param {builder} builder - function to concatenate CSS from node’s parts
* or generate string and source map
*
* @return {void}
*
* @function
*/
postcss.stringify = _stringify2.default;
/**
* Parses source css and returns a new {@link Root} node,
* which contains the source CSS nodes.
*
* @param {string|toString} css - string with input CSS or any object
* with toString() method, like a Buffer
* @param {processOptions} [opts] - options with only `from` and `map` keys
*
* @return {Root} PostCSS AST
*
* @example
* // Simple CSS concatenation with source map support
* const root1 = postcss.parse(css1, { from: file1 });
* const root2 = postcss.parse(css2, { from: file2 });
* root1.append(root2).toResult().css;
*
* @function
*/
postcss.parse = _parse2.default;
/**
* @member {vendor} - Contains the {@link vendor} module.
*
* @example
* postcss.vendor.unprefixed('-moz-tab') //=> ['tab']
*/
postcss.vendor = _vendor2.default;
/**
* @member {list} - Contains the {@link list} module.
*
* @example
* postcss.list.space('5px calc(10% + 5px)') //=> ['5px', 'calc(10% + 5px)']
*/
postcss.list = _list2.default;
/**
* Creates a new {@link Comment} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {Comment} new Comment node
*
* @example
* postcss.comment({ text: 'test' })
*/
postcss.comment = function (defaults) {
return new _comment2.default(defaults);
};
/**
* Creates a new {@link AtRule} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {AtRule} new AtRule node
*
* @example
* postcss.atRule({ name: 'charset' }).toString() //=> "@charset"
*/
postcss.atRule = function (defaults) {
return new _atRule2.default(defaults);
};
/**
* Creates a new {@link Declaration} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {Declaration} new Declaration node
*
* @example
* postcss.decl({ prop: 'color', value: 'red' }).toString() //=> "color: red"
*/
postcss.decl = function (defaults) {
return new _declaration2.default(defaults);
};
/**
* Creates a new {@link Rule} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {Rule} new Rule node
*
* @example
* postcss.rule({ selector: 'a' }).toString() //=> "a {\n}"
*/
postcss.rule = function (defaults) {
return new _rule2.default(defaults);
};
/**
* Creates a new {@link Root} node.
*
* @param {object} [defaults] - properties for the new node.
*
* @return {Root} new Root node
*
* @example
* postcss.root({ after: '\n' }).toString() //=> "\n"
*/
postcss.root = function (defaults) {
return new _root2.default(defaults);
};
exports.default = postcss;
module.exports = exports['default'];
},{"./at-rule":529,"./comment":530,"./declaration":533,"./list":536,"./parse":539,"./processor":543,"./root":545,"./rule":546,"./stringify":548,"./vendor":551}],542:[function(require,module,exports){
(function (Buffer){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var _sourceMap = require('source-map');
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Source map information from input CSS.
* For example, source map after Sass compiler.
*
* This class will automatically find source map in input CSS or in file system
* near input file (according `from` option).
*
* @example
* const root = postcss.parse(css, { from: 'a.sass.css' });
* root.input.map //=> PreviousMap
*/
var PreviousMap = function () {
/**
* @param {string} css - input CSS source
* @param {processOptions} [opts] - {@link Processor#process} options
*/
function PreviousMap(css, opts) {
_classCallCheck(this, PreviousMap);
this.loadAnnotation(css);
/**
* @member {boolean} - Was source map inlined by data-uri to input CSS.
*/
this.inline = this.startWith(this.annotation, 'data:');
var prev = opts.map ? opts.map.prev : undefined;
var text = this.loadMap(opts.from, prev);
if (text) this.text = text;
}
/**
* Create a instance of `SourceMapGenerator` class
* from the `source-map` library to work with source map information.
*
* It is lazy method, so it will create object only on first call
* and then it will use cache.
*
* @return {SourceMapGenerator} object with source map information
*/
PreviousMap.prototype.consumer = function consumer() {
if (!this.consumerCache) {
this.consumerCache = new _sourceMap2.default.SourceMapConsumer(this.text);
}
return this.consumerCache;
};
/**
* Does source map contains `sourcesContent` with input source text.
*
* @return {boolean} Is `sourcesContent` present
*/
PreviousMap.prototype.withContent = function withContent() {
return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
};
PreviousMap.prototype.startWith = function startWith(string, start) {
if (!string) return false;
return string.substr(0, start.length) === start;
};
PreviousMap.prototype.loadAnnotation = function loadAnnotation(css) {
var match = css.match(/\/\*\s*# sourceMappingURL=(.*)\s*\*\//);
if (match) this.annotation = match[1].trim();
};
PreviousMap.prototype.decodeInline = function decodeInline(text) {
// data:application/json;charset=utf-8;base64,
// data:application/json;charset=utf8;base64,
// data:application/json;base64,
var baseUri = /^data:application\/json;(?:charset=utf-?8;)?base64,/;
var uri = 'data:application/json,';
if (this.startWith(text, uri)) {
return decodeURIComponent(text.substr(uri.length));
} else if (baseUri.test(text)) {
return new Buffer(text.substr(RegExp.lastMatch.length), 'base64').toString();
} else {
var encoding = text.match(/data:application\/json;([^,]+),/)[1];
throw new Error('Unsupported source map encoding ' + encoding);
}
};
PreviousMap.prototype.loadMap = function loadMap(file, prev) {
if (prev === false) return false;
if (prev) {
if (typeof prev === 'string') {
return prev;
} else if (typeof prev === 'function') {
var prevPath = prev(file);
if (prevPath && _fs2.default.existsSync && _fs2.default.existsSync(prevPath)) {
return _fs2.default.readFileSync(prevPath, 'utf-8').toString().trim();
} else {
throw new Error('Unable to load previous source map: ' + prevPath.toString());
}
} else if (prev instanceof _sourceMap2.default.SourceMapConsumer) {
return _sourceMap2.default.SourceMapGenerator.fromSourceMap(prev).toString();
} else if (prev instanceof _sourceMap2.default.SourceMapGenerator) {
return prev.toString();
} else if (this.isMap(prev)) {
return JSON.stringify(prev);
} else {
throw new Error('Unsupported previous source map format: ' + prev.toString());
}
} else if (this.inline) {
return this.decodeInline(this.annotation);
} else if (this.annotation) {
var map = this.annotation;
if (file) map = _path2.default.join(_path2.default.dirname(file), map);
this.root = _path2.default.dirname(map);
if (_fs2.default.existsSync && _fs2.default.existsSync(map)) {
return _fs2.default.readFileSync(map, 'utf-8').toString().trim();
} else {
return false;
}
}
};
PreviousMap.prototype.isMap = function isMap(map) {
if ((typeof map === 'undefined' ? 'undefined' : _typeof(map)) !== 'object') return false;
return typeof map.mappings === 'string' || typeof map._mappings === 'string';
};
return PreviousMap;
}();
exports.default = PreviousMap;
module.exports = exports['default'];
}).call(this,require("buffer").Buffer)
},{"buffer":66,"fs":64,"path":523,"source-map":568}],543:[function(require,module,exports){
'use strict';
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
};
var _lazyResult = require('./lazy-result');
var _lazyResult2 = _interopRequireDefault(_lazyResult);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Contains plugins to process CSS. Create one `Processor` instance,
* initialize its plugins, and then use that instance on numerous CSS files.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.process(css1).then(result => console.log(result.css));
* processor.process(css2).then(result => console.log(result.css));
*/
var Processor = function () {
/**
* @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
* plugins. See {@link Processor#use} for plugin format.
*/
function Processor() {
var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
_classCallCheck(this, Processor);
/**
* @member {string} - Current PostCSS version.
*
* @example
* if ( result.processor.version.split('.')[0] !== '6' ) {
* throw new Error('This plugin works only with PostCSS 6');
* }
*/
this.version = '6.0.6';
/**
* @member {pluginFunction[]} - Plugins added to this processor.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.plugins.length //=> 2
*/
this.plugins = this.normalize(plugins);
}
/**
* Adds a plugin to be used as a CSS processor.
*
* PostCSS plugin can be in 4 formats:
* * A plugin created by {@link postcss.plugin} method.
* * A function. PostCSS will pass the function a @{link Root}
* as the first argument and current {@link Result} instance
* as the second.
* * An object with a `postcss` method. PostCSS will use that method
* as described in #2.
* * Another {@link Processor} instance. PostCSS will copy plugins
* from that instance into this one.
*
* Plugins can also be added by passing them as arguments when creating
* a `postcss` instance (see [`postcss(plugins)`]).
*
* Asynchronous plugins should return a `Promise` instance.
*
* @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin
* or {@link Processor}
* with plugins
*
* @example
* const processor = postcss()
* .use(autoprefixer)
* .use(precss);
*
* @return {Processes} current processor to make methods chain
*/
Processor.prototype.use = function use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]));
return this;
};
/**
* Parses source CSS and returns a {@link LazyResult} Promise proxy.
* Because some plugins can be asynchronous it doesn’t make
* any transformations. Transformations will be applied
* in the {@link LazyResult} methods.
*
* @param {string|toString|Result} css - String with input CSS or
* any object with a `toString()`
* method, like a Buffer.
* Optionally, send a {@link Result}
* instance and the processor will
* take the {@link Root} from it.
* @param {processOptions} [opts] - options
*
* @return {LazyResult} Promise proxy
*
* @example
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css);
* });
*/
Processor.prototype.process = function process(css) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return new _lazyResult2.default(this, css, opts);
};
Processor.prototype.normalize = function normalize(plugins) {
var normalized = [];
for (var _iterator = plugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var i = _ref;
if (i.postcss) i = i.postcss;
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && Array.isArray(i.plugins)) {
normalized = normalized.concat(i.plugins);
} else if (typeof i === 'function') {
normalized.push(i);
} else if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && (i.parse || i.stringify)) {
throw new Error('PostCSS syntaxes cannot be used as plugins. ' + 'Instead, please use one of the ' + 'syntax/parser/stringifier options as ' + 'outlined in your PostCSS ' + 'runner documentation.');
} else {
throw new Error(i + ' is not a PostCSS plugin');
}
}
return normalized;
};
return Processor;
}();
exports.default = Processor;
/**
* @callback builder
* @param {string} part - part of generated CSS connected to this node
* @param {Node} node - AST node
* @param {"start"|"end"} [type] - node’s part type
*/
/**
* @callback parser
*
* @param {string|toString} css - string with input CSS or any object
* with toString() method, like a Buffer
* @param {processOptions} [opts] - options with only `from` and `map` keys
*
* @return {Root} PostCSS AST
*/
/**
* @callback stringifier
*
* @param {Node} node - start node for stringifing. Usually {@link Root}.
* @param {builder} builder - function to concatenate CSS from node’s parts
* or generate string and source map
*
* @return {void}
*/
/**
* @typedef {object} syntax
* @property {parser} parse - function to generate AST by string
* @property {stringifier} stringify - function to generate string by AST
*/
/**
* @typedef {object} toString
* @property {function} toString
*/
/**
* @callback pluginFunction
* @param {Root} root - parsed input CSS
* @param {Result} result - result to set warnings or check other plugins
*/
/**
* @typedef {object} Plugin
* @property {function} postcss - PostCSS plugin function
*/
/**
* @typedef {object} processOptions
* @property {string} from - the path of the CSS source file.
* You should always set `from`,
* because it is used in source map
* generation and syntax error messages.
* @property {string} to - the path where you’ll put the output
* CSS file. You should always set `to`
* to generate correct source maps.
* @property {parser} parser - function to generate AST by string
* @property {stringifier} stringifier - class to generate string by AST
* @property {syntax} syntax - object with `parse` and `stringify`
* @property {object} map - source map options
* @property {boolean} map.inline - does source map should
* be embedded in the output
* CSS as a base64-encoded
* comment
* @property {string|object|false|function} map.prev - source map content
* from a previous
* processing step
* (for example, Sass).
* PostCSS will try to find
* previous map
* automatically, so you
* could disable it by
* `false` value.
* @property {boolean} map.sourcesContent - does PostCSS should set
* the origin content to map
* @property {string|false} map.annotation - does PostCSS should set
* annotation comment to map
* @property {string} map.from - override `from` in map’s
* `sources`
*/
module.exports = exports['default'];
},{"./lazy-result":535}],544:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _warning = require('./warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Provides the result of the PostCSS transformations.
*
* A Result instance is returned by {@link LazyResult#then}
* or {@link Root#toResult} methods.
*
* @example
* postcss([cssnext]).process(css).then(function (result) {
* console.log(result.css);
* });
*
* @example
* var result2 = postcss.parse(css).toResult();
*/
var Result = function () {
/**
* @param {Processor} processor - processor used for this transformation.
* @param {Root} root - Root node after all transformations.
* @param {processOptions} opts - options from the {@link Processor#process}
* or {@link Root#toResult}
*/
function Result(processor, root, opts) {
_classCallCheck(this, Result);
/**
* @member {Processor} - The Processor instance used
* for this transformation.
*
* @example
* for ( let plugin of result.processor.plugins) {
* if ( plugin.postcssPlugin === 'postcss-bad' ) {
* throw 'postcss-good is incompatible with postcss-bad';
* }
* });
*/
this.processor = processor;
/**
* @member {Message[]} - Contains messages from plugins
* (e.g., warnings or custom messages).
* Each message should have type
* and plugin properties.
*
* @example
* postcss.plugin('postcss-min-browser', () => {
* return (root, result) => {
* var browsers = detectMinBrowsersByCanIUse(root);
* result.messages.push({
* type: 'min-browser',
* plugin: 'postcss-min-browser',
* browsers: browsers
* });
* };
* });
*/
this.messages = [];
/**
* @member {Root} - Root node after all transformations.
*
* @example
* root.toResult().root == root;
*/
this.root = root;
/**
* @member {processOptions} - Options from the {@link Processor#process}
* or {@link Root#toResult} call
* that produced this Result instance.
*
* @example
* root.toResult(opts).opts == opts;
*/
this.opts = opts;
/**
* @member {string} - A CSS string representing of {@link Result#root}.
*
* @example
* postcss.parse('a{}').toResult().css //=> "a{}"
*/
this.css = undefined;
/**
* @member {SourceMapGenerator} - An instance of `SourceMapGenerator`
* class from the `source-map` library,
* representing changes
* to the {@link Result#root} instance.
*
* @example
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
*
* @example
* if ( result.map ) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString());
* }
*/
this.map = undefined;
}
/**
* Returns for @{link Result#css} content.
*
* @example
* result + '' === result.css
*
* @return {string} string representing of {@link Result#root}
*/
Result.prototype.toString = function toString() {
return this.css;
};
/**
* Creates an instance of {@link Warning} and adds it
* to {@link Result#messages}.
*
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*
* @return {Warning} created warning
*/
Result.prototype.warn = function warn(text) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!opts.plugin) {
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
opts.plugin = this.lastPlugin.postcssPlugin;
}
}
var warning = new _warning2.default(text, opts);
this.messages.push(warning);
return warning;
};
/**
* Returns warnings from plugins. Filters {@link Warning} instances
* from {@link Result#messages}.
*
* @example
* result.warnings().forEach(warn => {
* console.warn(warn.toString());
* });
*
* @return {Warning[]} warnings from plugins
*/
Result.prototype.warnings = function warnings() {
return this.messages.filter(function (i) {
return i.type === 'warning';
});
};
/**
* An alias for the {@link Result#css} property.
* Use it with syntaxes that generate non-CSS output.
* @type {string}
*
* @example
* result.css === result.content;
*/
_createClass(Result, [{
key: 'content',
get: function get() {
return this.css;
}
}]);
return Result;
}();
exports.default = Result;
/**
* @typedef {object} Message
* @property {string} type - message type
* @property {string} plugin - source PostCSS plugin name
*/
module.exports = exports['default'];
},{"./warning":553}],545:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents a CSS file and contains all its parsed nodes.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{color:black} b{z-index:2}');
* root.type //=> 'root'
* root.nodes.length //=> 2
*/
var Root = function (_Container) {
_inherits(Root, _Container);
function Root(defaults) {
_classCallCheck(this, Root);
var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));
_this.type = 'root';
if (!_this.nodes) _this.nodes = [];
return _this;
}
Root.prototype.removeChild = function removeChild(child, ignore) {
var index = this.index(child);
if (!ignore && index === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[index].raws.before;
}
return _Container.prototype.removeChild.call(this, child);
};
Root.prototype.normalize = function normalize(child, sample, type) {
var nodes = _Container.prototype.normalize.call(this, child);
if (sample) {
if (type === 'prepend') {
if (this.nodes.length > 1) {
sample.raws.before = this.nodes[1].raws.before;
} else {
delete sample.raws.before;
}
} else if (this.first !== sample) {
for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var node = _ref;
node.raws.before = sample.raws.before;
}
}
}
return nodes;
};
/**
* Returns a {@link Result} instance representing the root’s CSS.
*
* @param {processOptions} [opts] - options with only `to` and `map` keys
*
* @return {Result} result with current root’s CSS
*
* @example
* const root1 = postcss.parse(css1, { from: 'a.css' });
* const root2 = postcss.parse(css2, { from: 'b.css' });
* root1.append(root2);
* const result = root1.toResult({ to: 'all.css', map: true });
*/
Root.prototype.toResult = function toResult() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var LazyResult = require('./lazy-result');
var Processor = require('./processor');
var lazy = new LazyResult(new Processor(), this, opts);
return lazy.stringify();
};
/**
* @memberof Root#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `after`: the space symbols after the last child to the end of file.
* * `semicolon`: is the last child has an (optional) semicolon.
*
* @example
* postcss.parse('a {}\n').raws //=> { after: '\n' }
* postcss.parse('a {}').raws //=> { after: '' }
*/
return Root;
}(_container2.default);
exports.default = Root;
module.exports = exports['default'];
},{"./container":531,"./lazy-result":535,"./processor":543}],546:[function(require,module,exports){
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.__esModule = true;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
var _container = require('./container');
var _container2 = _interopRequireDefault(_container);
var _list = require('./list');
var _list2 = _interopRequireDefault(_list);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass)));
}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
/**
* Represents a CSS rule: a selector followed by a declaration block.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{}');
* const rule = root.first;
* rule.type //=> 'rule'
* rule.toString() //=> 'a{}'
*/
var Rule = function (_Container) {
_inherits(Rule, _Container);
function Rule(defaults) {
_classCallCheck(this, Rule);
var _this = _possibleConstructorReturn(this, _Container.call(this, defaults));
_this.type = 'rule';
if (!_this.nodes) _this.nodes = [];
return _this;
}
/**
* An array containing the rule’s individual selectors.
* Groups of selectors are split at commas.
*
* @type {string[]}
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
*
* rule.selector //=> 'a, b'
* rule.selectors //=> ['a', 'b']
*
* rule.selectors = ['a', 'strong'];
* rule.selector //=> 'a, strong'
*/
_createClass(Rule, [{
key: 'selectors',
get: function get() {
return _list2.default.comma(this.selector);
},
set: function set(values) {
var match = this.selector ? this.selector.match(/,\s*/) : null;
var sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
this.selector = values.join(sep);
}
/**
* @memberof Rule#
* @member {string} selector - the rule’s full selector represented
* as a string
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
* rule.selector //=> 'a, b'
*/
/**
* @memberof Rule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains `true` if the last child has
* an (optional) semicolon.
* * `ownSemicolon`: contains `true` if there is semicolon after rule.
*
* PostCSS cleans selectors from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
*/
}]);
return Rule;
}(_container2.default);
exports.default = Rule;
module.exports = exports['default'];
},{"./container":531,"./list":536}],547:[function(require,module,exports){
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var defaultRaw = {
colon: ': ',
indent: ' ',
beforeDecl: '\n',
beforeRule: '\n',
beforeOpen: ' ',
beforeClose: '\n',
beforeComment: '\n',
after: '\n',
emptyBody: '',
commentLeft: ' ',
commentRight: ' '
};
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
var Stringifier = function () {
function Stringifier(builder) {
_classCallCheck(this, Stringifier);
this.builder = builder;
}
Stringifier.prototype.stringify = function stringify(node, semicolon) {
this[node.type](node, semicolon);
};
Stringifier.prototype.root = function root(node) {
this.body(node);
if (node.raws.after) this.builder(node.raws.after);
};
Stringifier.prototype.comment = function comment(node) {
var left = this.raw(node, 'left', 'commentLeft');
var right = this.raw(node, 'right', 'commentRight');
this.builder('/*' + left + node.text + right + '*/', node);
};
Stringifier.prototype.decl = function decl(node, semicolon) {
var between = this.raw(node, 'between', 'colon');
var string = node.prop + between + this.rawValue(node, 'value');
if (node.important) {
string += node.raws.important || ' !important';
}
if (semicolon) string += ';';
this.builder(string, node);
};
Stringifier.prototype.rule = function rule(node) {
this.block(node, this.rawValue(node, 'selector'));
if (node.raws.ownSemicolon) {
this.builder(node.raws.ownSemicolon, node, 'end');
}
};
Stringifier.prototype.atrule = function atrule(node, semicolon) {
var name = '@' + node.name;
var params = node.params ? this.rawValue(node, 'params') : '';
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName;
} else if (params) {
name += ' ';
}
if (node.nodes) {
this.block(node, name + params);
} else {
var end = (node.raws.between || '') + (semicolon ? ';' : '');
this.builder(name + params + end, node);
}
};
Stringifier.prototype.body = function body(node) {
var last = node.nodes.length - 1;
while (last > 0) {
if (node.nodes[last].type !== 'comment') break;
last -= 1;
}
var semicolon = this.raw(node, 'semicolon');
for (var i = 0; i < node.nodes.length; i++) {
var child = node.nodes[i];
var before = this.raw(child, 'before');
if (before) this.builder(before);
this.stringify(child, last !== i || semicolon);
}
};
Stringifier.prototype.block = function block(node, start) {
var between = this.raw(node, 'between', 'beforeOpen');
this.builder(start + between + '{', node, 'start');
var after = void 0;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) this.builder(after);
this.builder('}', node, 'end');
};
Stringifier.prototype.raw = function raw(node, own, detect) {
var value = void 0;
if (!detect) detect = own;
// Already had
if (own) {
value = node.raws[own];
if (typeof value !== 'undefined') return value;
}
var parent = node.parent;
// Hack for first rule in CSS
if (detect === 'before') {
if (!parent || parent.type === 'root' && parent.first === node) {
return '';
}
}
// Floating child without parent
if (!parent) return defaultRaw[detect];
// Detect style by other nodes
var root = node.root();
if (!root.rawCache) root.rawCache = {};
if (typeof root.rawCache[detect] !== 'undefined') {
return root.rawCache[detect];
}
if (detect === 'before' || detect === 'after') {
return this.beforeAfter(node, detect);
} else {
var method = 'raw' + capitalize(detect);
if (this[method]) {
value = this[method](root, node);
} else {
root.walk(function (i) {
value = i.raws[own];
if (typeof value !== 'undefined') return false;
});
}
}
if (typeof value === 'undefined') value = defaultRaw[detect];
root.rawCache[detect] = value;
return value;
};
Stringifier.prototype.rawSemicolon = function rawSemicolon(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawEmptyBody = function rawEmptyBody(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawIndent = function rawIndent(root) {
if (root.raws.indent) return root.raws.indent;
var value = void 0;
root.walk(function (i) {
var p = i.parent;
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
var parts = i.raws.before.split('\n');
value = parts[parts.length - 1];
value = value.replace(/[^\s]/g, '');
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeComment = function rawBeforeComment(root, node) {
var value = void 0;
root.walkComments(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeDecl');
}
return value;
};
Stringifier.prototype.rawBeforeDecl = function rawBeforeDecl(root, node) {
var value = void 0;
root.walkDecls(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeRule');
}
return value;
};
Stringifier.prototype.rawBeforeRule = function rawBeforeRule(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && (i.parent !== root || root.first !== i)) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeClose = function rawBeforeClose(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeOpen = function rawBeforeOpen(root) {
var value = void 0;
root.walk(function (i) {
if (i.type !== 'decl') {
value = i.raws.between;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawColon = function rawColon(root) {
var value = void 0;
root.walkDecls(function (i) {
if (typeof i.raws.between !== 'undefined') {
value = i.raws.between.replace(/[^\s:]/g, '');
return false;
}
});
return value;
};
Stringifier.prototype.beforeAfter = function beforeAfter(node, detect) {
var value = void 0;
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl');
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment');
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule');
} else {
value = this.raw(node, null, 'beforeClose');
}
var buf = node.parent;
var depth = 0;
while (buf && buf.type !== 'root') {
depth += 1;
buf = buf.parent;
}
if (value.indexOf('\n') !== -1) {
var indent = this.raw(node, null, 'indent');
if (indent.length) {
for (var step = 0; step < depth; step++) {
value += indent;
}
}
}
return value;
};
Stringifier.prototype.rawValue = function rawValue(node, prop) {
var value = node[prop];
var raw = node.raws[prop];
if (raw && raw.value === value) {
return raw.raw;
} else {
return value;
}
};
return Stringifier;
}();
exports.default = Stringifier;
module.exports = exports['default'];
},{}],548:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.default = stringify;
var _stringifier = require('./stringifier');
var _stringifier2 = _interopRequireDefault(_stringifier);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function stringify(node, builder) {
var str = new _stringifier2.default(builder);
str.stringify(node);
}
module.exports = exports['default'];
},{"./stringifier":547}],549:[function(require,module,exports){
'use strict';
exports.__esModule = true;
var _chalk = require('chalk');
var _chalk2 = _interopRequireDefault(_chalk);
var _tokenize = require('./tokenize');
var _tokenize2 = _interopRequireDefault(_tokenize);
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var HIGHLIGHT_THEME = {
'brackets': _chalk2.default.cyan,
'at-word': _chalk2.default.cyan,
'call': _chalk2.default.cyan,
'comment': _chalk2.default.gray,
'string': _chalk2.default.green,
'class': _chalk2.default.yellow,
'hash': _chalk2.default.magenta,
'(': _chalk2.default.cyan,
')': _chalk2.default.cyan,
'{': _chalk2.default.yellow,
'}': _chalk2.default.yellow,
'[': _chalk2.default.yellow,
']': _chalk2.default.yellow,
':': _chalk2.default.yellow,
';': _chalk2.default.yellow
};
function getTokenType(_ref, processor) {
var type = _ref[0],
value = _ref[1];
if (type === 'word') {
if (value[0] === '.') {
return 'class';
}
if (value[0] === '#') {
return 'hash';
}
}
if (!processor.endOfFile()) {
var next = processor.nextToken();
processor.back(next);
if (next[0] === 'brackets' || next[0] === '(') return 'call';
}
return type;
}
function terminalHighlight(css) {
var processor = (0, _tokenize2.default)(new _input2.default(css), { ignoreErrors: true });
var result = '';
var _loop = function _loop() {
var token = processor.nextToken();
var color = HIGHLIGHT_THEME[getTokenType(token, processor)];
if (color) {
result += token[1].split(/\r?\n/).map(function (i) {
return color(i);
}).join('\n');
} else {
result += token[1];
}
};
while (!processor.endOfFile()) {
_loop();
}
return result;
}
exports.default = terminalHighlight;
module.exports = exports['default'];
},{"./input":534,"./tokenize":550,"chalk":554}],550:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.default = tokenizer;
var SINGLE_QUOTE = 39;
var DOUBLE_QUOTE = 34;
var BACKSLASH = 92;
var SLASH = 47;
var NEWLINE = 10;
var SPACE = 32;
var FEED = 12;
var TAB = 9;
var CR = 13;
var OPEN_SQUARE = 91;
var CLOSE_SQUARE = 93;
var OPEN_PARENTHESES = 40;
var CLOSE_PARENTHESES = 41;
var OPEN_CURLY = 123;
var CLOSE_CURLY = 125;
var SEMICOLON = 59;
var ASTERISK = 42;
var COLON = 58;
var AT = 64;
var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g;
var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
var RE_HEX_ESCAPE = /[a-f0-9]/i;
function tokenizer(input) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var css = input.css.valueOf();
var ignore = options.ignoreErrors;
var code = void 0,
next = void 0,
quote = void 0,
lines = void 0,
last = void 0,
content = void 0,
escape = void 0,
nextLine = void 0,
nextOffset = void 0,
escaped = void 0,
escapePos = void 0,
prev = void 0,
n = void 0,
currentToken = void 0;
var length = css.length;
var offset = -1;
var line = 1;
var pos = 0;
var buffer = [];
var returned = [];
function unclosed(what) {
throw input.error('Unclosed ' + what, line, pos - offset);
}
function endOfFile() {
return returned.length === 0 && pos >= length;
}
function nextToken() {
if (returned.length) return returned.pop();
if (pos >= length) return;
code = css.charCodeAt(pos);
if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) {
offset = pos;
line += 1;
}
switch (code) {
case NEWLINE:
case SPACE:
case TAB:
case CR:
case FEED:
next = pos;
do {
next += 1;
code = css.charCodeAt(next);
if (code === NEWLINE) {
offset = next;
line += 1;
}
} while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
currentToken = ['space', css.slice(pos, next)];
pos = next - 1;
break;
case OPEN_SQUARE:
currentToken = ['[', '[', line, pos - offset];
break;
case CLOSE_SQUARE:
currentToken = [']', ']', line, pos - offset];
break;
case OPEN_CURLY:
currentToken = ['{', '{', line, pos - offset];
break;
case CLOSE_CURLY:
currentToken = ['}', '}', line, pos - offset];
break;
case COLON:
currentToken = [':', ':', line, pos - offset];
break;
case SEMICOLON:
currentToken = [';', ';', line, pos - offset];
break;
case OPEN_PARENTHESES:
prev = buffer.length ? buffer.pop()[1] : '';
n = css.charCodeAt(pos + 1);
if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) {
next = pos;
do {
escaped = false;
next = css.indexOf(')', next + 1);
if (next === -1) {
if (ignore) {
next = pos;
break;
} else {
unclosed('bracket');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
currentToken = ['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset];
pos = next;
} else {
next = css.indexOf(')', pos + 1);
content = css.slice(pos, next + 1);
if (next === -1 || RE_BAD_BRACKET.test(content)) {
currentToken = ['(', '(', line, pos - offset];
} else {
currentToken = ['brackets', content, line, pos - offset, line, next - offset];
pos = next;
}
}
break;
case CLOSE_PARENTHESES:
currentToken = [')', ')', line, pos - offset];
break;
case SINGLE_QUOTE:
case DOUBLE_QUOTE:
quote = code === SINGLE_QUOTE ? '\'' : '"';
next = pos;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
if (ignore) {
next = pos + 1;
break;
} else {
unclosed('string');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
currentToken = ['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset];
offset = nextOffset;
line = nextLine;
pos = next;
break;
case AT:
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css);
if (RE_AT_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
currentToken = ['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];
pos = next;
break;
case BACKSLASH:
next = pos;
escape = true;
while (css.charCodeAt(next + 1) === BACKSLASH) {
next += 1;
escape = !escape;
}
code = css.charCodeAt(next + 1);
if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
next += 1;
if (RE_HEX_ESCAPE.test(css.charAt(next))) {
while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
next += 1;
}
if (css.charCodeAt(next + 1) === SPACE) {
next += 1;
}
}
}
currentToken = ['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];
pos = next;
break;
default:
if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
next = css.indexOf('*/', pos + 2) + 1;
if (next === 0) {
if (ignore) {
next = css.length;
} else {
unclosed('comment');
}
}
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
currentToken = ['comment', content, line, pos - offset, nextLine, next - nextOffset];
offset = nextOffset;
line = nextLine;
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css);
if (RE_WORD_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
currentToken = ['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset];
buffer.push(currentToken);
pos = next;
}
break;
}
pos++;
return currentToken;
}
function back(token) {
returned.push(token);
}
return {
back: back,
nextToken: nextToken,
endOfFile: endOfFile
};
}
module.exports = exports['default'];
},{}],551:[function(require,module,exports){
'use strict';
exports.__esModule = true;
/**
* Contains helpers for working with vendor prefixes.
*
* @example
* const vendor = postcss.vendor;
*
* @namespace vendor
*/
var vendor = {
/**
* Returns the vendor prefix extracted from an input string.
*
* @param {string} prop - string with or without vendor prefix
*
* @return {string} vendor prefix or empty string
*
* @example
* postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
* postcss.vendor.prefix('tab-size') //=> ''
*/
prefix: function prefix(prop) {
var match = prop.match(/^(-\w+-)/);
if (match) {
return match[0];
} else {
return '';
}
},
/**
* Returns the input string stripped of its vendor prefix.
*
* @param {string} prop - string with or without vendor prefix
*
* @return {string} string name without vendor prefixes
*
* @example
* postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
*/
unprefixed: function unprefixed(prop) {
return prop.replace(/^-\w+-/, '');
}
};
exports.default = vendor;
module.exports = exports['default'];
},{}],552:[function(require,module,exports){
'use strict';
exports.__esModule = true;
exports.default = warnOnce;
var printed = {};
function warnOnce(message) {
if (printed[message]) return;
printed[message] = true;
if (typeof console !== 'undefined' && console.warn) console.warn(message);
}
module.exports = exports['default'];
},{}],553:[function(require,module,exports){
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
/**
* Represents a plugin’s warning. It can be created using {@link Node#warn}.
*
* @example
* if ( decl.important ) {
* decl.warn(result, 'Avoid !important', { word: '!important' });
* }
*/
var Warning = function () {
/**
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*/
function Warning(text) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Warning);
/**
* @member {string} - Type to filter warnings from
* {@link Result#messages}. Always equal
* to `"warning"`.
*
* @example
* const nonWarning = result.messages.filter(i => i.type !== 'warning')
*/
this.type = 'warning';
/**
* @member {string} - The warning message.
*
* @example
* warning.text //=> 'Try to avoid !important'
*/
this.text = text;
if (opts.node && opts.node.source) {
var pos = opts.node.positionBy(opts);
/**
* @member {number} - Line in the input file
* with this warning’s source
*
* @example
* warning.line //=> 5
*/
this.line = pos.line;
/**
* @member {number} - Column in the input file
* with this warning’s source.
*
* @example
* warning.column //=> 6
*/
this.column = pos.column;
}
for (var opt in opts) {
this[opt] = opts[opt];
}
}
/**
* Returns a warning position and message.
*
* @example
* warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
*
* @return {string} warning position and message
*/
Warning.prototype.toString = function toString() {
if (this.node) {
return this.node.error(this.text, {
plugin: this.plugin,
index: this.index,
word: this.word
}).message;
} else if (this.plugin) {
return this.plugin + ': ' + this.text;
} else {
return this.text;
}
};
/**
* @memberof Warning#
* @member {string} plugin - The name of the plugin that created
* it will fill this property automatically.
* this warning. When you call {@link Node#warn}
*
* @example
* warning.plugin //=> 'postcss-important'
*/
/**
* @memberof Warning#
* @member {Node} node - Contains the CSS node that caused the warning.
*
* @example
* warning.node.toString() //=> 'color: white !important'
*/
return Warning;
}();
exports.default = Warning;
module.exports = exports['default'];
},{}],554:[function(require,module,exports){
(function (process){
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
var ansiStyles = require('ansi-styles');
var supportsColor = require('supports-color');
var template = require('./templates.js');
var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
// `color-convert` models to exclude from the Chalk API due to conflicts and such
var skipModels = new Set(['gray']);
var styles = Object.create(null);
function applyOptions(obj, options) {
options = options || {};
// Detect level if not set manually
obj.level = options.level === undefined ? supportsColor.level : options.level;
obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
}
function Chalk(options) {
// We check for this.template here since calling chalk.constructor()
// by itself will have a `this` of a previously constructed chalk object.
if (!this || !(this instanceof Chalk) || this.template) {
var chalk = {};
applyOptions(chalk, options);
chalk.template = function () {
var args = [].slice.call(arguments);
return chalkTag.apply(null, [chalk.template].concat(args));
};
Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
chalk.template.constructor = Chalk;
return chalk.template;
}
applyOptions(this, options);
}
// Use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\x1B[94m';
}
var _loop = function _loop(key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
styles[key] = {
get: function get() {
var codes = ansiStyles[key];
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], key);
}
};
};
for (var _iterator = Object.keys(ansiStyles), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var key = _ref;
_loop(key);
}
ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
var _loop2 = function _loop2(model) {
if (skipModels.has(model)) {
return 'continue';
}
styles[model] = {
get: function get() {
var level = this.level;
return function () {
var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
var codes = {
open: open,
close: ansiStyles.color.close,
closeRe: ansiStyles.color.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
};
}
};
};
for (var _iterator2 = Object.keys(ansiStyles.color.ansi), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var model = _ref2;
var _ret2 = _loop2(model);
if (_ret2 === 'continue') continue;
}
ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
var _loop3 = function _loop3(model) {
if (skipModels.has(model)) {
return 'continue';
}
var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get: function get() {
var level = this.level;
return function () {
var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
var codes = {
open: open,
close: ansiStyles.bgColor.close,
closeRe: ansiStyles.bgColor.closeRe
};
return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
};
}
};
};
for (var _iterator3 = Object.keys(ansiStyles.bgColor.ansi), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var model = _ref3;
var _ret3 = _loop3(model);
if (_ret3 === 'continue') continue;
}
var proto = Object.defineProperties(function () {}, styles);
function build(_styles, key) {
var builder = function builder() {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
var self = this;
Object.defineProperty(builder, 'level', {
enumerable: true,
get: function get() {
return self.level;
},
set: function set(level) {
self.level = level;
}
});
Object.defineProperty(builder, 'enabled', {
enumerable: true,
get: function get() {
return self.enabled;
},
set: function set(enabled) {
self.enabled = enabled;
}
});
// See below for fix regarding invisible grey/dim combination on Windows
builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
// `__proto__` is used because we must return a function, but there is
// no way to create a function with a different prototype.
builder.__proto__ = proto; // eslint-disable-line no-proto
return builder;
}
function applyStyle() {
// Support varags, but simply cast to string in case there's only one arg
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
// Don't slice `arguments`, it prevents V8 optimizations
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || this.level <= 0 || !str) {
return str;
}
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
var originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && this.hasGrey) {
ansiStyles.dim.open = '';
}
for (var _iterator4 = this._styles.slice().reverse(), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) {
var _ref4;
if (_isArray4) {
if (_i4 >= _iterator4.length) break;
_ref4 = _iterator4[_i4++];
} else {
_i4 = _iterator4.next();
if (_i4.done) break;
_ref4 = _i4.value;
}
var code = _ref4;
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
// Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS
// https://github.com/chalk/chalk/pull/92
str = str.replace(/\r?\n/g, code.close + '$&' + code.open);
}
// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
ansiStyles.dim.open = originalDim;
return str;
}
function chalkTag(chalk, strings) {
var args = [].slice.call(arguments, 2);
if (!Array.isArray(strings)) {
return strings.toString();
}
var parts = [strings.raw[0]];
for (var i = 1; i < strings.length; i++) {
parts.push(args[i - 1].toString().replace(/[{}]/g, '\\$&'));
parts.push(strings.raw[i]);
}
return template(chalk, parts.join(''));
}
Object.defineProperties(Chalk.prototype, styles);
module.exports = Chalk(); // eslint-disable-line new-cap
module.exports.supportsColor = supportsColor;
}).call(this,require('_process'))
},{"./templates.js":555,"_process":557,"ansi-styles":62,"escape-string-regexp":519,"supports-color":556}],555:[function(require,module,exports){
'use strict';
function data(parent) {
return {
styles: [],
parent: parent,
contents: []
};
}
var zeroBound = function zeroBound(n) {
return n < 0 ? 0 : n;
};
var lastIndex = function lastIndex(a) {
return zeroBound(a.length - 1);
};
var last = function last(a) {
return a[lastIndex(a)];
};
var takeWhileReverse = function takeWhileReverse(array, predicate, start) {
var out = [];
for (var i = start; i >= 0 && i <= start; i--) {
if (predicate(array[i])) {
out.unshift(array[i]);
} else {
break;
}
}
return out;
};
/**
* Checks if the character at position i in string is a normal character a.k.a a non control character.
* */
var isNormalCharacter = function isNormalCharacter(string, i) {
var char = string[i];
var backslash = '\\';
if (!(char === backslash || char === '{' || char === '}')) {
return true;
}
var n = i === 0 ? 0 : takeWhileReverse(string, function (x) {
return x === '\\';
}, zeroBound(i - 1)).length;
return n % 2 === 1;
};
var collectStyles = function collectStyles(data) {
return data ? collectStyles(data.parent).concat(data.styles) : ['reset'];
};
/**
* Computes the style for a given data based on it's style and the style of it's parent. Also accounts for !style styles
* which remove a style from the list if present.
* */
var sumStyles = function sumStyles(data) {
var negateRegex = /^~.+/;
var out = [];
for (var _iterator = collectStyles(data), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _style = _ref;
if (negateRegex.test(_style)) {
(function () {
var exclude = _style.slice(1);
out = out.filter(function (x) {
return x !== exclude;
});
})();
} else {
out.push(_style);
}
}
return out;
};
/**
* Takes a string and parses it into a tree of data objects which inherit styles from their parent.
* */
function parse(string) {
var root = data(null);
var pushingStyle = false;
var current = root;
var _loop = function _loop(i) {
var char = string[i];
var addNormalCharacter = function addNormalCharacter() {
var lastChunk = last(current.contents);
if (typeof lastChunk === 'string') {
current.contents[lastIndex(current.contents)] = lastChunk + char;
} else {
current.contents.push(char);
}
};
if (pushingStyle) {
if (' \t'.indexOf(char) > -1) {
pushingStyle = false;
} else if (char === '\n') {
pushingStyle = false;
addNormalCharacter();
} else if (char === '.') {
current.styles.push('');
} else {
current.styles[lastIndex(current.styles)] = (last(current.styles) || '') + char;
}
} else if (isNormalCharacter(string, i)) {
addNormalCharacter();
} else if (char === '{') {
pushingStyle = true;
var nCurrent = data(current);
current.contents.push(nCurrent);
current = nCurrent;
} else if (char === '}') {
current = current.parent;
}
};
for (var i = 0; i < string.length; i++) {
_loop(i);
}
if (current !== root) {
throw new Error('literal template has an unclosed block');
}
return root;
}
/**
* Takes a tree of data objects and flattens it to a list of data objects with the inherited and negations styles
* accounted for.
* */
function flatten(data) {
var flat = [];
for (var _iterator2 = data.contents, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var content = _ref2;
if (typeof content === 'string') {
flat.push({
styles: sumStyles(data),
content: content
});
} else {
flat = flat.concat(flatten(content));
}
}
return flat;
}
function assertStyle(chalk, style) {
if (!chalk[style]) {
throw new Error('invalid Chalk style: ' + style);
}
}
/**
* Checks if a given style is valid and parses style functions.
* */
function parseStyle(chalk, style) {
var fnMatch = style.match(/^\s*(\w+)\s*\(\s*([^)]*)\s*\)\s*/);
if (!fnMatch) {
assertStyle(chalk, style);
return chalk[style];
}
var name = fnMatch[1].trim();
var args = fnMatch[2].split(/,/g).map(function (s) {
return s.trim();
});
assertStyle(chalk, name);
return chalk[name].apply(chalk, args);
}
/**
* Performs the actual styling of the string, essentially lifted from cli.js.
* */
function style(chalk, flat) {
return flat.map(function (data) {
var fn = data.styles.reduce(parseStyle, chalk);
return fn(data.content.replace(/\n$/, ''));
}).join('');
}
module.exports = function (chalk, string) {
return style(chalk, flatten(parse(string)));
};
},{}],556:[function(require,module,exports){
'use strict';
module.exports = false;
},{}],557:[function(require,module,exports){
'use strict';
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) {
return [];
};
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () {
return '/';
};
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function () {
return 0;
};
},{}],558:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
var has = Object.prototype.hasOwnProperty;
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = Object.create(null);
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Return how many unique items are in this ArraySet. If duplicates have been
* added, than those do not count towards the size.
*
* @returns Number
*/
ArraySet.prototype.size = function ArraySet_size() {
return Object.getOwnPropertyNames(this._set).length;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var sStr = util.toSetString(aStr);
var isDuplicate = has.call(this._set, sStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[sStr] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
var sStr = util.toSetString(aStr);
return has.call(this._set, sStr);
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
var sStr = util.toSetString(aStr);
if (has.call(this._set, sStr)) {
return this._set[sStr];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
},{"./util":567}],559:[function(require,module,exports){
"use strict";
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var base64 = require('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative ? -shifted : shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string via the out parameter.
*/
exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (aIndex >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charCodeAt(aIndex++));
if (digit === -1) {
throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
}
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
aOutParam.value = fromVLQSigned(result);
aOutParam.rest = aIndex;
};
},{"./base64":560}],560:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function (number) {
if (0 <= number && number < intToCharMap.length) {
return intToCharMap[number];
}
throw new TypeError("Must be between 0 and 63: " + number);
};
/**
* Decode a single base 64 character code digit to an integer. Returns -1 on
* failure.
*/
exports.decode = function (charCode) {
var bigA = 65; // 'A'
var bigZ = 90; // 'Z'
var littleA = 97; // 'a'
var littleZ = 122; // 'z'
var zero = 48; // '0'
var nine = 57; // '9'
var plus = 43; // '+'
var slash = 47; // '/'
var littleOffset = 26;
var numberOffset = 52;
// 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
if (bigA <= charCode && charCode <= bigZ) {
return charCode - bigA;
}
// 26 - 51: abcdefghijklmnopqrstuvwxyz
if (littleA <= charCode && charCode <= littleZ) {
return charCode - littleA + littleOffset;
}
// 52 - 61: 0123456789
if (zero <= charCode && charCode <= nine) {
return charCode - zero + numberOffset;
}
// 62: +
if (charCode == plus) {
return 62;
}
// 63: /
if (charCode == slash) {
return 63;
}
// Invalid base64 digit.
return -1;
};
},{}],561:[function(require,module,exports){
"use strict";
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.GREATEST_LOWER_BOUND = 1;
exports.LEAST_UPPER_BOUND = 2;
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the index of
// the next-closest element.
//
// 3. We did not find the exact element, and there is no next-closest
// element than the one we are searching for, so we return -1.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return mid;
} else if (cmp > 0) {
// Our needle is greater than aHaystack[mid].
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return aHigh < aHaystack.length ? aHigh : -1;
} else {
return mid;
}
} else {
// Our needle is less than aHaystack[mid].
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
}
// we are in termination case (3) or (2) and return the appropriate thing.
if (aBias == exports.LEAST_UPPER_BOUND) {
return mid;
} else {
return aLow < 0 ? -1 : aLow;
}
}
}
/**
* This is an implementation of binary search which will always try and return
* the index of the closest element if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
* @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
* 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
*/
exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
if (aHaystack.length === 0) {
return -1;
}
var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND);
if (index < 0) {
return -1;
}
// We have found either the exact element, or the next-closest element than
// the one we are searching for. However, there may be more than one such
// element. Make sure we always return the smallest of these.
while (index - 1 >= 0) {
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
break;
}
--index;
}
return index;
};
},{}],562:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = { generatedLine: -1, generatedColumn: 0 };
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;
},{"./util":567}],563:[function(require,module,exports){
"use strict";
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
// It turns out that some (most?) JavaScript engines don't self-host
// `Array.prototype.sort`. This makes sense because C++ will likely remain
// faster than JS when doing raw CPU-intensive sorting. However, when using a
// custom comparator function, calling back and forth between the VM's C++ and
// JIT'd JS is rather slow *and* loses JIT type information, resulting in
// worse generated code for the comparator function than would be optimal. In
// fact, when sorting with a comparator, these costs outweigh the benefits of
// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
// a ~3500ms mean speed-up in `bench/bench.html`.
/**
* Swap the elements indexed by `x` and `y` in the array `ary`.
*
* @param {Array} ary
* The array.
* @param {Number} x
* The index of the first item.
* @param {Number} y
* The index of the second item.
*/
function swap(ary, x, y) {
var temp = ary[x];
ary[x] = ary[y];
ary[y] = temp;
}
/**
* Returns a random integer within the range `low .. high` inclusive.
*
* @param {Number} low
* The lower bound on the range.
* @param {Number} high
* The upper bound on the range.
*/
function randomIntInRange(low, high) {
return Math.round(low + Math.random() * (high - low));
}
/**
* The Quick Sort algorithm.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
* @param {Number} p
* Start index of the array
* @param {Number} r
* End index of the array
*/
function doQuickSort(ary, comparator, p, r) {
// If our lower bound is less than our upper bound, we (1) partition the
// array into two pieces and (2) recurse on each half. If it is not, this is
// the empty array and our base case.
if (p < r) {
// (1) Partitioning.
//
// The partitioning chooses a pivot between `p` and `r` and moves all
// elements that are less than or equal to the pivot to the before it, and
// all the elements that are greater than it after it. The effect is that
// once partition is done, the pivot is in the exact place it will be when
// the array is put in sorted order, and it will not need to be moved
// again. This runs in O(n) time.
// Always choose a random pivot so that an input array which is reverse
// sorted does not cause O(n^2) running time.
var pivotIndex = randomIntInRange(p, r);
var i = p - 1;
swap(ary, pivotIndex, r);
var pivot = ary[r];
// Immediately after `j` is incremented in this loop, the following hold
// true:
//
// * Every element in `ary[p .. i]` is less than or equal to the pivot.
//
// * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
for (var j = p; j < r; j++) {
if (comparator(ary[j], pivot) <= 0) {
i += 1;
swap(ary, i, j);
}
}
swap(ary, i + 1, j);
var q = i + 1;
// (2) Recurse on each half.
doQuickSort(ary, comparator, p, q - 1);
doQuickSort(ary, comparator, q + 1, r);
}
}
/**
* Sort the given array in-place with the given comparator function.
*
* @param {Array} ary
* An array to sort.
* @param {function} comparator
* Function to use to compare two items.
*/
exports.quickSort = function (ary, comparator) {
doQuickSort(ary, comparator, 0, ary.length - 1);
};
},{}],564:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
var binarySearch = require('./binary-search');
var ArraySet = require('./array-set').ArraySet;
var base64VLQ = require('./base64-vlq');
var quickSort = require('./quick-sort').quickSort;
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap);
}
SourceMapConsumer.fromSourceMap = function (aSourceMap) {
return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function get() {
if (!this.__generatedMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function get() {
if (!this.__originalMappings) {
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
var c = aStr.charAt(index);
return c === ";" || c === ",";
};
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
throw new Error("Subclasses must implement _parseMappings");
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer.LEAST_UPPER_BOUND = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source === null ? null : this._sources.at(mapping.source);
if (source != null && sourceRoot != null) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name === null ? null : this._names.at(mapping.name)
};
}, this).forEach(aCallback, context);
};
/**
* Returns all generated line and column information for the original source,
* line, and column provided. If no column is provided, returns all mappings
* corresponding to a either the line we are searching for or the next
* closest line that has any mappings. Otherwise, returns all mappings
* corresponding to the given line and either the column we are searching for
* or the next closest column that has any offsets.
*
* The only argument is an object with the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: Optional. the column number in the original source.
*
* and an array of objects is returned, each with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
var line = util.getArg(aArgs, 'line');
// When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
// returns the index of the closest mapping less than the needle. By
// setting needle.originalColumn to 0, we thus find the last mapping for
// the given line, provided such a mapping exists.
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: line,
originalColumn: util.getArg(aArgs, 'column', 0)
};
if (this.sourceRoot != null) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
if (!this._sources.has(needle.source)) {
return [];
}
needle.source = this._sources.indexOf(needle.source);
var mappings = [];
var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND);
if (index >= 0) {
var mapping = this._originalMappings[index];
if (aArgs.column === undefined) {
var originalLine = mapping.originalLine;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we found. Since
// mappings are sorted, this is guaranteed to find all mappings for
// the line we found.
while (mapping && mapping.originalLine === originalLine) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
});
mapping = this._originalMappings[++index];
}
} else {
var originalColumn = mapping.originalColumn;
// Iterate until either we run out of mappings, or we run into
// a mapping for a different line than the one we were searching for.
// Since mappings are sorted, this is guaranteed to find all mappings for
// the line we are searching for.
while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
mappings.push({
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
});
mapping = this._originalMappings[++index];
}
}
}
return mappings;
};
exports.SourceMapConsumer = SourceMapConsumer;
/**
* A BasicSourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: Optional. The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function BasicSourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
sources = sources.map(String)
// Some source maps produce relative source paths like "./foo.js" instead of
// "foo.js". Normalize these first so that future comparisons will succeed.
// See bugzil.la/1090768.
.map(util.normalize)
// Always ensure that absolute sources are internally stored relative to
// the source root, if the source root is absolute. Not doing this would
// be particularly problematic when the source root is a prefix of the
// source (valid, but why??). See github issue #199 and bugzil.la/1188982.
.map(function (source) {
return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source;
});
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names.map(String), true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
/**
* Create a BasicSourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns BasicSourceMapConsumer
*/
BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(BasicSourceMapConsumer.prototype);
var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot);
smc.file = aSourceMap._file;
// Because we are modifying the entries (by converting string sources and
// names to indices into the sources and names ArraySets), we have to make
// a copy of the entry or else bad things happen. Shared mutable state
// strikes again! See github issue #191.
var generatedMappings = aSourceMap._mappings.toArray().slice();
var destGeneratedMappings = smc.__generatedMappings = [];
var destOriginalMappings = smc.__originalMappings = [];
for (var i = 0, length = generatedMappings.length; i < length; i++) {
var srcMapping = generatedMappings[i];
var destMapping = new Mapping();
destMapping.generatedLine = srcMapping.generatedLine;
destMapping.generatedColumn = srcMapping.generatedColumn;
if (srcMapping.source) {
destMapping.source = sources.indexOf(srcMapping.source);
destMapping.originalLine = srcMapping.originalLine;
destMapping.originalColumn = srcMapping.originalColumn;
if (srcMapping.name) {
destMapping.name = names.indexOf(srcMapping.name);
}
destOriginalMappings.push(destMapping);
}
destGeneratedMappings.push(destMapping);
}
quickSort(smc.__originalMappings, util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
BasicSourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
get: function get() {
return this._sources.toArray().map(function (s) {
return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
/**
* Provide the JIT with a nice shape / hidden class.
*/
function Mapping() {
this.generatedLine = 0;
this.generatedColumn = 0;
this.source = null;
this.originalLine = null;
this.originalColumn = null;
this.name = null;
}
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var length = aStr.length;
var index = 0;
var cachedSegments = {};
var temp = {};
var originalMappings = [];
var generatedMappings = [];
var mapping, str, segment, end, value;
while (index < length) {
if (aStr.charAt(index) === ';') {
generatedLine++;
index++;
previousGeneratedColumn = 0;
} else if (aStr.charAt(index) === ',') {
index++;
} else {
mapping = new Mapping();
mapping.generatedLine = generatedLine;
// Because each offset is encoded relative to the previous one,
// many segments often have the same encoding. We can exploit this
// fact by caching the parsed variable length fields of each segment,
// allowing us to avoid a second parse if we encounter the same
// segment again.
for (end = index; end < length; end++) {
if (this._charIsMappingSeparator(aStr, end)) {
break;
}
}
str = aStr.slice(index, end);
segment = cachedSegments[str];
if (segment) {
index += str.length;
} else {
segment = [];
while (index < end) {
base64VLQ.decode(aStr, index, temp);
value = temp.value;
index = temp.rest;
segment.push(value);
}
if (segment.length === 2) {
throw new Error('Found a source, but no line and column');
}
if (segment.length === 3) {
throw new Error('Found a source and line, but no column');
}
cachedSegments[str] = segment;
}
// Generated column.
mapping.generatedColumn = previousGeneratedColumn + segment[0];
previousGeneratedColumn = mapping.generatedColumn;
if (segment.length > 1) {
// Original source.
mapping.source = previousSource + segment[1];
previousSource += segment[1];
// Original line.
mapping.originalLine = previousOriginalLine + segment[2];
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
// Original column.
mapping.originalColumn = previousOriginalColumn + segment[3];
previousOriginalColumn = mapping.originalColumn;
if (segment.length > 4) {
// Original name.
mapping.name = previousName + segment[4];
previousName += segment[4];
}
}
generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
originalMappings.push(mapping);
}
}
}
quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
this.__generatedMappings = generatedMappings;
quickSort(originalMappings, util.compareByOriginalPositions);
this.__originalMappings = originalMappings;
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
};
/**
* Compute the last column for each generated mapping. The last column is
* inclusive.
*/
BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
for (var index = 0; index < this._generatedMappings.length; ++index) {
var mapping = this._generatedMappings[index];
// Mappings do not contain a field for the last generated columnt. We
// can come up with an optimistic estimate, however, by assuming that
// mappings are contiguous (i.e. given two consecutive mappings, the
// first mapping ends where the second one starts).
if (index + 1 < this._generatedMappings.length) {
var nextMapping = this._generatedMappings[index + 1];
if (mapping.generatedLine === nextMapping.generatedLine) {
mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
continue;
}
}
// The last mapping for each line spans the entire line.
mapping.lastGeneratedColumn = Infinity;
}
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var index = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND));
if (index >= 0) {
var mapping = this._generatedMappings[index];
if (mapping.generatedLine === needle.generatedLine) {
var source = util.getArg(mapping, 'source', null);
if (source !== null) {
source = this._sources.at(source);
if (this.sourceRoot != null) {
source = util.join(this.sourceRoot, source);
}
}
var name = util.getArg(mapping, 'name', null);
if (name !== null) {
name = this._names.at(name);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: name
};
}
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
if (!this.sourcesContent) {
return false;
}
return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) {
return sc == null;
});
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot != null) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
}
if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
// This function is used recursively from
// IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
// don't want to throw if we can't find the source - we just want to
// return null, so we provide a flag to exit gracefully.
if (nullOnMissing) {
return null;
} else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
* - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
* 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
* closest element that is smaller than or greater than the one we are
* searching for, respectively, if the exact element cannot be found.
* Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
var source = util.getArg(aArgs, 'source');
if (this.sourceRoot != null) {
source = util.relative(this.sourceRoot, source);
}
if (!this._sources.has(source)) {
return {
line: null,
column: null,
lastColumn: null
};
}
source = this._sources.indexOf(source);
var needle = {
source: source,
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND));
if (index >= 0) {
var mapping = this._originalMappings[index];
if (mapping.source === needle.source) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null),
lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
};
}
}
return {
line: null,
column: null,
lastColumn: null
};
};
exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
/**
* An IndexedSourceMapConsumer instance represents a parsed source map which
* we can query for information. It differs from BasicSourceMapConsumer in
* that it takes "indexed" source maps (i.e. ones with a "sections" field) as
* input.
*
* The only parameter is a raw source map (either as a JSON string, or already
* parsed to an object). According to the spec for indexed source maps, they
* have the following attributes:
*
* - version: Which version of the source map spec this map is following.
* - file: Optional. The generated file this source map is associated with.
* - sections: A list of section definitions.
*
* Each value under the "sections" field has two fields:
* - offset: The offset into the original specified at which this section
* begins to apply, defined as an object with a "line" and "column"
* field.
* - map: A source map definition. This source map could also be indexed,
* but doesn't have to be.
*
* Instead of the "map" field, it's also possible to have a "url" field
* specifying a URL to retrieve a source map from, but that's currently
* unsupported.
*
* Here's an example source map, taken from the source map spec[0], but
* modified to omit a section which uses the "url" field.
*
* {
* version : 3,
* file: "app.js",
* sections: [{
* offset: {line:100, column:10},
* map: {
* version : 3,
* file: "section.js",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AAAA,E;;ABCDE;"
* }
* }],
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
*/
function IndexedSourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sections = util.getArg(sourceMap, 'sections');
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
this._sources = new ArraySet();
this._names = new ArraySet();
var lastOffset = {
line: -1,
column: 0
};
this._sections = sections.map(function (s) {
if (s.url) {
// The url field will require support for asynchronicity.
// See https://github.com/mozilla/source-map/issues/16
throw new Error('Support for url field in sections not implemented.');
}
var offset = util.getArg(s, 'offset');
var offsetLine = util.getArg(offset, 'line');
var offsetColumn = util.getArg(offset, 'column');
if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
throw new Error('Section offsets must be ordered and non-overlapping.');
}
lastOffset = offset;
return {
generatedOffset: {
// The offset fields are 0-based, but we use 1-based indices when
// encoding/decoding from VLQ.
generatedLine: offsetLine + 1,
generatedColumn: offsetColumn + 1
},
consumer: new SourceMapConsumer(util.getArg(s, 'map'))
};
});
}
IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
/**
* The version of the source mapping spec that we are consuming.
*/
IndexedSourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
get: function get() {
var sources = [];
for (var i = 0; i < this._sections.length; i++) {
for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
sources.push(this._sections[i].consumer.sources[j]);
}
}
return sources;
}
});
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
// Find the section containing the generated position we're trying to map
// to an original position.
var sectionIndex = binarySearch.search(needle, this._sections, function (needle, section) {
var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
if (cmp) {
return cmp;
}
return needle.generatedColumn - section.generatedOffset.generatedColumn;
});
var section = this._sections[sectionIndex];
if (!section) {
return {
source: null,
line: null,
column: null,
name: null
};
}
return section.consumer.originalPositionFor({
line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
bias: aArgs.bias
});
};
/**
* Return true if we have the source content for every source in the source
* map, false otherwise.
*/
IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
return this._sections.every(function (s) {
return s.consumer.hasContentsOfAllSources();
});
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* available.
*/
IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
var content = section.consumer.sourceContentFor(aSource, true);
if (content) {
return content;
}
}
if (nullOnMissing) {
return null;
} else {
throw new Error('"' + aSource + '" is not in the SourceMap.');
}
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
// Only consider this section if the requested source is in the list of
// sources of the consumer.
if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
continue;
}
var generatedPosition = section.consumer.generatedPositionFor(aArgs);
if (generatedPosition) {
var ret = {
line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
};
return ret;
}
}
return {
line: null,
column: null
};
};
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
this.__generatedMappings = [];
this.__originalMappings = [];
for (var i = 0; i < this._sections.length; i++) {
var section = this._sections[i];
var sectionMappings = section.consumer._generatedMappings;
for (var j = 0; j < sectionMappings.length; j++) {
var mapping = sectionMappings[j];
var source = section.consumer._sources.at(mapping.source);
if (section.consumer.sourceRoot !== null) {
source = util.join(section.consumer.sourceRoot, source);
}
this._sources.add(source);
source = this._sources.indexOf(source);
var name = section.consumer._names.at(mapping.name);
this._names.add(name);
name = this._names.indexOf(name);
// The mappings coming from the consumer for the section have
// generated positions relative to the start of the section, so we
// need to offset them to be relative to the start of the concatenated
// generated file.
var adjustedMapping = {
source: source,
generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: name
};
this.__generatedMappings.push(adjustedMapping);
if (typeof adjustedMapping.originalLine === 'number') {
this.__originalMappings.push(adjustedMapping);
}
}
}
quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
quickSort(this.__originalMappings, util.compareByOriginalPositions);
};
exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
},{"./array-set":558,"./base64-vlq":559,"./binary-search":561,"./quick-sort":563,"./util":567}],565:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var base64VLQ = require('./base64-vlq');
var util = require('./util');
var ArraySet = require('./array-set').ArraySet;
var MappingList = require('./mapping-list').MappingList;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. You may pass an object with the following
* properties:
*
* - file: The filename of the generated source.
* - sourceRoot: A root for all relative URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
if (!aArgs) {
aArgs = {};
}
this._file = util.getArg(aArgs, 'file', null);
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = new MappingList();
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source != null) {
newMapping.source = mapping.source;
if (sourceRoot != null) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name != null) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
if (!this._skipValidation) {
this._validateMapping(generated, original, source, name);
}
if (source != null) {
source = String(source);
if (!this._sources.has(source)) {
this._sources.add(source);
}
}
if (name != null) {
name = String(name);
if (!this._names.has(name)) {
this._names.add(name);
}
}
this._mappings.add({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot != null) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent != null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = Object.create(null);
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else if (this._sourcesContents) {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
* @param aSourceMapPath Optional. The dirname of the path to the source map
* to be applied. If relative, it is relative to the SourceMapConsumer.
* This parameter is needed when the two source maps aren't in the same
* directory, and the source map to be applied contains relative source
* paths. If so, those relative source paths need to be rewritten
* relative to the SourceMapGenerator.
*/
SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
var sourceFile = aSourceFile;
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (aSourceFile == null) {
if (aSourceMapConsumer.file == null) {
throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.');
}
sourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "sourceFile" relative if an absolute Url is passed.
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "sourceFile"
this._mappings.unsortedForEach(function (mapping) {
if (mapping.source === sourceFile && mapping.originalLine != null) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source != null) {
// Copy mapping
mapping.source = original.source;
if (aSourceMapPath != null) {
mapping.source = util.join(aSourceMapPath, mapping.source);
}
if (sourceRoot != null) {
mapping.source = util.relative(sourceRoot, mapping.source);
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name != null) {
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source != null && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name != null && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aSourceMapPath != null) {
sourceFile = util.join(aSourceMapPath, sourceFile);
}
if (sourceRoot != null) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
// Case 1.
return;
} else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
// Cases 2 and 3.
return;
} else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
original: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var next;
var mapping;
var nameIdx;
var sourceIdx;
var mappings = this._mappings.toArray();
for (var i = 0, len = mappings.length; i < len; i++) {
mapping = mappings[i];
next = '';
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
next += ';';
previousGeneratedLine++;
}
} else {
if (i > 0) {
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
continue;
}
next += ',';
}
}
next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source != null) {
sourceIdx = this._sources.indexOf(mapping.source);
next += base64VLQ.encode(sourceIdx - previousSource);
previousSource = sourceIdx;
// lines are stored 0-based in SourceMap spec version 3
next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name != null) {
nameIdx = this._names.indexOf(mapping.name);
next += base64VLQ.encode(nameIdx - previousName);
previousName = nameIdx;
}
}
result += next;
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot != null) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._file != null) {
map.file = this._file;
}
if (this._sourceRoot != null) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() {
return JSON.stringify(this.toJSON());
};
exports.SourceMapGenerator = SourceMapGenerator;
},{"./array-set":558,"./base64-vlq":559,"./mapping-list":562,"./util":567}],566:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
var util = require('./util');
// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
// operating systems these days (capturing the result).
var REGEX_NEWLINE = /(\r?\n)/;
// Newline character code for charCodeAt() comparisons
var NEWLINE_CODE = 10;
// Private symbol for identifying `SourceNode`s when multiple versions of
// the source-map library are loaded. This MUST NOT CHANGE across
// versions!
var isSourceNode = "$$$isSourceNode$$$";
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine == null ? null : aLine;
this.column = aColumn == null ? null : aColumn;
this.source = aSource == null ? null : aSource;
this.name = aName == null ? null : aName;
this[isSourceNode] = true;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
* @param aRelativePath Optional. The path that relative sources in the
* SourceMapConsumer should be relative to.
*/
SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// All even indices of this array are one line of the generated code,
// while all odd indices are the newlines between two adjacent lines
// (since `REGEX_NEWLINE` captures its match).
// Processed fragments are removed from this array, by calling `shiftNextLine`.
var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
var shiftNextLine = function shiftNextLine() {
var lineContents = remainingLines.shift();
// The last line of a file might not have a newline.
var newLine = remainingLines.shift() || "";
return lineContents + newLine;
};
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1,
lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping !== null) {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
// Associate first line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
lastGeneratedLine++;
lastGeneratedColumn = 0;
// The remaining code is added without mapping
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
// No more remaining code, continue
lastMapping = mapping;
return;
}
}
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(shiftNextLine());
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
if (remainingLines.length > 0) {
if (lastMapping) {
// Associate the remaining code in the current line with "lastMapping"
addMappingWithCode(lastMapping, shiftNextLine());
}
// and add the remaining lines without any mapping
node.add(remainingLines.join(""));
}
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content != null) {
if (aRelativePath != null) {
sourceFile = util.join(aRelativePath, sourceFile);
}
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source;
node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
} else {
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length - 1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
} else if (aChunk[isSourceNode] || typeof aChunk === "string") {
this.children.unshift(aChunk);
} else {
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk[isSourceNode]) {
chunk.walk(aFn);
} else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len - 1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild[isSourceNode]) {
lastChild.replaceRight(aPattern, aReplacement);
} else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
} else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i][isSourceNode]) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null && original.line !== null && original.column !== null) {
if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
for (var idx = 0, length = chunk.length; idx < length; idx++) {
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
generated.line++;
generated.column = 0;
// Mappings end at eol
if (idx + 1 === length) {
lastOriginalSource = null;
sourceMappingActive = false;
} else if (sourceMappingActive) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
} else {
generated.column++;
}
}
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
},{"./source-map-generator":565,"./util":567}],567:[function(require,module,exports){
'use strict';
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
var dataUrlRegexp = /^data:.+\,.+$/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[2],
host: match[3],
port: match[4],
path: match[5]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = '';
if (aParsedUrl.scheme) {
url += aParsedUrl.scheme + ':';
}
url += '//';
if (aParsedUrl.auth) {
url += aParsedUrl.auth + '@';
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port;
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
/**
* Normalizes a path, or the path portion of a URL:
*
* - Replaces consecutive slashes with one slash.
* - Removes unnecessary '.' parts.
* - Removes unnecessary '<dir>/..' parts.
*
* Based on code in the Node.js 'path' core module.
*
* @param aPath The path or url to normalize.
*/
function normalize(aPath) {
var path = aPath;
var url = urlParse(aPath);
if (url) {
if (!url.path) {
return aPath;
}
path = url.path;
}
var isAbsolute = exports.isAbsolute(path);
var parts = path.split(/\/+/);
for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
part = parts[i];
if (part === '.') {
parts.splice(i, 1);
} else if (part === '..') {
up++;
} else if (up > 0) {
if (part === '') {
// The first part is blank if the path is absolute. Trying to go
// above the root is a no-op. Therefore we can remove all '..' parts
// directly after the root.
parts.splice(i + 1, up);
up = 0;
} else {
parts.splice(i, 2);
up--;
}
}
}
path = parts.join('/');
if (path === '') {
path = isAbsolute ? '/' : '.';
}
if (url) {
url.path = path;
return urlGenerate(url);
}
return path;
}
exports.normalize = normalize;
/**
* Joins two paths/URLs.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be joined with the root.
*
* - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
* scheme-relative URL: Then the scheme of aRoot, if any, is prepended
* first.
* - Otherwise aPath is a path. If aRoot is a URL, then its path portion
* is updated with the result and aRoot is returned. Otherwise the result
* is returned.
* - If aPath is absolute, the result is aPath.
* - Otherwise the two paths are joined with a slash.
* - Joining for example 'http://' and 'www.example.com' is also supported.
*/
function join(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
if (aPath === "") {
aPath = ".";
}
var aPathUrl = urlParse(aPath);
var aRootUrl = urlParse(aRoot);
if (aRootUrl) {
aRoot = aRootUrl.path || '/';
}
// `join(foo, '//www.example.org')`
if (aPathUrl && !aPathUrl.scheme) {
if (aRootUrl) {
aPathUrl.scheme = aRootUrl.scheme;
}
return urlGenerate(aPathUrl);
}
if (aPathUrl || aPath.match(dataUrlRegexp)) {
return aPath;
}
// `join('http://', 'www.example.com')`
if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
aRootUrl.host = aPath;
return urlGenerate(aRootUrl);
}
var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
if (aRootUrl) {
aRootUrl.path = joined;
return urlGenerate(aRootUrl);
}
return joined;
}
exports.join = join;
exports.isAbsolute = function (aPath) {
return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
};
/**
* Make a path relative to a URL or another path.
*
* @param aRoot The root path or URL.
* @param aPath The path or URL to be made relative to aRoot.
*/
function relative(aRoot, aPath) {
if (aRoot === "") {
aRoot = ".";
}
aRoot = aRoot.replace(/\/$/, '');
// It is possible for the path to be above the root. In this case, simply
// checking whether the root is a prefix of the path won't work. Instead, we
// need to remove components from the root one by one, until either we find
// a prefix that fits, or we run out of components to remove.
var level = 0;
while (aPath.indexOf(aRoot + '/') !== 0) {
var index = aRoot.lastIndexOf("/");
if (index < 0) {
return aPath;
}
// If the only part of the root that is left is the scheme (i.e. http://,
// file:///, etc.), one or more slashes (/), or simply nothing at all, we
// have exhausted all components, so the path is not relative to the root.
aRoot = aRoot.slice(0, index);
if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
return aPath;
}
++level;
}
// Make sure we add a "../" for each component we removed from the root.
return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
}
exports.relative = relative;
var supportsNullProto = function () {
var obj = Object.create(null);
return !('__proto__' in obj);
}();
function identity(s) {
return s;
}
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
if (isProtoString(aStr)) {
return '$' + aStr;
}
return aStr;
}
exports.toSetString = supportsNullProto ? identity : toSetString;
function fromSetString(aStr) {
if (isProtoString(aStr)) {
return aStr.slice(1);
}
return aStr;
}
exports.fromSetString = supportsNullProto ? identity : fromSetString;
function isProtoString(s) {
if (!s) {
return false;
}
var length = s.length;
if (length < 9 /* "__proto__".length */) {
return false;
}
if (s.charCodeAt(length - 1) !== 95 /* '_' */ || s.charCodeAt(length - 2) !== 95 /* '_' */ || s.charCodeAt(length - 3) !== 111 /* 'o' */ || s.charCodeAt(length - 4) !== 116 /* 't' */ || s.charCodeAt(length - 5) !== 111 /* 'o' */ || s.charCodeAt(length - 6) !== 114 /* 'r' */ || s.charCodeAt(length - 7) !== 112 /* 'p' */ || s.charCodeAt(length - 8) !== 95 /* '_' */ || s.charCodeAt(length - 9) !== 95 /* '_' */) {
return false;
}
for (var i = length - 10; i >= 0; i--) {
if (s.charCodeAt(i) !== 36 /* '$' */) {
return false;
}
}
return true;
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0 || onlyCompareOriginal) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings with deflated source and name indices where
* the generated positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0 || onlyCompareGenerated) {
return cmp;
}
cmp = mappingA.source - mappingB.source;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return mappingA.name - mappingB.name;
}
exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
function strcmp(aStr1, aStr2) {
if (aStr1 === aStr2) {
return 0;
}
if (aStr1 > aStr2) {
return 1;
}
return -1;
}
/**
* Comparator between two mappings with inflated source and name strings where
* the generated positions are compared.
*/
function compareByGeneratedPositionsInflated(mappingA, mappingB) {
var cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp !== 0) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp !== 0) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp !== 0) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
}
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
},{}],568:[function(require,module,exports){
'use strict';
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer;
exports.SourceNode = require('./lib/source-node').SourceNode;
},{"./lib/source-map-consumer":564,"./lib/source-map-generator":565,"./lib/source-node":566}]},{},[3])(3)
}); | Update autoprefixer.js with new Can I Use data
| vendor/autoprefixer.js | Update autoprefixer.js with new Can I Use data | <ide><path>endor/autoprefixer.js
<ide> },{}],155:[function(require,module,exports){
<ide> "use strict";
<ide>
<del>module.exports = { A: { A: { "2": "J C G TB", "8": "E", "292": "B A" }, B: { "292": "D X g H", "2049": "L" }, C: { "1": "2 4 t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB", "8": "O P Q R S T U V W u Y Z a b c d e f K h i", "584": "j k l m n o p q r w x v", "1025": "0 z" }, D: { "1": "8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T", "8": "U V W u", "200": "0 2 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "1025": "4" }, E: { "1": "A IB JB", "2": "7 F I CB EB", "8": "J C G E B FB GB HB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y", "200": "u Y Z a b c d e f K h i j k l m" }, G: { "1": "A bB", "2": "3 7 9 UB", "8": "G VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 F dB eB fB gB", "8": "3 hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "8": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "292": "B A" }, O: { "2": "jB" }, P: { "2": "I", "8": "F" }, Q: { "200": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Grid Layout" };
<add>module.exports = { A: { A: { "2": "J C G TB", "8": "E", "292": "B A" }, B: { "1": "L", "292": "D X g H" }, C: { "1": "2 4 t s", "2": "1 RB F I J C G E B A D X g H L M N PB OB", "8": "O P Q R S T U V W u Y Z a b c d e f K h i", "584": "j k l m n o p q r w x v", "1025": "0 z" }, D: { "1": "8 DB AB SB BB", "2": "F I J C G E B A D X g H L M N O P Q R S T", "8": "U V W u", "200": "0 2 Y Z a b c d e f K h i j k l m n o p q r w x v z t s", "1025": "4" }, E: { "1": "A IB JB", "2": "7 F I CB EB", "8": "J C G E B FB GB HB" }, F: { "1": "n o p q r", "2": "5 6 E A D H L M N O P Q R S T U V W KB LB MB NB QB y", "200": "u Y Z a b c d e f K h i j k l m" }, G: { "1": "A bB", "2": "3 7 9 UB", "8": "G VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "1": "s", "2": "1 F dB eB fB gB", "8": "3 hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D y", "8": "K" }, L: { "1": "8" }, M: { "1": "t" }, N: { "292": "B A" }, O: { "2": "jB" }, P: { "2": "I", "8": "F" }, Q: { "200": "kB" }, R: { "2": "lB" } }, B: 4, C: "CSS Grid Layout" };
<ide>
<ide> },{}],156:[function(require,module,exports){
<ide> "use strict";
<ide> },{}],257:[function(require,module,exports){
<ide> "use strict";
<ide>
<del>module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "194": "H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "322": "2 4 t s" }, D: { "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "194": "AB SB BB" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB y", "194": "q r" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "ES6 module" };
<add>module.exports = { A: { A: { "2": "J C G E B A TB" }, B: { "2": "D X g", "194": "H L" }, C: { "2": "0 1 RB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z PB OB", "322": "2 4 t s" }, D: { "1": "SB BB", "2": "0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s DB", "194": "AB" }, E: { "1": "A IB JB", "2": "7 F I J C G E B CB EB FB GB HB" }, F: { "2": "5 6 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB y", "194": "q r" }, G: { "1": "A bB", "2": "3 7 9 G UB VB WB XB YB ZB aB" }, H: { "2": "cB" }, I: { "2": "1 3 F s dB eB fB gB hB iB" }, J: { "2": "C B" }, K: { "2": "5 6 B A D K y" }, L: { "2": "8" }, M: { "2": "t" }, N: { "2": "B A" }, O: { "2": "jB" }, P: { "2": "F I" }, Q: { "2": "kB" }, R: { "2": "lB" } }, B: 1, C: "ES6 module" };
<ide>
<ide> },{}],258:[function(require,module,exports){
<ide> "use strict"; |
|
Java | agpl-3.0 | fe91c8ee7673d6df34ee8a35eb1adb2f78060558 | 0 | bisq-network/exchange,ManfredKarrer/exchange,bisq-network/exchange,bitsquare/bitsquare,bitsquare/bitsquare,ManfredKarrer/exchange | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bisq.core.dao.blockchain.parse;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Message;
import io.bisq.common.proto.persistable.PersistableEnvelope;
import io.bisq.common.proto.persistable.PersistenceProtoResolver;
import io.bisq.common.storage.Storage;
import io.bisq.common.util.FunctionalReadWriteLock;
import io.bisq.common.util.Tuple2;
import io.bisq.core.app.BisqEnvironment;
import io.bisq.core.dao.blockchain.exceptions.BlockNotConnectingException;
import io.bisq.core.dao.blockchain.vo.*;
import io.bisq.generated.protobuffer.PB;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
// Represents mutable state of BSQ chain data
// We get accessed the data from different threads so we need to make sure it is thread safe.
@Slf4j
public class BsqChainState implements PersistableEnvelope {
///////////////////////////////////////////////////////////////////////////////////////////
// Static
///////////////////////////////////////////////////////////////////////////////////////////
@VisibleForTesting
static int getSnapshotHeight(int genesisHeight, int height, int grid) {
return Math.round(Math.max(genesisHeight + 3 * grid, height) / grid) * grid - grid;
}
@VisibleForTesting
static boolean isSnapshotHeight(int genesisHeight, int height, int grid) {
return height % grid == 0 && height >= getSnapshotHeight(genesisHeight, height, grid);
}
private static final int SNAPSHOT_GRID = 100; // set high to deactivate
private static final int ISSUANCE_MATURITY = 144 * 30; // 30 days
//mainnet
// this tx has a lot of outputs
// https://blockchain.info/de/tx/ee921650ab3f978881b8fe291e0c025e0da2b7dc684003d7a03d9649dfee2e15
// BLOCK_HEIGHT 411779
// 411812 has 693 recursions
// BTC MAIN NET
// private static final String BTC_GENESIS_TX_ID = "b26371e2145f52c94b3d30713a9e38305bfc665fc27cd554e794b5e369d99ef5";
//private static final int BTC_GENESIS_BLOCK_HEIGHT = 461718; // 2017-04-13
private static final String BTC_GENESIS_TX_ID = "4371a1579bccc672231178cc5fe9fbb9366774d3bcbf21545a82f637f4b61a06";
private static final int BTC_GENESIS_BLOCK_HEIGHT = 473000; // 2017-06-26
// LTC MAIN NET
private static final String LTC_GENESIS_TX_ID = "44074e68c1168d67871b3e9af0e65d6d7c820b03ba15445df2c4089729985fb6";
private static final int LTC_GENESIS_BLOCK_HEIGHT = 1220170; // 2017-06-11
// 1186935
//1220127
// block 300000 2014-05-10
// block 350000 2015-03-30
// block 400000 2016-02-25
// block 450000 2017-01-25
// REG TEST
private static final String BTC_REG_TEST_GENESIS_TX_ID = "da216721fb915da499fe0400d08362f44b672096f37c74501c2f9bcaa7760656";
private static final int BTC_REG_TEST_GENESIS_BLOCK_HEIGHT = 363;
// LTC REG TEST
private static final String LTC_REG_TEST_GENESIS_TX_ID = "3551aa22fbf2e237df3d96d94f286aecc4f3109a7dcd873c5c51e30a6398172c";
private static final int LTC_REG_TEST_GENESIS_BLOCK_HEIGHT = 105;
// TEST NET
// TEST NET
// Phase 0 initial genesis tx 6.10.2017: 2f194230e23459a9211322c4b1c182cf3f367086e8059aca2f8f44e20dac527a
private static final String BTC_TEST_NET_GENESIS_TX_ID = "2f194230e23459a9211322c4b1c182cf3f367086e8059aca2f8f44e20dac527a";
private static final int BTC_TEST_NET_GENESIS_BLOCK_HEIGHT = 1209140;
private static final String LTC_TEST_NET_GENESIS_TX_ID = "not set";
private static final int LTC_TEST_NET_GENESIS_BLOCK_HEIGHT = 1;
// block 376078 has 2843 recursions and caused once a StackOverflowError, a second run worked. Took 1,2 sec.
///////////////////////////////////////////////////////////////////////////////////////////
// Instance fields
///////////////////////////////////////////////////////////////////////////////////////////
// Persisted data
private final LinkedList<BsqBlock> bsqBlocks;
private final Map<String, Tx> txMap;
private final Map<TxIdIndexTuple, TxOutput> unspentTxOutputsMap;
private final String genesisTxId;
private final int genesisBlockHeight;
private int chainHeadHeight = 0;
private Tx genesisTx;
// not impl in PB yet
private Set<Tuple2<Long, Integer>> compensationRequestFees;
private Set<Tuple2<Long, Integer>> votingFees;
// transient
@Nullable
transient private Storage<BsqChainState> storage;
@Nullable
transient private BsqChainState snapshotCandidate;
transient private final FunctionalReadWriteLock lock;
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////
@SuppressWarnings("WeakerAccess")
@Inject
public BsqChainState(PersistenceProtoResolver persistenceProtoResolver,
@Named(Storage.STORAGE_DIR) File storageDir) {
bsqBlocks = new LinkedList<>();
txMap = new HashMap<>();
unspentTxOutputsMap = new HashMap<>();
compensationRequestFees = new HashSet<>();
votingFees = new HashSet<>();
storage = new Storage<>(storageDir, persistenceProtoResolver);
switch (BisqEnvironment.getBaseCurrencyNetwork()) {
case BTC_MAINNET:
genesisTxId = BTC_GENESIS_TX_ID;
genesisBlockHeight = BTC_GENESIS_BLOCK_HEIGHT;
break;
case BTC_TESTNET:
genesisTxId = BTC_TEST_NET_GENESIS_TX_ID;
genesisBlockHeight = BTC_TEST_NET_GENESIS_BLOCK_HEIGHT;
break;
case BTC_REGTEST:
genesisTxId = BTC_REG_TEST_GENESIS_TX_ID;
genesisBlockHeight = BTC_REG_TEST_GENESIS_BLOCK_HEIGHT;
break;
case LTC_TESTNET:
genesisTxId = LTC_TEST_NET_GENESIS_TX_ID;
genesisBlockHeight = LTC_TEST_NET_GENESIS_BLOCK_HEIGHT;
break;
case LTC_REGTEST:
genesisTxId = LTC_REG_TEST_GENESIS_TX_ID;
genesisBlockHeight = LTC_REG_TEST_GENESIS_BLOCK_HEIGHT;
break;
case LTC_MAINNET:
default:
genesisTxId = LTC_GENESIS_TX_ID;
genesisBlockHeight = LTC_GENESIS_BLOCK_HEIGHT;
break;
}
lock = new FunctionalReadWriteLock(true);
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
private BsqChainState(LinkedList<BsqBlock> bsqBlocks,
Map<String, Tx> txMap,
Map<TxIdIndexTuple, TxOutput> unspentTxOutputsMap,
String genesisTxId,
int genesisBlockHeight,
int chainHeadHeight,
Tx genesisTx) {
this.bsqBlocks = bsqBlocks;
this.txMap = txMap;
this.unspentTxOutputsMap = unspentTxOutputsMap;
this.genesisTxId = genesisTxId;
this.genesisBlockHeight = genesisBlockHeight;
this.chainHeadHeight = chainHeadHeight;
this.genesisTx = genesisTx;
lock = new FunctionalReadWriteLock(true);
// not impl yet in PB
compensationRequestFees = new HashSet<>();
votingFees = new HashSet<>();
}
@Override
public Message toProtoMessage() {
return PB.PersistableEnvelope.newBuilder().setBsqChainState(getBsqChainStateBuilder()).build();
}
private PB.BsqChainState.Builder getBsqChainStateBuilder() {
return PB.BsqChainState.newBuilder()
.addAllBsqBlocks(bsqBlocks.stream()
.map(BsqBlock::toProtoMessage)
.collect(Collectors.toList()))
.putAllTxMap(txMap.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
v -> v.getValue().toProtoMessage())))
.putAllUnspentTxOutputsMap(unspentTxOutputsMap.entrySet().stream()
.collect(Collectors.toMap(k -> k.getKey().getAsString(),
v -> v.getValue().toProtoMessage())))
.setGenesisTxId(genesisTxId)
.setGenesisBlockHeight(genesisBlockHeight)
.setChainHeadHeight(chainHeadHeight)
.setGenesisTx(genesisTx.toProtoMessage());
}
public static PersistableEnvelope fromProto(PB.BsqChainState proto) {
return new BsqChainState(new LinkedList<>(proto.getBsqBlocksList().stream()
.map(BsqBlock::fromProto)
.collect(Collectors.toList())),
new HashMap<>(proto.getTxMapMap().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, v -> Tx.fromProto(v.getValue())))),
new HashMap<>(proto.getUnspentTxOutputsMapMap().entrySet().stream()
.collect(Collectors.toMap(k -> new TxIdIndexTuple(k.getKey()), v -> TxOutput.fromProto(v.getValue())))),
proto.getGenesisTxId(),
proto.getGenesisBlockHeight(),
proto.getChainHeadHeight(),
Tx.fromProto(proto.getGenesisTx())
);
}
///////////////////////////////////////////////////////////////////////////////////////////
// Public write access
///////////////////////////////////////////////////////////////////////////////////////////
public void applySnapshot() {
lock.write(() -> {
checkNotNull(storage, "storage must not be null");
BsqChainState snapshot = storage.initAndGetPersistedWithFileName("BsqChainState");
bsqBlocks.clear();
txMap.clear();
unspentTxOutputsMap.clear();
chainHeadHeight = 0;
genesisTx = null;
if (snapshot != null) {
log.info("applySnapshot snapshot.chainHeadHeight=" + snapshot.chainHeadHeight);
bsqBlocks.addAll(snapshot.bsqBlocks);
txMap.putAll(snapshot.txMap);
unspentTxOutputsMap.putAll(snapshot.unspentTxOutputsMap);
chainHeadHeight = snapshot.chainHeadHeight;
genesisTx = snapshot.genesisTx;
} else {
log.info("Try to apply snapshot but no stored snapshot available");
}
printDetails();
});
}
public void setCreateCompensationRequestFee(long fee, int blockHeight) {
lock.write(() -> compensationRequestFees.add(new Tuple2<>(fee, blockHeight)));
}
public void setVotingFee(long fee, int blockHeight) {
lock.write(() -> votingFees.add(new Tuple2<>(fee, blockHeight)));
}
///////////////////////////////////////////////////////////////////////////////////////////
// Package scope write access
///////////////////////////////////////////////////////////////////////////////////////////
void addBlock(BsqBlock block) throws BlockNotConnectingException {
try {
lock.write2(() -> {
if (!bsqBlocks.contains(block)) {
if (bsqBlocks.isEmpty() || (bsqBlocks.getLast().getHash().equals(block.getPreviousBlockHash()) &&
bsqBlocks.getLast().getHeight() + 1 == block.getHeight())) {
bsqBlocks.add(block);
block.getTxs().stream().forEach(BsqChainState.this::addTxToMap);
chainHeadHeight = block.getHeight();
maybeMakeSnapshot();
printDetails();
} else {
log.warn("addBlock called with a not connecting block:\n" +
"height()={}, hash()={}, head.height()={}, head.hash()={}",
block.getHeight(), block.getHash(), bsqBlocks.getLast().getHeight(), bsqBlocks.getLast().getHash());
throw new BlockNotConnectingException(block);
}
} else {
log.trace("We got that block already");
}
return null;
});
} catch (Exception e) {
throw new BlockNotConnectingException(block);
} catch (Throwable e) {
log.error(e.toString());
e.printStackTrace();
throw e;
}
}
void addTxToMap(Tx tx) {
lock.write(() -> txMap.put(tx.getId(), tx));
}
void addUnspentTxOutput(TxOutput txOutput) {
lock.write(() -> {
checkArgument(txOutput.isVerified(), "txOutput must be verified at addUnspentTxOutput");
unspentTxOutputsMap.put(txOutput.getTxIdIndexTuple(), txOutput);
});
}
void removeUnspentTxOutput(TxOutput txOutput) {
lock.write(() -> unspentTxOutputsMap.remove(txOutput.getTxIdIndexTuple()));
}
void setGenesisTx(Tx tx) {
lock.write(() -> genesisTx = tx);
}
///////////////////////////////////////////////////////////////////////////////////////////
// Public read access
///////////////////////////////////////////////////////////////////////////////////////////
public String getGenesisTxId() {
return genesisTxId;
}
public int getGenesisBlockHeight() {
return lock.read(() -> genesisBlockHeight);
}
public BsqChainState getClone() {
return getClone(this);
}
public BsqChainState getClone(BsqChainState bsqChainState) {
return lock.read(() -> (BsqChainState) BsqChainState.fromProto(bsqChainState.getBsqChainStateBuilder().build()));
}
public boolean containsBlock(BsqBlock bsqBlock) {
return lock.read(() -> bsqBlocks.contains(bsqBlock));
}
Optional<TxOutput> getUnspentTxOutput(TxIdIndexTuple txIdIndexTuple) {
return lock.read(() -> unspentTxOutputsMap.entrySet().stream()
.filter(e -> e.getKey().equals(txIdIndexTuple))
.map(Map.Entry::getValue).findAny());
}
public boolean isTxOutputSpendable(String txId, int index) {
return lock.read(() -> getSpendableTxOutput(txId, index).isPresent());
}
public boolean hasTxBurntFee(String txId) {
return lock.read(() -> getTx(txId).map(Tx::getBurntFee).filter(fee -> fee > 0).isPresent());
}
public Optional<TxType> getTxType(String txId) {
return lock.read(() -> getTx(txId).map(Tx::getTxType));
}
public boolean containsTx(String txId) {
return lock.read(() -> getTx(txId).isPresent());
}
public int getChainHeadHeight() {
return lock.read(() -> chainHeadHeight);
}
// Only used for Json Exporter
public Map<String, Tx> getTxMap() {
return lock.read(() -> txMap);
}
public List<BsqBlock> getResettedBlocksFrom(int fromBlockHeight) {
return lock.read(() -> {
BsqChainState clone = getClone();
List<BsqBlock> filtered = clone.bsqBlocks.stream()
.filter(block -> block.getHeight() >= fromBlockHeight)
.collect(Collectors.toList());
filtered.stream().forEach(BsqBlock::reset);
return filtered;
});
}
///////////////////////////////////////////////////////////////////////////////////////////
// Package scope read access
///////////////////////////////////////////////////////////////////////////////////////////
Optional<TxOutput> getSpendableTxOutput(String txId, int index) {
return lock.read(() -> getSpendableTxOutput(new TxIdIndexTuple(txId, index)));
}
Optional<TxOutput> getSpendableTxOutput(TxIdIndexTuple txIdIndexTuple) {
return lock.read(() -> getUnspentTxOutput(txIdIndexTuple)
.filter(this::isTxOutputMature));
}
long getCreateCompensationRequestFee(int blockHeight) {
return lock.read(() -> {
long fee = -1;
for (Tuple2<Long, Integer> feeAtHeight : compensationRequestFees) {
if (feeAtHeight.second <= blockHeight)
fee = feeAtHeight.first;
}
checkArgument(fee > -1, "compensationRequestFees must be set");
return fee;
});
}
//TODO not impl yet
boolean isCompensationRequestPeriodValid(int blockHeight) {
return lock.read(() -> true);
}
long getVotingFee(int blockHeight) {
return lock.read(() -> {
long fee = -1;
for (Tuple2<Long, Integer> feeAtHeight : votingFees) {
if (feeAtHeight.second <= blockHeight)
fee = feeAtHeight.first;
}
checkArgument(fee > -1, "compensationRequestFees must be set");
return fee;
});
}
//TODO not impl yet
boolean isVotingPeriodValid(int blockHeight) {
return lock.read(() -> true);
}
boolean existsCompensationRequestBtcAddress(String btcAddress) {
return lock.read(() -> getAllTxOutputs().stream()
.filter(txOutput -> txOutput.isCompensationRequestBtcOutput() &&
txOutput.getAddress().equals(btcAddress))
.findAny()
.isPresent());
}
Set<TxOutput> findSponsoringBtcOutputsWithSameBtcAddress(String btcAddress) {
return lock.read(() -> getAllTxOutputs().stream()
.filter(txOutput -> txOutput.isSponsoringBtcOutput() &&
txOutput.getAddress().equals(btcAddress))
.collect(Collectors.toSet()));
}
//TODO
// for genesis we dont need it and for issuance we need more implemented first
boolean isTxOutputMature(TxOutput spendingTxOutput) {
return lock.read(() -> true);
}
///////////////////////////////////////////////////////////////////////////////////////////
// Private
///////////////////////////////////////////////////////////////////////////////////////////
private Optional<Tx> getTx(String txId) {
return lock.read(() -> txMap.get(txId) != null ? Optional.of(txMap.get(txId)) : Optional.<Tx>empty());
}
private boolean isSnapshotHeight(int height) {
return isSnapshotHeight(genesisBlockHeight, height, SNAPSHOT_GRID);
}
private void maybeMakeSnapshot() {
lock.read(() -> {
if (isSnapshotHeight(getChainHeadHeight()) &&
(snapshotCandidate == null ||
snapshotCandidate.chainHeadHeight != getChainHeadHeight())) {
// At trigger event we store the latest snapshotCandidate to disc
if (snapshotCandidate != null) {
// We clone because storage is in a threaded context
final BsqChainState cloned = getClone(snapshotCandidate);
checkNotNull(storage, "storage must nto be null");
storage.queueUpForSave(cloned);
// dont access cloned anymore with methods as locks are transient!
log.info("Saved snapshotCandidate to Disc at height " + cloned.chainHeadHeight);
}
// Now we clone and keep it in memory for the next trigger
snapshotCandidate = getClone(this);
// dont access cloned anymore with methods as locks are transient!
log.debug("Cloned new snapshotCandidate at height " + snapshotCandidate.chainHeadHeight);
}
});
}
private Set<TxOutput> getAllTxOutputs() {
return txMap.values().stream()
.flatMap(tx -> tx.getOutputs().stream())
.collect(Collectors.toSet());
}
private void printDetails() {
log.debug("\nchainHeadHeight={}\n" +
" blocks.size={}\n" +
" txMap.size={}\n" +
" unspentTxOutputsMap.size={}\n" +
" compensationRequestFees.size={}\n" +
" votingFees.size={}\n" +
getChainHeadHeight(),
bsqBlocks.size(),
txMap.size(),
unspentTxOutputsMap.size(),
compensationRequestFees.size(),
votingFees.size());
}
}
| core/src/main/java/io/bisq/core/dao/blockchain/parse/BsqChainState.java | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bisq.core.dao.blockchain.parse;
import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.Message;
import io.bisq.common.proto.persistable.PersistableEnvelope;
import io.bisq.common.proto.persistable.PersistenceProtoResolver;
import io.bisq.common.storage.Storage;
import io.bisq.common.util.FunctionalReadWriteLock;
import io.bisq.common.util.Tuple2;
import io.bisq.core.app.BisqEnvironment;
import io.bisq.core.dao.blockchain.exceptions.BlockNotConnectingException;
import io.bisq.core.dao.blockchain.vo.*;
import io.bisq.generated.protobuffer.PB;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
// Represents mutable state of BSQ chain data
// We get accessed the data from different threads so we need to make sure it is thread safe.
@Slf4j
public class BsqChainState implements PersistableEnvelope {
///////////////////////////////////////////////////////////////////////////////////////////
// Static
///////////////////////////////////////////////////////////////////////////////////////////
@VisibleForTesting
static int getSnapshotHeight(int genesisHeight, int height, int grid) {
return Math.round(Math.max(genesisHeight + 3 * grid, height) / grid) * grid - grid;
}
@VisibleForTesting
static boolean isSnapshotHeight(int genesisHeight, int height, int grid) {
return height % grid == 0 && height >= getSnapshotHeight(genesisHeight, height, grid);
}
private static final int SNAPSHOT_GRID = 100; // set high to deactivate
private static final int ISSUANCE_MATURITY = 144 * 30; // 30 days
//mainnet
// this tx has a lot of outputs
// https://blockchain.info/de/tx/ee921650ab3f978881b8fe291e0c025e0da2b7dc684003d7a03d9649dfee2e15
// BLOCK_HEIGHT 411779
// 411812 has 693 recursions
// BTC MAIN NET
// private static final String BTC_GENESIS_TX_ID = "b26371e2145f52c94b3d30713a9e38305bfc665fc27cd554e794b5e369d99ef5";
//private static final int BTC_GENESIS_BLOCK_HEIGHT = 461718; // 2017-04-13
private static final String BTC_GENESIS_TX_ID = "4371a1579bccc672231178cc5fe9fbb9366774d3bcbf21545a82f637f4b61a06";
private static final int BTC_GENESIS_BLOCK_HEIGHT = 473000; // 2017-06-26
// LTC MAIN NET
private static final String LTC_GENESIS_TX_ID = "44074e68c1168d67871b3e9af0e65d6d7c820b03ba15445df2c4089729985fb6";
private static final int LTC_GENESIS_BLOCK_HEIGHT = 1220170; // 2017-06-11
// 1186935
//1220127
// block 300000 2014-05-10
// block 350000 2015-03-30
// block 400000 2016-02-25
// block 450000 2017-01-25
// REG TEST
private static final String BTC_REG_TEST_GENESIS_TX_ID = "da216721fb915da499fe0400d08362f44b672096f37c74501c2f9bcaa7760656";
private static final int BTC_REG_TEST_GENESIS_BLOCK_HEIGHT = 363;
// LTC REG TEST
private static final String LTC_REG_TEST_GENESIS_TX_ID = "3551aa22fbf2e237df3d96d94f286aecc4f3109a7dcd873c5c51e30a6398172c";
private static final int LTC_REG_TEST_GENESIS_BLOCK_HEIGHT = 105;
// TEST NET
// 0.5 BTC to grazcoin ms4ewGfJEv5RTnBD2moDoP5Kp1uJJwDGSX
// 0.3 BTC to alice: myjn5JVuQLN9S4QwGzY4VrD86819Zc2uhj
// 0.2BTC to bob: mx3xo655TAjC5r7ScuVEU8b6FMLomnKSeX
private static final String BTC_TEST_NET_GENESIS_TX_ID = "e360c3c77f43d53cbbf3dc8064c888a10310930a6427770ce4c8ead388edf17c";
private static final int BTC_TEST_NET_GENESIS_BLOCK_HEIGHT = 1119668;
private static final String LTC_TEST_NET_GENESIS_TX_ID = "not set";
private static final int LTC_TEST_NET_GENESIS_BLOCK_HEIGHT = 1;
// block 376078 has 2843 recursions and caused once a StackOverflowError, a second run worked. Took 1,2 sec.
///////////////////////////////////////////////////////////////////////////////////////////
// Instance fields
///////////////////////////////////////////////////////////////////////////////////////////
// Persisted data
private final LinkedList<BsqBlock> bsqBlocks;
private final Map<String, Tx> txMap;
private final Map<TxIdIndexTuple, TxOutput> unspentTxOutputsMap;
private final String genesisTxId;
private final int genesisBlockHeight;
private int chainHeadHeight = 0;
private Tx genesisTx;
// not impl in PB yet
private Set<Tuple2<Long, Integer>> compensationRequestFees;
private Set<Tuple2<Long, Integer>> votingFees;
// transient
@Nullable
transient private Storage<BsqChainState> storage;
@Nullable
transient private BsqChainState snapshotCandidate;
transient private final FunctionalReadWriteLock lock;
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////////////////////////////////////
@SuppressWarnings("WeakerAccess")
@Inject
public BsqChainState(PersistenceProtoResolver persistenceProtoResolver,
@Named(Storage.STORAGE_DIR) File storageDir) {
bsqBlocks = new LinkedList<>();
txMap = new HashMap<>();
unspentTxOutputsMap = new HashMap<>();
compensationRequestFees = new HashSet<>();
votingFees = new HashSet<>();
storage = new Storage<>(storageDir, persistenceProtoResolver);
switch (BisqEnvironment.getBaseCurrencyNetwork()) {
case BTC_MAINNET:
genesisTxId = BTC_GENESIS_TX_ID;
genesisBlockHeight = BTC_GENESIS_BLOCK_HEIGHT;
break;
case BTC_TESTNET:
genesisTxId = BTC_TEST_NET_GENESIS_TX_ID;
genesisBlockHeight = BTC_TEST_NET_GENESIS_BLOCK_HEIGHT;
break;
case BTC_REGTEST:
genesisTxId = BTC_REG_TEST_GENESIS_TX_ID;
genesisBlockHeight = BTC_REG_TEST_GENESIS_BLOCK_HEIGHT;
break;
case LTC_TESTNET:
genesisTxId = LTC_TEST_NET_GENESIS_TX_ID;
genesisBlockHeight = LTC_TEST_NET_GENESIS_BLOCK_HEIGHT;
break;
case LTC_REGTEST:
genesisTxId = LTC_REG_TEST_GENESIS_TX_ID;
genesisBlockHeight = LTC_REG_TEST_GENESIS_BLOCK_HEIGHT;
break;
case LTC_MAINNET:
default:
genesisTxId = LTC_GENESIS_TX_ID;
genesisBlockHeight = LTC_GENESIS_BLOCK_HEIGHT;
break;
}
lock = new FunctionalReadWriteLock(true);
}
///////////////////////////////////////////////////////////////////////////////////////////
// PROTO BUFFER
///////////////////////////////////////////////////////////////////////////////////////////
private BsqChainState(LinkedList<BsqBlock> bsqBlocks,
Map<String, Tx> txMap,
Map<TxIdIndexTuple, TxOutput> unspentTxOutputsMap,
String genesisTxId,
int genesisBlockHeight,
int chainHeadHeight,
Tx genesisTx) {
this.bsqBlocks = bsqBlocks;
this.txMap = txMap;
this.unspentTxOutputsMap = unspentTxOutputsMap;
this.genesisTxId = genesisTxId;
this.genesisBlockHeight = genesisBlockHeight;
this.chainHeadHeight = chainHeadHeight;
this.genesisTx = genesisTx;
lock = new FunctionalReadWriteLock(true);
// not impl yet in PB
compensationRequestFees = new HashSet<>();
votingFees = new HashSet<>();
}
@Override
public Message toProtoMessage() {
return PB.PersistableEnvelope.newBuilder().setBsqChainState(getBsqChainStateBuilder()).build();
}
private PB.BsqChainState.Builder getBsqChainStateBuilder() {
return PB.BsqChainState.newBuilder()
.addAllBsqBlocks(bsqBlocks.stream()
.map(BsqBlock::toProtoMessage)
.collect(Collectors.toList()))
.putAllTxMap(txMap.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
v -> v.getValue().toProtoMessage())))
.putAllUnspentTxOutputsMap(unspentTxOutputsMap.entrySet().stream()
.collect(Collectors.toMap(k -> k.getKey().getAsString(),
v -> v.getValue().toProtoMessage())))
.setGenesisTxId(genesisTxId)
.setGenesisBlockHeight(genesisBlockHeight)
.setChainHeadHeight(chainHeadHeight)
.setGenesisTx(genesisTx.toProtoMessage());
}
public static PersistableEnvelope fromProto(PB.BsqChainState proto) {
return new BsqChainState(new LinkedList<>(proto.getBsqBlocksList().stream()
.map(BsqBlock::fromProto)
.collect(Collectors.toList())),
new HashMap<>(proto.getTxMapMap().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, v -> Tx.fromProto(v.getValue())))),
new HashMap<>(proto.getUnspentTxOutputsMapMap().entrySet().stream()
.collect(Collectors.toMap(k -> new TxIdIndexTuple(k.getKey()), v -> TxOutput.fromProto(v.getValue())))),
proto.getGenesisTxId(),
proto.getGenesisBlockHeight(),
proto.getChainHeadHeight(),
Tx.fromProto(proto.getGenesisTx())
);
}
///////////////////////////////////////////////////////////////////////////////////////////
// Public write access
///////////////////////////////////////////////////////////////////////////////////////////
public void applySnapshot() {
lock.write(() -> {
checkNotNull(storage, "storage must not be null");
BsqChainState snapshot = storage.initAndGetPersistedWithFileName("BsqChainState");
bsqBlocks.clear();
txMap.clear();
unspentTxOutputsMap.clear();
chainHeadHeight = 0;
genesisTx = null;
if (snapshot != null) {
log.info("applySnapshot snapshot.chainHeadHeight=" + snapshot.chainHeadHeight);
bsqBlocks.addAll(snapshot.bsqBlocks);
txMap.putAll(snapshot.txMap);
unspentTxOutputsMap.putAll(snapshot.unspentTxOutputsMap);
chainHeadHeight = snapshot.chainHeadHeight;
genesisTx = snapshot.genesisTx;
} else {
log.info("Try to apply snapshot but no stored snapshot available");
}
printDetails();
});
}
public void setCreateCompensationRequestFee(long fee, int blockHeight) {
lock.write(() -> compensationRequestFees.add(new Tuple2<>(fee, blockHeight)));
}
public void setVotingFee(long fee, int blockHeight) {
lock.write(() -> votingFees.add(new Tuple2<>(fee, blockHeight)));
}
///////////////////////////////////////////////////////////////////////////////////////////
// Package scope write access
///////////////////////////////////////////////////////////////////////////////////////////
void addBlock(BsqBlock block) throws BlockNotConnectingException {
try {
lock.write2(() -> {
if (!bsqBlocks.contains(block)) {
if (bsqBlocks.isEmpty() || (bsqBlocks.getLast().getHash().equals(block.getPreviousBlockHash()) &&
bsqBlocks.getLast().getHeight() + 1 == block.getHeight())) {
bsqBlocks.add(block);
block.getTxs().stream().forEach(BsqChainState.this::addTxToMap);
chainHeadHeight = block.getHeight();
maybeMakeSnapshot();
printDetails();
} else {
log.warn("addBlock called with a not connecting block:\n" +
"height()={}, hash()={}, head.height()={}, head.hash()={}",
block.getHeight(), block.getHash(), bsqBlocks.getLast().getHeight(), bsqBlocks.getLast().getHash());
throw new BlockNotConnectingException(block);
}
} else {
log.trace("We got that block already");
}
return null;
});
} catch (Exception e) {
throw new BlockNotConnectingException(block);
} catch (Throwable e) {
log.error(e.toString());
e.printStackTrace();
throw e;
}
}
void addTxToMap(Tx tx) {
lock.write(() -> txMap.put(tx.getId(), tx));
}
void addUnspentTxOutput(TxOutput txOutput) {
lock.write(() -> {
checkArgument(txOutput.isVerified(), "txOutput must be verified at addUnspentTxOutput");
unspentTxOutputsMap.put(txOutput.getTxIdIndexTuple(), txOutput);
});
}
void removeUnspentTxOutput(TxOutput txOutput) {
lock.write(() -> unspentTxOutputsMap.remove(txOutput.getTxIdIndexTuple()));
}
void setGenesisTx(Tx tx) {
lock.write(() -> genesisTx = tx);
}
///////////////////////////////////////////////////////////////////////////////////////////
// Public read access
///////////////////////////////////////////////////////////////////////////////////////////
public String getGenesisTxId() {
return genesisTxId;
}
public int getGenesisBlockHeight() {
return lock.read(() -> genesisBlockHeight);
}
public BsqChainState getClone() {
return getClone(this);
}
public BsqChainState getClone(BsqChainState bsqChainState) {
return lock.read(() -> (BsqChainState) BsqChainState.fromProto(bsqChainState.getBsqChainStateBuilder().build()));
}
public boolean containsBlock(BsqBlock bsqBlock) {
return lock.read(() -> bsqBlocks.contains(bsqBlock));
}
Optional<TxOutput> getUnspentTxOutput(TxIdIndexTuple txIdIndexTuple) {
return lock.read(() -> unspentTxOutputsMap.entrySet().stream()
.filter(e -> e.getKey().equals(txIdIndexTuple))
.map(Map.Entry::getValue).findAny());
}
public boolean isTxOutputSpendable(String txId, int index) {
return lock.read(() -> getSpendableTxOutput(txId, index).isPresent());
}
public boolean hasTxBurntFee(String txId) {
return lock.read(() -> getTx(txId).map(Tx::getBurntFee).filter(fee -> fee > 0).isPresent());
}
public Optional<TxType> getTxType(String txId) {
return lock.read(() -> getTx(txId).map(Tx::getTxType));
}
public boolean containsTx(String txId) {
return lock.read(() -> getTx(txId).isPresent());
}
public int getChainHeadHeight() {
return lock.read(() -> chainHeadHeight);
}
// Only used for Json Exporter
public Map<String, Tx> getTxMap() {
return lock.read(() -> txMap);
}
public List<BsqBlock> getResettedBlocksFrom(int fromBlockHeight) {
return lock.read(() -> {
BsqChainState clone = getClone();
List<BsqBlock> filtered = clone.bsqBlocks.stream()
.filter(block -> block.getHeight() >= fromBlockHeight)
.collect(Collectors.toList());
filtered.stream().forEach(BsqBlock::reset);
return filtered;
});
}
///////////////////////////////////////////////////////////////////////////////////////////
// Package scope read access
///////////////////////////////////////////////////////////////////////////////////////////
Optional<TxOutput> getSpendableTxOutput(String txId, int index) {
return lock.read(() -> getSpendableTxOutput(new TxIdIndexTuple(txId, index)));
}
Optional<TxOutput> getSpendableTxOutput(TxIdIndexTuple txIdIndexTuple) {
return lock.read(() -> getUnspentTxOutput(txIdIndexTuple)
.filter(this::isTxOutputMature));
}
long getCreateCompensationRequestFee(int blockHeight) {
return lock.read(() -> {
long fee = -1;
for (Tuple2<Long, Integer> feeAtHeight : compensationRequestFees) {
if (feeAtHeight.second <= blockHeight)
fee = feeAtHeight.first;
}
checkArgument(fee > -1, "compensationRequestFees must be set");
return fee;
});
}
//TODO not impl yet
boolean isCompensationRequestPeriodValid(int blockHeight) {
return lock.read(() -> true);
}
long getVotingFee(int blockHeight) {
return lock.read(() -> {
long fee = -1;
for (Tuple2<Long, Integer> feeAtHeight : votingFees) {
if (feeAtHeight.second <= blockHeight)
fee = feeAtHeight.first;
}
checkArgument(fee > -1, "compensationRequestFees must be set");
return fee;
});
}
//TODO not impl yet
boolean isVotingPeriodValid(int blockHeight) {
return lock.read(() -> true);
}
boolean existsCompensationRequestBtcAddress(String btcAddress) {
return lock.read(() -> getAllTxOutputs().stream()
.filter(txOutput -> txOutput.isCompensationRequestBtcOutput() &&
txOutput.getAddress().equals(btcAddress))
.findAny()
.isPresent());
}
Set<TxOutput> findSponsoringBtcOutputsWithSameBtcAddress(String btcAddress) {
return lock.read(() -> getAllTxOutputs().stream()
.filter(txOutput -> txOutput.isSponsoringBtcOutput() &&
txOutput.getAddress().equals(btcAddress))
.collect(Collectors.toSet()));
}
//TODO
// for genesis we dont need it and for issuance we need more implemented first
boolean isTxOutputMature(TxOutput spendingTxOutput) {
return lock.read(() -> true);
}
///////////////////////////////////////////////////////////////////////////////////////////
// Private
///////////////////////////////////////////////////////////////////////////////////////////
private Optional<Tx> getTx(String txId) {
return lock.read(() -> txMap.get(txId) != null ? Optional.of(txMap.get(txId)) : Optional.<Tx>empty());
}
private boolean isSnapshotHeight(int height) {
return isSnapshotHeight(genesisBlockHeight, height, SNAPSHOT_GRID);
}
private void maybeMakeSnapshot() {
lock.read(() -> {
if (isSnapshotHeight(getChainHeadHeight()) &&
(snapshotCandidate == null ||
snapshotCandidate.chainHeadHeight != getChainHeadHeight())) {
// At trigger event we store the latest snapshotCandidate to disc
if (snapshotCandidate != null) {
// We clone because storage is in a threaded context
final BsqChainState cloned = getClone(snapshotCandidate);
checkNotNull(storage, "storage must nto be null");
storage.queueUpForSave(cloned);
// dont access cloned anymore with methods as locks are transient!
log.info("Saved snapshotCandidate to Disc at height " + cloned.chainHeadHeight);
}
// Now we clone and keep it in memory for the next trigger
snapshotCandidate = getClone(this);
// dont access cloned anymore with methods as locks are transient!
log.debug("Cloned new snapshotCandidate at height " + snapshotCandidate.chainHeadHeight);
}
});
}
private Set<TxOutput> getAllTxOutputs() {
return txMap.values().stream()
.flatMap(tx -> tx.getOutputs().stream())
.collect(Collectors.toSet());
}
private void printDetails() {
log.debug("\nchainHeadHeight={}\n" +
" blocks.size={}\n" +
" txMap.size={}\n" +
" unspentTxOutputsMap.size={}\n" +
" compensationRequestFees.size={}\n" +
" votingFees.size={}\n" +
getChainHeadHeight(),
bsqBlocks.size(),
txMap.size(),
unspentTxOutputsMap.size(),
compensationRequestFees.size(),
votingFees.size());
}
}
| Set phase 0 genesis tx
| core/src/main/java/io/bisq/core/dao/blockchain/parse/BsqChainState.java | Set phase 0 genesis tx | <ide><path>ore/src/main/java/io/bisq/core/dao/blockchain/parse/BsqChainState.java
<ide>
<ide>
<ide> // TEST NET
<del> // 0.5 BTC to grazcoin ms4ewGfJEv5RTnBD2moDoP5Kp1uJJwDGSX
<del> // 0.3 BTC to alice: myjn5JVuQLN9S4QwGzY4VrD86819Zc2uhj
<del> // 0.2BTC to bob: mx3xo655TAjC5r7ScuVEU8b6FMLomnKSeX
<del> private static final String BTC_TEST_NET_GENESIS_TX_ID = "e360c3c77f43d53cbbf3dc8064c888a10310930a6427770ce4c8ead388edf17c";
<del> private static final int BTC_TEST_NET_GENESIS_BLOCK_HEIGHT = 1119668;
<add> // TEST NET
<add> // Phase 0 initial genesis tx 6.10.2017: 2f194230e23459a9211322c4b1c182cf3f367086e8059aca2f8f44e20dac527a
<add> private static final String BTC_TEST_NET_GENESIS_TX_ID = "2f194230e23459a9211322c4b1c182cf3f367086e8059aca2f8f44e20dac527a";
<add> private static final int BTC_TEST_NET_GENESIS_BLOCK_HEIGHT = 1209140;
<ide>
<ide> private static final String LTC_TEST_NET_GENESIS_TX_ID = "not set";
<ide> private static final int LTC_TEST_NET_GENESIS_BLOCK_HEIGHT = 1; |
|
Java | apache-2.0 | 9456e891633fa8f6fc5865dc1168728e9239c936 | 0 | cuba-platform/cuba,cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,cuba-platform/cuba,dimone-kun/cuba | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.
*
*/
package com.haulmont.cuba.core.global;
import com.haulmont.chile.core.model.Instance;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.MetaProperty;
import com.haulmont.chile.core.model.MetaPropertyPath;
import com.haulmont.cuba.core.entity.annotation.LocalizedValue;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
/**
* Utility class to provide common functionality related to localized messages.
* <br> Implemented as Spring bean to allow extension in application projects.
* <br> A reference to this class can be obtained either via DI or by
* {@link com.haulmont.cuba.core.global.Messages#getTools()} method.
*/
@Component(MessageTools.NAME)
public class MessageTools {
/**
* Prefix defining that the string is actually a key in a localized messages pack.
*/
public static final String MARK = "msg://";
public static final String MAIN_MARK = "mainMsg://";
public static final String NAME = "cuba_MessageTools";
private final Logger log = LoggerFactory.getLogger(MessageTools.class);
protected volatile Boolean useLocaleLanguageOnly;
@Inject
protected Messages messages;
@Inject
protected Metadata metadata;
@Inject
protected ExtendedEntities extendedEntities;
protected GlobalConfig globalConfig;
@Inject
public MessageTools(Configuration configuration) {
globalConfig = configuration.getConfig(GlobalConfig.class);
}
/**
* Get localized message by reference provided in the full format.
* @param ref reference to message in the following format: {@code msg://message_pack/message_id}
* @return localized message or input string itself if it doesn't begin with {@code msg://}
*/
public String loadString(String ref) {
return loadString(null, ref);
}
/**
* Get localized message by reference provided in the full format.
* @param ref reference to message in the following format: {@code msg://message_pack/message_id}
* @return localized message or input string itself if it doesn't begin with {@code msg://}
*/
public String loadString(String ref, Locale locale) {
return loadString(null, ref, locale);
}
/**
* Get localized message by reference provided in full or brief format.
* @param messagesPack messages pack to use if the second parameter is in brief format
* @param ref reference to message in the following format:
* <ul>
* <li>Full: {@code msg://message_pack/message_id}
* <li>Brief: {@code msg://message_id}, in this case the first parameter is taken into account
* <li>Message from a main messages pack: {@code mainMsg://message_id}
* </ul>
* @return localized message or input string itself if it doesn't begin with {@code msg://} or {@code mainMsg://}
*/
@Nullable
public String loadString(@Nullable String messagesPack, @Nullable String ref) {
return loadString(messagesPack, ref, null);
}
/**
* Get localized message by reference provided in full or brief format.
* @param messagesPack messages pack to use if the second parameter is in brief format
* @param ref reference to message in the following format:
* @param locale locale
* <ul>
* <li>Full: {@code msg://message_pack/message_id}
* <li>Brief: {@code msg://message_id}, in this case the first parameter is taken into account
* <li>Message from a main messages pack: {@code mainMsg://message_id}
* </ul>
* @return localized message or input string itself if it doesn't begin with {@code msg://} or {@code mainMsg://}
*/
@Nullable
public String loadString(@Nullable String messagesPack, @Nullable String ref, @Nullable Locale locale) {
if (ref != null) {
if (ref.startsWith(MARK)) {
String path = ref.substring(6);
final String[] strings = path.split("/");
if (strings.length == 1 && messagesPack != null) {
if (locale == null) {
ref = messages.getMessage(messagesPack, strings[0]);
} else {
ref = messages.getMessage(messagesPack, strings[0], locale);
}
} else if (strings.length == 2) {
if (locale == null) {
ref = messages.getMessage(strings[0], strings[1]);
} else {
ref = messages.getMessage(strings[0], strings[1], locale);
}
} else {
throw new UnsupportedOperationException("Unsupported resource string format: '" + ref
+ "', messagesPack=" + messagesPack);
}
} else if (ref.startsWith(MAIN_MARK)) {
String path = ref.substring(10);
if (locale == null) {
return messages.getMainMessage(path);
} else {
return messages.getMainMessage(path, locale);
}
}
}
return ref;
}
/**
* @return a localized name of an entity. Messages pack must be located in the same package as entity.
*/
public String getEntityCaption(MetaClass metaClass) {
return getEntityCaption(metaClass, null);
}
/**
* @return a localized name of an entity with given locale or default if null. Messages pack must be located in the same package as entity.
*/
public String getEntityCaption(MetaClass metaClass, @Nullable Locale locale) {
Function<MetaClass, String> getMessage = locale != null ?
mc -> messages.getMessage(mc.getJavaClass(), mc.getJavaClass().getSimpleName(), locale) :
mc -> messages.getMessage(mc.getJavaClass(), mc.getJavaClass().getSimpleName());
String message = getMessage.apply(metaClass);
if (metaClass.getJavaClass().getSimpleName().equals(message)) {
MetaClass original = metadata.getExtendedEntities().getOriginalMetaClass(metaClass);
if (original != null)
return getMessage.apply(original);
}
return message;
}
/**
* @return a detailed localized name of an entity. Messages pack must be located in the same package as entity.
*/
public String getDetailedEntityCaption(MetaClass metaClass) {
return getDetailedEntityCaption(metaClass, null);
}
/**
* @return a detailed localized name of an entity with given locale or default if null. Messages pack must be located in the same package as entity.
*/
public String getDetailedEntityCaption(MetaClass metaClass, @Nullable Locale locale) {
return getEntityCaption(metaClass, locale) + " (" + metaClass.getName() + ")";
}
/**
* Get localized name of an entity property. Messages pack must be located in the same package as entity.
* @param metaClass MetaClass containing the property
* @param propertyName property's name
* @return localized name
*/
public String getPropertyCaption(MetaClass metaClass, String propertyName) {
return getPropertyCaption(metaClass, propertyName, null);
}
/**
* Get localized name of an entity property. Messages pack must be located in the same package as entity.
*
* @param metaClass MetaClass containing the property
* @param propertyName property's name
* @param locale locale, if value is null locale of current user is used
* @return localized name
*/
public String getPropertyCaption(MetaClass metaClass, String propertyName, @Nullable Locale locale) {
Class originalClass = extendedEntities.getOriginalClass(metaClass);
Class<?> ownClass = originalClass != null ? originalClass : metaClass.getJavaClass();
String className = ownClass.getSimpleName();
String key = className + "." + propertyName;
String message;
if (locale == null) {
message = messages.getMessage(ownClass, key);
} else {
message = messages.getMessage(ownClass, key, locale);
}
if (!message.equals(key)) {
return message;
}
MetaPropertyPath propertyPath = metaClass.getPropertyPath(propertyName);
if (propertyPath != null) {
return getPropertyCaption(propertyPath.getMetaProperty());
} else {
return message;
}
}
/**
* Get localized name of an entity property. Messages pack must be located in the same package as entity.
*
* @param property MetaProperty
* @return localized name
*/
public String getPropertyCaption(MetaProperty property) {
return getPropertyCaption(property, null);
}
/**
* Get localized name of an entity property. Messages pack must be located in the same package as entity.
*
* @param property MetaProperty
* @param locale locale, if value is null locale of current user is used
* @return localized name
*/
public String getPropertyCaption(MetaProperty property, @Nullable Locale locale) {
Class<?> declaringClass = property.getDeclaringClass();
if (declaringClass == null) {
return property.getName();
}
String className = declaringClass.getSimpleName();
if (locale == null) {
return messages.getMessage(declaringClass, className + "." + property.getName());
}
return messages.getMessage(declaringClass, className + "." + property.getName(), locale);
}
/**
* Checks whether a localized name of the property exists.
* @param property MetaProperty
* @return true if {@link #getPropertyCaption(com.haulmont.chile.core.model.MetaProperty)} returns a
* string which has no dots inside or the first part before a dot is not equal to the declaring class
*/
public boolean hasPropertyCaption(MetaProperty property) {
Class<?> declaringClass = property.getDeclaringClass();
if (declaringClass == null)
return false;
String caption = getPropertyCaption(property);
int i = caption.indexOf('.');
if (i > 0 && declaringClass.getSimpleName().equals(caption.substring(0, i)))
return false;
else
return true;
}
/**
* @deprecated Use {@link #getDefaultRequiredMessage(MetaClass, String)}
* @return default required message for specified property.
*/
@Deprecated
public String getDefaultRequiredMessage(MetaProperty metaProperty) {
String notNullMessage = getNotNullMessage(metaProperty);
if (notNullMessage != null) {
return notNullMessage;
}
return messages.formatMessage(messages.getMainMessagePack(),
"validation.required.defaultMsg", getPropertyCaption(metaProperty));
}
/**
* Get default required message for specified property of MetaClass.
*
* @param metaClass MetaClass containing the property
* @param propertyName property's name
* @return default required message for specified property of MetaClass
*/
public String getDefaultRequiredMessage(MetaClass metaClass, String propertyName) {
MetaPropertyPath propertyPath = metaClass.getPropertyPath(propertyName);
if (propertyPath != null) {
String notNullMessage = getNotNullMessage(propertyPath.getMetaProperty());
if (notNullMessage != null) {
return notNullMessage;
}
}
return messages.formatMessage(messages.getMainMessagePack(),
"validation.required.defaultMsg", getPropertyCaption(metaClass, propertyName));
}
/**
* Get default required message for specified property of MetaClass if it has {@link NotNull} annotation.
*
* @param metaProperty MetaProperty
* @return localized not null message
*/
protected String getNotNullMessage(MetaProperty metaProperty) {
String notNullMessage = (String) metaProperty.getAnnotations()
.get(NotNull.class.getName() + "_notnull_message");
if (notNullMessage != null
&& !"{javax.validation.constraints.NotNull.message}".equals(notNullMessage)) {
if (notNullMessage.startsWith("{") && notNullMessage.endsWith("}")) {
notNullMessage = notNullMessage.substring(1, notNullMessage.length() - 1);
if (notNullMessage.startsWith(MAIN_MARK) || notNullMessage.startsWith(MARK)) {
return loadString(notNullMessage);
}
}
// return as is, parameters and value interpolation are not supported
return notNullMessage;
}
return null;
}
/**
* Get message reference of an entity property.
* Messages pack part of the reference corresponds to the entity's package.
* @param metaClass MetaClass containing the property
* @param propertyName property's name
* @return message key in the form {@code msg://message_pack/message_id}
*/
public String getMessageRef(MetaClass metaClass, String propertyName) {
MetaProperty property = metaClass.getProperty(propertyName);
if (property == null) {
throw new RuntimeException("Property " + propertyName + " is wrong for metaclass " + metaClass);
}
return getMessageRef(property);
}
/**
* Get message reference of an entity property.
* Messages pack part of the reference corresponds to the entity's package.
*
* @param property MetaProperty
* @return message key in the form {@code msg://message_pack/message_id}
*/
public String getMessageRef(MetaProperty property) {
Class<?> declaringClass = property.getDeclaringClass();
if (declaringClass == null)
return MARK + property.getName();
String className = declaringClass.getName();
String packageName= "";
int i = className.lastIndexOf('.');
if (i > -1) {
packageName = className.substring(0, i);
className = className.substring(i + 1);
}
return MARK + packageName + "/" + className + "." + property.getName();
}
/**
* Get localized value of an attribute based on {@link com.haulmont.cuba.core.entity.annotation.LocalizedValue} annotation.
*
* @param attribute attribute name
* @param instance entity instance
* @return localized value or the value itself, if the value is null or the message pack can not be inferred
*/
@Nullable
public String getLocValue(String attribute, Instance instance) {
String value = instance.getValue(attribute);
if (value == null)
return null;
String mp = inferMessagePack(attribute, instance);
if (mp == null)
return value;
else
return messages.getMessage(mp, value);
}
/**
* Returns message pack inferred from {@link com.haulmont.cuba.core.entity.annotation.LocalizedValue} annotation.
* @param attribute attribute name
* @param instance entity instance
* @return inferred message pack or null
*/
@Nullable
public String inferMessagePack(String attribute, Instance instance) {
Objects.requireNonNull(attribute, "attribute is null");
Objects.requireNonNull(instance, "instance is null");
MetaClass metaClass = metadata.getSession().getClassNN(instance.getClass());
MetaProperty property = metaClass.getPropertyNN(attribute);
Map<String, Object> attributes = metadata.getTools().getMetaAnnotationAttributes(property.getAnnotations(), LocalizedValue.class);
String messagePack = (String) attributes.get("messagePack");
if (!StringUtils.isBlank(messagePack))
return messagePack;
else {
String messagePackExpr = (String) attributes.get("messagePackExpr");
if (!StringUtils.isBlank(messagePackExpr)) {
try {
return instance.getValueEx(messagePackExpr);
} catch (Exception e) {
log.error("Unable to infer message pack from expression: " + messagePackExpr, e);
}
}
}
return null;
}
/**
* @return whether to use a full locale representation, or language only. Returns true if all locales listed
* in {@code cuba.availableLocales} app property are language only.
*/
public boolean useLocaleLanguageOnly() {
if (useLocaleLanguageOnly == null) {
boolean found = false;
for (Locale locale : globalConfig.getAvailableLocales().values()) {
if (!StringUtils.isEmpty(locale.getCountry()) || !StringUtils.isEmpty(locale.getVariant())) {
useLocaleLanguageOnly = false;
found = true;
break;
}
}
if (!found)
useLocaleLanguageOnly = true;
}
return useLocaleLanguageOnly;
}
/**
* Locale representation depending on {@code cuba.useLocaleLanguageOnly} application property.
*
* @param locale locale instance
* @return language code if {@code cuba.useLocaleLanguageOnly=true}, or full locale representation otherwise
*/
public String localeToString(Locale locale) {
return useLocaleLanguageOnly() ? locale.getLanguage() : locale.toString();
}
/**
* Trims locale to language-only if {@link #useLocaleLanguageOnly()} is true.
* @param locale a locale
* @return the locale with the same language and empty country and variant
*/
public Locale trimLocale(Locale locale) {
return useLocaleLanguageOnly() ? Locale.forLanguageTag(locale.getLanguage()) : locale;
}
/**
* @return first locale from the list defined in {@code cuba.availableLocales} app property, taking into
* account {@link #useLocaleLanguageOnly()} return value.
*/
public Locale getDefaultLocale() {
if (globalConfig.getAvailableLocales().isEmpty())
throw new DevelopmentException("Invalid cuba.availableLocales application property");
return globalConfig.getAvailableLocales().entrySet().iterator().next().getValue();
}
/**
* @param temporalType a temporal type
* @return default date format string for passed temporal type
*/
public String getDefaultDateFormat(TemporalType temporalType) {
return temporalType == TemporalType.DATE
? messages.getMainMessage("dateFormat")
: messages.getMainMessage("dateTimeFormat");
}
} | modules/global/src/com/haulmont/cuba/core/global/MessageTools.java | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.
*
*/
package com.haulmont.cuba.core.global;
import com.haulmont.chile.core.model.Instance;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.MetaProperty;
import com.haulmont.chile.core.model.MetaPropertyPath;
import com.haulmont.cuba.core.entity.annotation.LocalizedValue;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
/**
* Utility class to provide common functionality related to localized messages.
* <br> Implemented as Spring bean to allow extension in application projects.
* <br> A reference to this class can be obtained either via DI or by
* {@link com.haulmont.cuba.core.global.Messages#getTools()} method.
*/
@Component(MessageTools.NAME)
public class MessageTools {
/**
* Prefix defining that the string is actually a key in a localized messages pack.
*/
public static final String MARK = "msg://";
public static final String MAIN_MARK = "mainMsg://";
public static final String NAME = "cuba_MessageTools";
private final Logger log = LoggerFactory.getLogger(MessageTools.class);
protected volatile Boolean useLocaleLanguageOnly;
@Inject
protected Messages messages;
@Inject
protected Metadata metadata;
@Inject
protected ExtendedEntities extendedEntities;
protected GlobalConfig globalConfig;
@Inject
public MessageTools(Configuration configuration) {
globalConfig = configuration.getConfig(GlobalConfig.class);
}
/**
* Get localized message by reference provided in the full format.
* @param ref reference to message in the following format: {@code msg://message_pack/message_id}
* @return localized message or input string itself if it doesn't begin with {@code msg://}
*/
public String loadString(String ref) {
return loadString(null, ref);
}
/**
* Get localized message by reference provided in the full format.
* @param ref reference to message in the following format: {@code msg://message_pack/message_id}
* @return localized message or input string itself if it doesn't begin with {@code msg://}
*/
public String loadString(String ref, Locale locale) {
return loadString(null, ref, locale);
}
/**
* Get localized message by reference provided in full or brief format.
* @param messagesPack messages pack to use if the second parameter is in brief format
* @param ref reference to message in the following format:
* <ul>
* <li>Full: {@code msg://message_pack/message_id}
* <li>Brief: {@code msg://message_id}, in this case the first parameter is taken into account
* <li>Message from a main messages pack: {@code mainMsg://message_id}
* </ul>
* @return localized message or input string itself if it doesn't begin with {@code msg://} or {@code mainMsg://}
*/
@Nullable
public String loadString(@Nullable String messagesPack, @Nullable String ref) {
return loadString(messagesPack, ref, null);
}
/**
* Get localized message by reference provided in full or brief format.
* @param messagesPack messages pack to use if the second parameter is in brief format
* @param ref reference to message in the following format:
* @param locale locale
* <ul>
* <li>Full: {@code msg://message_pack/message_id}
* <li>Brief: {@code msg://message_id}, in this case the first parameter is taken into account
* <li>Message from a main messages pack: {@code mainMsg://message_id}
* </ul>
* @return localized message or input string itself if it doesn't begin with {@code msg://} or {@code mainMsg://}
*/
@Nullable
public String loadString(@Nullable String messagesPack, @Nullable String ref, @Nullable Locale locale) {
if (ref != null) {
if (ref.startsWith(MARK)) {
String path = ref.substring(6);
final String[] strings = path.split("/");
if (strings.length == 1 && messagesPack != null) {
if (locale == null) {
ref = messages.getMessage(messagesPack, strings[0]);
} else {
ref = messages.getMessage(messagesPack, strings[0], locale);
}
} else if (strings.length == 2) {
if (locale == null) {
ref = messages.getMessage(strings[0], strings[1]);
} else {
ref = messages.getMessage(strings[0], strings[1], locale);
}
} else {
throw new UnsupportedOperationException("Unsupported resource string format: '" + ref
+ "', messagesPack=" + messagesPack);
}
} else if (ref.startsWith(MAIN_MARK)) {
String path = ref.substring(10);
if (locale == null) {
return messages.getMainMessage(path);
} else {
return messages.getMainMessage(path, locale);
}
}
}
return ref;
}
/**
* @return a localized name of an entity. Messages pack must be located in the same package as entity.
*/
public String getEntityCaption(MetaClass metaClass) {
return getEntityCaption(metaClass, null);
}
/**
* @return a localized name of an entity with given locale or default if null. Messages pack must be located in the same package as entity.
*/
public String getEntityCaption(MetaClass metaClass, @Nullable Locale locale) {
Function<MetaClass, String> getMessage = locale != null ?
mc -> messages.getMessage(mc.getJavaClass(), mc.getJavaClass().getSimpleName(), locale) :
mc -> messages.getMessage(mc.getJavaClass(), mc.getJavaClass().getSimpleName());
String message = getMessage.apply(metaClass);
if (metaClass.getJavaClass().getSimpleName().equals(message)) {
MetaClass original = metadata.getExtendedEntities().getOriginalMetaClass(metaClass);
if (original != null)
return getMessage.apply(original);
}
return message;
}
/**
* @return a detailed localized name of an entity. Messages pack must be located in the same package as entity.
*/
public String getDetailedEntityCaption(MetaClass metaClass) {
return getDetailedEntityCaption(metaClass, null);
}
/**
* @return a detailed localized name of an entity with given locale or default if null. Messages pack must be located in the same package as entity.
*/
public String getDetailedEntityCaption(MetaClass metaClass, @Nullable Locale locale) {
return getEntityCaption(metaClass, locale) + " (" + metaClass.getName() + ")";
}
/**
* Get localized name of an entity property. Messages pack must be located in the same package as entity.
* @param metaClass MetaClass containing the property
* @param propertyName property's name
* @return localized name
*/
public String getPropertyCaption(MetaClass metaClass, String propertyName) {
Class originalClass = extendedEntities.getOriginalClass(metaClass);
Class<?> ownClass = originalClass != null ? originalClass : metaClass.getJavaClass();
String className = ownClass.getSimpleName();
String key = className + "." + propertyName;
String message = messages.getMessage(ownClass, key);
if (!message.equals(key)) {
return message;
}
MetaPropertyPath propertyPath = metaClass.getPropertyPath(propertyName);
if (propertyPath != null) {
return getPropertyCaption(propertyPath.getMetaProperty());
} else {
return message;
}
}
/**
* Get localized name of an entity property. Messages pack must be located in the same package as entity.
* @param property MetaProperty
* @return localized name
*/
public String getPropertyCaption(MetaProperty property) {
Class<?> declaringClass = property.getDeclaringClass();
if (declaringClass == null)
return property.getName();
String className = declaringClass.getSimpleName();
return messages.getMessage(declaringClass, className + "." + property.getName());
}
/**
* Checks whether a localized name of the property exists.
* @param property MetaProperty
* @return true if {@link #getPropertyCaption(com.haulmont.chile.core.model.MetaProperty)} returns a
* string which has no dots inside or the first part before a dot is not equal to the declaring class
*/
public boolean hasPropertyCaption(MetaProperty property) {
Class<?> declaringClass = property.getDeclaringClass();
if (declaringClass == null)
return false;
String caption = getPropertyCaption(property);
int i = caption.indexOf('.');
if (i > 0 && declaringClass.getSimpleName().equals(caption.substring(0, i)))
return false;
else
return true;
}
/**
* @deprecated Use {@link #getDefaultRequiredMessage(MetaClass, String)}
* @return default required message for specified property.
*/
@Deprecated
public String getDefaultRequiredMessage(MetaProperty metaProperty) {
String notNullMessage = getNotNullMessage(metaProperty);
if (notNullMessage != null) {
return notNullMessage;
}
return messages.formatMessage(messages.getMainMessagePack(),
"validation.required.defaultMsg", getPropertyCaption(metaProperty));
}
/**
* Get default required message for specified property of MetaClass.
*
* @param metaClass MetaClass containing the property
* @param propertyName property's name
* @return default required message for specified property of MetaClass
*/
public String getDefaultRequiredMessage(MetaClass metaClass, String propertyName) {
MetaPropertyPath propertyPath = metaClass.getPropertyPath(propertyName);
if (propertyPath != null) {
String notNullMessage = getNotNullMessage(propertyPath.getMetaProperty());
if (notNullMessage != null) {
return notNullMessage;
}
}
return messages.formatMessage(messages.getMainMessagePack(),
"validation.required.defaultMsg", getPropertyCaption(metaClass, propertyName));
}
/**
* Get default required message for specified property of MetaClass if it has {@link NotNull} annotation.
*
* @param metaProperty MetaProperty
* @return localized not null message
*/
protected String getNotNullMessage(MetaProperty metaProperty) {
String notNullMessage = (String) metaProperty.getAnnotations()
.get(NotNull.class.getName() + "_notnull_message");
if (notNullMessage != null
&& !"{javax.validation.constraints.NotNull.message}".equals(notNullMessage)) {
if (notNullMessage.startsWith("{") && notNullMessage.endsWith("}")) {
notNullMessage = notNullMessage.substring(1, notNullMessage.length() - 1);
if (notNullMessage.startsWith(MAIN_MARK) || notNullMessage.startsWith(MARK)) {
return loadString(notNullMessage);
}
}
// return as is, parameters and value interpolation are not supported
return notNullMessage;
}
return null;
}
/**
* Get message reference of an entity property.
* Messages pack part of the reference corresponds to the entity's package.
* @param metaClass MetaClass containing the property
* @param propertyName property's name
* @return message key in the form {@code msg://message_pack/message_id}
*/
public String getMessageRef(MetaClass metaClass, String propertyName) {
MetaProperty property = metaClass.getProperty(propertyName);
if (property == null) {
throw new RuntimeException("Property " + propertyName + " is wrong for metaclass " + metaClass);
}
return getMessageRef(property);
}
/**
* Get message reference of an entity property.
* Messages pack part of the reference corresponds to the entity's package.
*
* @param property MetaProperty
* @return message key in the form {@code msg://message_pack/message_id}
*/
public String getMessageRef(MetaProperty property) {
Class<?> declaringClass = property.getDeclaringClass();
if (declaringClass == null)
return MARK + property.getName();
String className = declaringClass.getName();
String packageName= "";
int i = className.lastIndexOf('.');
if (i > -1) {
packageName = className.substring(0, i);
className = className.substring(i + 1);
}
return MARK + packageName + "/" + className + "." + property.getName();
}
/**
* Get localized value of an attribute based on {@link com.haulmont.cuba.core.entity.annotation.LocalizedValue} annotation.
*
* @param attribute attribute name
* @param instance entity instance
* @return localized value or the value itself, if the value is null or the message pack can not be inferred
*/
@Nullable
public String getLocValue(String attribute, Instance instance) {
String value = instance.getValue(attribute);
if (value == null)
return null;
String mp = inferMessagePack(attribute, instance);
if (mp == null)
return value;
else
return messages.getMessage(mp, value);
}
/**
* Returns message pack inferred from {@link com.haulmont.cuba.core.entity.annotation.LocalizedValue} annotation.
* @param attribute attribute name
* @param instance entity instance
* @return inferred message pack or null
*/
@Nullable
public String inferMessagePack(String attribute, Instance instance) {
Objects.requireNonNull(attribute, "attribute is null");
Objects.requireNonNull(instance, "instance is null");
MetaClass metaClass = metadata.getSession().getClassNN(instance.getClass());
MetaProperty property = metaClass.getPropertyNN(attribute);
Map<String, Object> attributes = metadata.getTools().getMetaAnnotationAttributes(property.getAnnotations(), LocalizedValue.class);
String messagePack = (String) attributes.get("messagePack");
if (!StringUtils.isBlank(messagePack))
return messagePack;
else {
String messagePackExpr = (String) attributes.get("messagePackExpr");
if (!StringUtils.isBlank(messagePackExpr)) {
try {
return instance.getValueEx(messagePackExpr);
} catch (Exception e) {
log.error("Unable to infer message pack from expression: " + messagePackExpr, e);
}
}
}
return null;
}
/**
* @return whether to use a full locale representation, or language only. Returns true if all locales listed
* in {@code cuba.availableLocales} app property are language only.
*/
public boolean useLocaleLanguageOnly() {
if (useLocaleLanguageOnly == null) {
boolean found = false;
for (Locale locale : globalConfig.getAvailableLocales().values()) {
if (!StringUtils.isEmpty(locale.getCountry()) || !StringUtils.isEmpty(locale.getVariant())) {
useLocaleLanguageOnly = false;
found = true;
break;
}
}
if (!found)
useLocaleLanguageOnly = true;
}
return useLocaleLanguageOnly;
}
/**
* Locale representation depending on {@code cuba.useLocaleLanguageOnly} application property.
*
* @param locale locale instance
* @return language code if {@code cuba.useLocaleLanguageOnly=true}, or full locale representation otherwise
*/
public String localeToString(Locale locale) {
return useLocaleLanguageOnly() ? locale.getLanguage() : locale.toString();
}
/**
* Trims locale to language-only if {@link #useLocaleLanguageOnly()} is true.
* @param locale a locale
* @return the locale with the same language and empty country and variant
*/
public Locale trimLocale(Locale locale) {
return useLocaleLanguageOnly() ? Locale.forLanguageTag(locale.getLanguage()) : locale;
}
/**
* @return first locale from the list defined in {@code cuba.availableLocales} app property, taking into
* account {@link #useLocaleLanguageOnly()} return value.
*/
public Locale getDefaultLocale() {
if (globalConfig.getAvailableLocales().isEmpty())
throw new DevelopmentException("Invalid cuba.availableLocales application property");
return globalConfig.getAvailableLocales().entrySet().iterator().next().getValue();
}
/**
* @param temporalType a temporal type
* @return default date format string for passed temporal type
*/
public String getDefaultDateFormat(TemporalType temporalType) {
return temporalType == TemporalType.DATE
? messages.getMainMessage("dateFormat")
: messages.getMainMessage("dateTimeFormat");
}
} | PL-5306 Provide MessageTools.getPropertyCaption methods with Locale parameter
| modules/global/src/com/haulmont/cuba/core/global/MessageTools.java | PL-5306 Provide MessageTools.getPropertyCaption methods with Locale parameter | <ide><path>odules/global/src/com/haulmont/cuba/core/global/MessageTools.java
<ide> * @return localized name
<ide> */
<ide> public String getPropertyCaption(MetaClass metaClass, String propertyName) {
<add> return getPropertyCaption(metaClass, propertyName, null);
<add> }
<add>
<add> /**
<add> * Get localized name of an entity property. Messages pack must be located in the same package as entity.
<add> *
<add> * @param metaClass MetaClass containing the property
<add> * @param propertyName property's name
<add> * @param locale locale, if value is null locale of current user is used
<add> * @return localized name
<add> */
<add> public String getPropertyCaption(MetaClass metaClass, String propertyName, @Nullable Locale locale) {
<ide> Class originalClass = extendedEntities.getOriginalClass(metaClass);
<ide> Class<?> ownClass = originalClass != null ? originalClass : metaClass.getJavaClass();
<ide> String className = ownClass.getSimpleName();
<ide>
<ide> String key = className + "." + propertyName;
<del> String message = messages.getMessage(ownClass, key);
<add> String message;
<add> if (locale == null) {
<add> message = messages.getMessage(ownClass, key);
<add> } else {
<add> message = messages.getMessage(ownClass, key, locale);
<add> }
<add>
<ide> if (!message.equals(key)) {
<ide> return message;
<ide> }
<ide>
<ide> /**
<ide> * Get localized name of an entity property. Messages pack must be located in the same package as entity.
<del> * @param property MetaProperty
<add> *
<add> * @param property MetaProperty
<ide> * @return localized name
<ide> */
<ide> public String getPropertyCaption(MetaProperty property) {
<add> return getPropertyCaption(property, null);
<add> }
<add>
<add> /**
<add> * Get localized name of an entity property. Messages pack must be located in the same package as entity.
<add> *
<add> * @param property MetaProperty
<add> * @param locale locale, if value is null locale of current user is used
<add> * @return localized name
<add> */
<add> public String getPropertyCaption(MetaProperty property, @Nullable Locale locale) {
<ide> Class<?> declaringClass = property.getDeclaringClass();
<del> if (declaringClass == null)
<add> if (declaringClass == null) {
<ide> return property.getName();
<add> }
<ide>
<ide> String className = declaringClass.getSimpleName();
<del> return messages.getMessage(declaringClass, className + "." + property.getName());
<add> if (locale == null) {
<add> return messages.getMessage(declaringClass, className + "." + property.getName());
<add> }
<add>
<add> return messages.getMessage(declaringClass, className + "." + property.getName(), locale);
<ide> }
<ide>
<ide> /** |
|
Java | bsd-2-clause | f6da67cd2de4fe908a6d6d9f0cec959bcc8b78fc | 0 | l2-/runelite,runelite/runelite,Sethtroll/runelite,runelite/runelite,Sethtroll/runelite,l2-/runelite,runelite/runelite | /*
* Copyright (c) 2016-2017, Adam <[email protected]>
* Copyright (c) 2018, Tomas Slusny <[email protected]>
* Copyright (c) 2019 Abex
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.rs;
import com.google.archivepatcher.applier.FileByFileV1DeltaApplier;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingOutputStream;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import java.applet.Applet;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.StandardOpenOption;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.function.Supplier;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import javax.annotation.Nonnull;
import javax.swing.SwingUtilities;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.client.RuneLite;
import net.runelite.client.RuneLiteProperties;
import static net.runelite.client.rs.ClientUpdateCheckMode.AUTO;
import static net.runelite.client.rs.ClientUpdateCheckMode.NONE;
import static net.runelite.client.rs.ClientUpdateCheckMode.VANILLA;
import net.runelite.client.ui.FatalErrorDialog;
import net.runelite.client.ui.SplashScreen;
import net.runelite.client.util.CountingInputStream;
import net.runelite.client.util.VerificationException;
import net.runelite.http.api.RuneLiteAPI;
import net.runelite.http.api.worlds.World;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
@Slf4j
@SuppressWarnings("deprecation")
public class ClientLoader implements Supplier<Applet>
{
private static final int NUM_ATTEMPTS = 6;
private static File LOCK_FILE = new File(RuneLite.CACHE_DIR, "cache.lock");
private static File VANILLA_CACHE = new File(RuneLite.CACHE_DIR, "vanilla.cache");
private static File PATCHED_CACHE = new File(RuneLite.CACHE_DIR, "patched.cache");
private ClientUpdateCheckMode updateCheckMode;
private Object client = null;
private WorldSupplier worldSupplier = new WorldSupplier();
public ClientLoader(ClientUpdateCheckMode updateCheckMode)
{
this.updateCheckMode = updateCheckMode;
}
@Override
public synchronized Applet get()
{
if (client == null)
{
client = doLoad();
}
if (client instanceof Throwable)
{
throw new RuntimeException((Throwable) client);
}
return (Applet) client;
}
private Object doLoad()
{
if (updateCheckMode == NONE)
{
return null;
}
try
{
SplashScreen.stage(0, null, "Fetching applet viewer config");
RSConfig config = downloadConfig();
SplashScreen.stage(.05, null, "Waiting for other clients to start");
LOCK_FILE.getParentFile().mkdirs();
ClassLoader classLoader;
try (FileChannel lockfile = FileChannel.open(LOCK_FILE.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
FileLock flock = lockfile.lock())
{
SplashScreen.stage(.05, null, "Downloading Old School RuneScape");
try
{
updateVanilla(config);
}
catch (IOException ex)
{
// try again with the fallback config and gamepack
if (!config.isFallback())
{
log.warn("Unable to download game client, attempting to use fallback config", ex);
config = downloadFallbackConfig();
updateVanilla(config);
}
else
{
throw ex;
}
}
if (updateCheckMode == AUTO)
{
SplashScreen.stage(.35, null, "Patching");
applyPatch();
}
SplashScreen.stage(.40, null, "Loading client");
File jarFile = updateCheckMode == AUTO ? PATCHED_CACHE : VANILLA_CACHE;
// create the classloader for the jar while we hold the lock, and eagerly load and link all classes
// in the jar. Otherwise the jar can change on disk and can break future classloads.
classLoader = createJarClassLoader(jarFile);
}
SplashScreen.stage(.465, "Starting", "Starting Old School RuneScape");
Applet rs = loadClient(config, classLoader);
SplashScreen.stage(.5, null, "Starting core classes");
return rs;
}
catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException
| VerificationException | SecurityException e)
{
log.error("Error loading RS!", e);
SwingUtilities.invokeLater(() -> FatalErrorDialog.showNetErrorWindow("loading the client", e));
return e;
}
}
private RSConfig downloadConfig() throws IOException
{
HttpUrl url = HttpUrl.parse(RuneLiteProperties.getJavConfig());
IOException err = null;
for (int attempt = 0; attempt < NUM_ATTEMPTS; attempt++)
{
try
{
RSConfig config = ClientConfigLoader.fetch(url);
if (Strings.isNullOrEmpty(config.getCodeBase()) || Strings.isNullOrEmpty(config.getInitialJar()) || Strings.isNullOrEmpty(config.getInitialClass()))
{
throw new IOException("Invalid or missing jav_config");
}
return config;
}
catch (IOException e)
{
log.info("Failed to get jav_config from host \"{}\" ({})", url.host(), e.getMessage());
String host = worldSupplier.get().getAddress();
url = url.newBuilder().host(host).build();
err = e;
}
}
log.info("Falling back to backup client config");
try
{
return downloadFallbackConfig();
}
catch (IOException ex)
{
log.debug("error downloading backup config", ex);
throw err; // use error from Jagex's servers
}
}
@Nonnull
private RSConfig downloadFallbackConfig() throws IOException
{
RSConfig backupConfig = ClientConfigLoader.fetch(HttpUrl.parse(RuneLiteProperties.getJavConfigBackup()));
if (Strings.isNullOrEmpty(backupConfig.getCodeBase()) || Strings.isNullOrEmpty(backupConfig.getInitialJar()) || Strings.isNullOrEmpty(backupConfig.getInitialClass()))
{
throw new IOException("Invalid or missing jav_config");
}
if (Strings.isNullOrEmpty(backupConfig.getRuneLiteGamepack()) || Strings.isNullOrEmpty(backupConfig.getRuneLiteWorldParam()))
{
throw new IOException("Backup config does not have RuneLite gamepack url");
}
// Randomize the codebase
World world = worldSupplier.get();
backupConfig.setCodebase("http://" + world.getAddress() + "/");
// Update the world applet parameter
Map<String, String> appletProperties = backupConfig.getAppletProperties();
appletProperties.put(backupConfig.getRuneLiteWorldParam(), Integer.toString(world.getId()));
return backupConfig;
}
private void updateVanilla(RSConfig config) throws IOException, VerificationException
{
Certificate[] jagexCertificateChain = getJagexCertificateChain();
// Get the mtime of the first thing in the vanilla cache
// we check this against what the server gives us to let us skip downloading and patching the whole thing
try (FileChannel vanilla = FileChannel.open(VANILLA_CACHE.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE))
{
long vanillaCacheMTime = -1;
boolean vanillaCacheIsInvalid = false;
try
{
JarInputStream vanillaCacheTest = new JarInputStream(Channels.newInputStream(vanilla));
vanillaCacheTest.skip(Long.MAX_VALUE);
JarEntry je = vanillaCacheTest.getNextJarEntry();
if (je != null)
{
verifyJarEntry(je, jagexCertificateChain);
vanillaCacheMTime = je.getLastModifiedTime().toMillis();
}
else
{
vanillaCacheIsInvalid = true;
}
}
catch (Exception e)
{
log.info("Failed to read the vanilla cache: {}", e.toString());
vanillaCacheIsInvalid = true;
}
vanilla.position(0);
// Start downloading the vanilla client
HttpUrl url;
if (config.isFallback())
{
// If we are using the backup config, use our own gamepack and ignore the codebase
url = HttpUrl.parse(config.getRuneLiteGamepack());
}
else
{
String codebase = config.getCodeBase();
String initialJar = config.getInitialJar();
url = HttpUrl.parse(codebase + initialJar);
}
for (int attempt = 0; ; attempt++)
{
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute())
{
// Its important to not close the response manually - this should be the only close or
// try-with-resources on this stream or it's children
if (!response.isSuccessful())
{
throw new IOException("unsuccessful response fetching gamepack: " + response.message());
}
int length = (int) response.body().contentLength();
if (length < 0)
{
length = 3 * 1024 * 1024;
}
else
{
if (!vanillaCacheIsInvalid && vanilla.size() != length)
{
// The zip trailer filetab can be missing and the ZipInputStream will not notice
log.info("Vanilla cache is the wrong size");
vanillaCacheIsInvalid = true;
}
}
final int flength = length;
TeeInputStream copyStream = new TeeInputStream(new CountingInputStream(response.body().byteStream(),
read -> SplashScreen.stage(.05, .35, null, "Downloading Old School RuneScape", read, flength, true)));
// Save the bytes from the mtime test so we can write it to disk
// if the test fails, or the cache doesn't verify
ByteArrayOutputStream preRead = new ByteArrayOutputStream();
copyStream.setOut(preRead);
JarInputStream networkJIS = new JarInputStream(copyStream);
// Get the mtime from the first entry so check it against the cache
{
JarEntry je = networkJIS.getNextJarEntry();
if (je == null)
{
throw new IOException("unable to peek first jar entry");
}
networkJIS.skip(Long.MAX_VALUE);
verifyJarEntry(je, jagexCertificateChain);
long vanillaClientMTime = je.getLastModifiedTime().toMillis();
if (!vanillaCacheIsInvalid && vanillaClientMTime != vanillaCacheMTime)
{
log.info("Vanilla cache is out of date: {} != {}", vanillaClientMTime, vanillaCacheMTime);
vanillaCacheIsInvalid = true;
}
}
// the mtime matches so the cache is probably up to date, but just make sure its fully
// intact before closing the server connection
if (!vanillaCacheIsInvalid)
{
try
{
// as with the request stream, its important to not early close vanilla too
JarInputStream vanillaCacheTest = new JarInputStream(Channels.newInputStream(vanilla));
verifyWholeJar(vanillaCacheTest, jagexCertificateChain);
}
catch (Exception e)
{
log.warn("Failed to verify the vanilla cache", e);
vanillaCacheIsInvalid = true;
}
}
if (vanillaCacheIsInvalid)
{
// the cache is not up to date, commit our peek to the file and write the rest of it, while verifying
vanilla.position(0);
OutputStream out = Channels.newOutputStream(vanilla);
out.write(preRead.toByteArray());
copyStream.setOut(out);
verifyWholeJar(networkJIS, jagexCertificateChain);
copyStream.skip(Long.MAX_VALUE); // write the trailer to the file too
out.flush();
vanilla.truncate(vanilla.position());
}
else
{
log.info("Using cached vanilla client");
}
return;
}
catch (IOException e)
{
log.warn("Failed to download gamepack from \"{}\"", url, e);
// With fallback config do 1 attempt (there are no additional urls to try)
if (config.isFallback() || attempt >= NUM_ATTEMPTS)
{
throw e;
}
url = url.newBuilder().host(worldSupplier.get().getAddress()).build();
}
}
}
}
private void applyPatch() throws IOException
{
byte[] vanillaHash = new byte[64];
byte[] appliedPatchHash = new byte[64];
try (InputStream is = ClientLoader.class.getResourceAsStream("/client.serial"))
{
if (is == null)
{
SwingUtilities.invokeLater(() ->
new FatalErrorDialog("The client-patch is missing from the classpath. If you are building " +
"the client you need to re-run maven")
.addBuildingGuide()
.open());
throw new NullPointerException();
}
DataInputStream dis = new DataInputStream(is);
dis.readFully(vanillaHash);
dis.readFully(appliedPatchHash);
}
byte[] vanillaCacheHash = Files.asByteSource(VANILLA_CACHE).hash(Hashing.sha512()).asBytes();
if (!Arrays.equals(vanillaHash, vanillaCacheHash))
{
log.info("Client is outdated!");
updateCheckMode = VANILLA;
return;
}
if (PATCHED_CACHE.exists())
{
byte[] diskBytes = Files.asByteSource(PATCHED_CACHE).hash(Hashing.sha512()).asBytes();
if (!Arrays.equals(diskBytes, appliedPatchHash))
{
log.warn("Cached patch hash mismatches, regenerating patch");
}
else
{
log.info("Using cached patched client");
return;
}
}
try (HashingOutputStream hos = new HashingOutputStream(Hashing.sha512(), new FileOutputStream(PATCHED_CACHE));
InputStream patch = ClientLoader.class.getResourceAsStream("/client.patch"))
{
new FileByFileV1DeltaApplier().applyDelta(VANILLA_CACHE, patch, hos);
if (!Arrays.equals(hos.hash().asBytes(), appliedPatchHash))
{
log.error("Patched client hash mismatch");
updateCheckMode = VANILLA;
return;
}
}
catch (IOException e)
{
log.error("Unable to apply patch despite hash matching", e);
updateCheckMode = VANILLA;
return;
}
}
private ClassLoader createJarClassLoader(File jar) throws IOException, ClassNotFoundException
{
try (JarFile jarFile = new JarFile(jar))
{
ClassLoader classLoader = new ClassLoader(ClientLoader.class.getClassLoader())
{
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
String entryName = name.replace('.', '/').concat(".class");
JarEntry jarEntry;
try
{
jarEntry = jarFile.getJarEntry(entryName);
}
catch (IllegalStateException ex)
{
throw new ClassNotFoundException(name, ex);
}
if (jarEntry == null)
{
throw new ClassNotFoundException(name);
}
try
{
InputStream inputStream = jarFile.getInputStream(jarEntry);
if (inputStream == null)
{
throw new ClassNotFoundException(name);
}
byte[] bytes = ByteStreams.toByteArray(inputStream);
return defineClass(name, bytes, 0, bytes.length);
}
catch (IOException e)
{
throw new ClassNotFoundException(null, e);
}
}
};
// load all of the classes in this jar; after the jar is closed the classloader
// will no longer be able to look up classes
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
if (name.endsWith(".class"))
{
name = name.substring(0, name.length() - 6);
classLoader.loadClass(name);
}
}
return classLoader;
}
}
private Applet loadClient(RSConfig config, ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
String initialClass = config.getInitialClass();
Class<?> clientClass = classLoader.loadClass(initialClass);
Applet rs = (Applet) clientClass.newInstance();
rs.setStub(new RSAppletStub(config));
if (rs instanceof Client)
{
log.info("client-patch {}", ((Client) rs).getBuildID());
}
return rs;
}
private static Certificate[] getJagexCertificateChain()
{
try
{
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(ClientLoader.class.getResourceAsStream("jagex.crt"));
return certificates.toArray(new Certificate[0]);
}
catch (CertificateException e)
{
throw new RuntimeException("Unable to parse pinned certificates", e);
}
}
private void verifyJarEntry(JarEntry je, Certificate[] certs) throws VerificationException
{
switch (je.getName())
{
case "META-INF/JAGEXLTD.SF":
case "META-INF/JAGEXLTD.RSA":
// You can't sign the signing files
return;
default:
if (!Arrays.equals(je.getCertificates(), certs))
{
throw new VerificationException("Unable to verify jar entry: " + je.getName());
}
}
}
private void verifyWholeJar(JarInputStream jis, Certificate[] certs) throws IOException, VerificationException
{
for (JarEntry je; (je = jis.getNextJarEntry()) != null; )
{
jis.skip(Long.MAX_VALUE);
verifyJarEntry(je, certs);
}
}
}
| runelite-client/src/main/java/net/runelite/client/rs/ClientLoader.java | /*
* Copyright (c) 2016-2017, Adam <[email protected]>
* Copyright (c) 2018, Tomas Slusny <[email protected]>
* Copyright (c) 2019 Abex
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.rs;
import com.google.archivepatcher.applier.FileByFileV1DeltaApplier;
import com.google.common.base.Strings;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingOutputStream;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import java.applet.Applet;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.StandardOpenOption;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import java.util.function.Supplier;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import javax.annotation.Nonnull;
import javax.swing.SwingUtilities;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.client.RuneLite;
import net.runelite.client.RuneLiteProperties;
import static net.runelite.client.rs.ClientUpdateCheckMode.AUTO;
import static net.runelite.client.rs.ClientUpdateCheckMode.NONE;
import static net.runelite.client.rs.ClientUpdateCheckMode.VANILLA;
import net.runelite.client.ui.FatalErrorDialog;
import net.runelite.client.ui.SplashScreen;
import net.runelite.client.util.CountingInputStream;
import net.runelite.client.util.VerificationException;
import net.runelite.http.api.RuneLiteAPI;
import net.runelite.http.api.worlds.World;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
@Slf4j
@SuppressWarnings("deprecation")
public class ClientLoader implements Supplier<Applet>
{
private static final int NUM_ATTEMPTS = 6;
private static File LOCK_FILE = new File(RuneLite.CACHE_DIR, "cache.lock");
private static File VANILLA_CACHE = new File(RuneLite.CACHE_DIR, "vanilla.cache");
private static File PATCHED_CACHE = new File(RuneLite.CACHE_DIR, "patched.cache");
private ClientUpdateCheckMode updateCheckMode;
private Object client = null;
private WorldSupplier worldSupplier = new WorldSupplier();
public ClientLoader(ClientUpdateCheckMode updateCheckMode)
{
this.updateCheckMode = updateCheckMode;
}
@Override
public synchronized Applet get()
{
if (client == null)
{
client = doLoad();
}
if (client instanceof Throwable)
{
throw new RuntimeException((Throwable) client);
}
return (Applet) client;
}
private Object doLoad()
{
if (updateCheckMode == NONE)
{
return null;
}
try
{
SplashScreen.stage(0, null, "Fetching applet viewer config");
RSConfig config = downloadConfig();
SplashScreen.stage(.05, null, "Waiting for other clients to start");
LOCK_FILE.getParentFile().mkdirs();
ClassLoader classLoader;
try (FileChannel lockfile = FileChannel.open(LOCK_FILE.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
FileLock flock = lockfile.lock())
{
SplashScreen.stage(.05, null, "Downloading Old School RuneScape");
try
{
updateVanilla(config);
}
catch (IOException ex)
{
// try again with the fallback config and gamepack
if (!config.isFallback())
{
log.warn("Unable to download game client, attempting to use fallback config", ex);
config = downloadFallbackConfig();
updateVanilla(config);
}
else
{
throw ex;
}
}
if (updateCheckMode == AUTO)
{
SplashScreen.stage(.35, null, "Patching");
applyPatch();
}
SplashScreen.stage(.40, null, "Loading client");
File jarFile = updateCheckMode == AUTO ? PATCHED_CACHE : VANILLA_CACHE;
// create the classloader for the jar while we hold the lock, and eagerly load and link all classes
// in the jar. Otherwise the jar can change on disk and can break future classloads.
classLoader = createJarClassLoader(jarFile);
}
SplashScreen.stage(.465, "Starting", "Starting Old School RuneScape");
Applet rs = loadClient(config, classLoader);
SplashScreen.stage(.5, null, "Starting core classes");
return rs;
}
catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException
| VerificationException | SecurityException e)
{
log.error("Error loading RS!", e);
SwingUtilities.invokeLater(() -> FatalErrorDialog.showNetErrorWindow("loading the client", e));
return e;
}
}
private RSConfig downloadConfig() throws IOException
{
HttpUrl url = HttpUrl.parse(RuneLiteProperties.getJavConfig());
IOException err = null;
for (int attempt = 0; attempt < NUM_ATTEMPTS; attempt++)
{
try
{
RSConfig config = ClientConfigLoader.fetch(url);
if (Strings.isNullOrEmpty(config.getCodeBase()) || Strings.isNullOrEmpty(config.getInitialJar()) || Strings.isNullOrEmpty(config.getInitialClass()))
{
throw new IOException("Invalid or missing jav_config");
}
return config;
}
catch (IOException e)
{
log.info("Failed to get jav_config from host \"{}\" ({})", url.host(), e.getMessage());
String host = worldSupplier.get().getAddress();
url = url.newBuilder().host(host).build();
err = e;
}
}
log.info("Falling back to backup client config");
try
{
return downloadFallbackConfig();
}
catch (IOException ex)
{
log.debug("error downloading backup config", ex);
throw err; // use error from Jagex's servers
}
}
@Nonnull
private RSConfig downloadFallbackConfig() throws IOException
{
RSConfig backupConfig = ClientConfigLoader.fetch(HttpUrl.parse(RuneLiteProperties.getJavConfigBackup()));
if (Strings.isNullOrEmpty(backupConfig.getCodeBase()) || Strings.isNullOrEmpty(backupConfig.getInitialJar()) || Strings.isNullOrEmpty(backupConfig.getInitialClass()))
{
throw new IOException("Invalid or missing jav_config");
}
if (Strings.isNullOrEmpty(backupConfig.getRuneLiteGamepack()) || Strings.isNullOrEmpty(backupConfig.getRuneLiteWorldParam()))
{
throw new IOException("Backup config does not have RuneLite gamepack url");
}
// Randomize the codebase
World world = worldSupplier.get();
backupConfig.setCodebase("http://" + world.getAddress() + "/");
// Update the world applet parameter
Map<String, String> appletProperties = backupConfig.getAppletProperties();
appletProperties.put(backupConfig.getRuneLiteWorldParam(), Integer.toString(world.getId()));
return backupConfig;
}
private void updateVanilla(RSConfig config) throws IOException, VerificationException
{
Certificate[] jagexCertificateChain = getJagexCertificateChain();
// Get the mtime of the first thing in the vanilla cache
// we check this against what the server gives us to let us skip downloading and patching the whole thing
try (FileChannel vanilla = FileChannel.open(VANILLA_CACHE.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE))
{
long vanillaCacheMTime = -1;
boolean vanillaCacheIsInvalid = false;
try
{
JarInputStream vanillaCacheTest = new JarInputStream(Channels.newInputStream(vanilla));
vanillaCacheTest.skip(Long.MAX_VALUE);
JarEntry je = vanillaCacheTest.getNextJarEntry();
if (je != null)
{
verifyJarEntry(je, jagexCertificateChain);
vanillaCacheMTime = je.getLastModifiedTime().toMillis();
}
else
{
vanillaCacheIsInvalid = true;
}
}
catch (Exception e)
{
log.info("Failed to read the vanilla cache: {}", e.toString());
vanillaCacheIsInvalid = true;
}
vanilla.position(0);
// Start downloading the vanilla client
HttpUrl url;
if (config.isFallback())
{
// If we are using the backup config, use our own gamepack and ignore the codebase
url = HttpUrl.parse(config.getRuneLiteGamepack());
}
else
{
String codebase = config.getCodeBase();
String initialJar = config.getInitialJar();
url = HttpUrl.parse(codebase + initialJar);
}
for (int attempt = 0; ; attempt++)
{
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = RuneLiteAPI.CLIENT.newCall(request).execute())
{
// Its important to not close the response manually - this should be the only close or
// try-with-resources on this stream or it's children
if (!response.isSuccessful())
{
throw new IOException("unsuccessful response fetching gamepack: " + response.message());
}
int length = (int) response.body().contentLength();
if (length < 0)
{
length = 3 * 1024 * 1024;
}
else
{
if (!vanillaCacheIsInvalid && vanilla.size() != length)
{
// The zip trailer filetab can be missing and the ZipInputStream will not notice
log.info("Vanilla cache is the wrong size");
vanillaCacheIsInvalid = true;
}
}
final int flength = length;
TeeInputStream copyStream = new TeeInputStream(new CountingInputStream(response.body().byteStream(),
read -> SplashScreen.stage(.05, .35, null, "Downloading Old School RuneScape", read, flength, true)));
// Save the bytes from the mtime test so we can write it to disk
// if the test fails, or the cache doesn't verify
ByteArrayOutputStream preRead = new ByteArrayOutputStream();
copyStream.setOut(preRead);
JarInputStream networkJIS = new JarInputStream(copyStream);
// Get the mtime from the first entry so check it against the cache
{
JarEntry je = networkJIS.getNextJarEntry();
if (je == null)
{
throw new IOException("unable to peek first jar entry");
}
networkJIS.skip(Long.MAX_VALUE);
verifyJarEntry(je, jagexCertificateChain);
long vanillaClientMTime = je.getLastModifiedTime().toMillis();
if (!vanillaCacheIsInvalid && vanillaClientMTime != vanillaCacheMTime)
{
log.info("Vanilla cache is out of date: {} != {}", vanillaClientMTime, vanillaCacheMTime);
vanillaCacheIsInvalid = true;
}
}
// the mtime matches so the cache is probably up to date, but just make sure its fully
// intact before closing the server connection
if (!vanillaCacheIsInvalid)
{
try
{
// as with the request stream, its important to not early close vanilla too
JarInputStream vanillaCacheTest = new JarInputStream(Channels.newInputStream(vanilla));
verifyWholeJar(vanillaCacheTest, jagexCertificateChain);
}
catch (Exception e)
{
log.warn("Failed to verify the vanilla cache", e);
vanillaCacheIsInvalid = true;
}
}
if (vanillaCacheIsInvalid)
{
// the cache is not up to date, commit our peek to the file and write the rest of it, while verifying
vanilla.position(0);
OutputStream out = Channels.newOutputStream(vanilla);
out.write(preRead.toByteArray());
copyStream.setOut(out);
verifyWholeJar(networkJIS, jagexCertificateChain);
copyStream.skip(Long.MAX_VALUE); // write the trailer to the file too
out.flush();
vanilla.truncate(vanilla.position());
}
else
{
log.info("Using cached vanilla client");
}
return;
}
catch (IOException e)
{
log.warn("Failed to download gamepack from \"{}\"", url, e);
if (attempt >= NUM_ATTEMPTS)
{
throw e;
}
url = url.newBuilder().host(worldSupplier.get().getAddress()).build();
}
}
}
}
private void applyPatch() throws IOException
{
byte[] vanillaHash = new byte[64];
byte[] appliedPatchHash = new byte[64];
try (InputStream is = ClientLoader.class.getResourceAsStream("/client.serial"))
{
if (is == null)
{
SwingUtilities.invokeLater(() ->
new FatalErrorDialog("The client-patch is missing from the classpath. If you are building " +
"the client you need to re-run maven")
.addBuildingGuide()
.open());
throw new NullPointerException();
}
DataInputStream dis = new DataInputStream(is);
dis.readFully(vanillaHash);
dis.readFully(appliedPatchHash);
}
byte[] vanillaCacheHash = Files.asByteSource(VANILLA_CACHE).hash(Hashing.sha512()).asBytes();
if (!Arrays.equals(vanillaHash, vanillaCacheHash))
{
log.info("Client is outdated!");
updateCheckMode = VANILLA;
return;
}
if (PATCHED_CACHE.exists())
{
byte[] diskBytes = Files.asByteSource(PATCHED_CACHE).hash(Hashing.sha512()).asBytes();
if (!Arrays.equals(diskBytes, appliedPatchHash))
{
log.warn("Cached patch hash mismatches, regenerating patch");
}
else
{
log.info("Using cached patched client");
return;
}
}
try (HashingOutputStream hos = new HashingOutputStream(Hashing.sha512(), new FileOutputStream(PATCHED_CACHE));
InputStream patch = ClientLoader.class.getResourceAsStream("/client.patch"))
{
new FileByFileV1DeltaApplier().applyDelta(VANILLA_CACHE, patch, hos);
if (!Arrays.equals(hos.hash().asBytes(), appliedPatchHash))
{
log.error("Patched client hash mismatch");
updateCheckMode = VANILLA;
return;
}
}
catch (IOException e)
{
log.error("Unable to apply patch despite hash matching", e);
updateCheckMode = VANILLA;
return;
}
}
private ClassLoader createJarClassLoader(File jar) throws IOException, ClassNotFoundException
{
try (JarFile jarFile = new JarFile(jar))
{
ClassLoader classLoader = new ClassLoader(ClientLoader.class.getClassLoader())
{
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
String entryName = name.replace('.', '/').concat(".class");
JarEntry jarEntry;
try
{
jarEntry = jarFile.getJarEntry(entryName);
}
catch (IllegalStateException ex)
{
throw new ClassNotFoundException(name, ex);
}
if (jarEntry == null)
{
throw new ClassNotFoundException(name);
}
try
{
InputStream inputStream = jarFile.getInputStream(jarEntry);
if (inputStream == null)
{
throw new ClassNotFoundException(name);
}
byte[] bytes = ByteStreams.toByteArray(inputStream);
return defineClass(name, bytes, 0, bytes.length);
}
catch (IOException e)
{
throw new ClassNotFoundException(null, e);
}
}
};
// load all of the classes in this jar; after the jar is closed the classloader
// will no longer be able to look up classes
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry jarEntry = entries.nextElement();
String name = jarEntry.getName();
if (name.endsWith(".class"))
{
name = name.substring(0, name.length() - 6);
classLoader.loadClass(name);
}
}
return classLoader;
}
}
private Applet loadClient(RSConfig config, ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException
{
String initialClass = config.getInitialClass();
Class<?> clientClass = classLoader.loadClass(initialClass);
Applet rs = (Applet) clientClass.newInstance();
rs.setStub(new RSAppletStub(config));
if (rs instanceof Client)
{
log.info("client-patch {}", ((Client) rs).getBuildID());
}
return rs;
}
private static Certificate[] getJagexCertificateChain()
{
try
{
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(ClientLoader.class.getResourceAsStream("jagex.crt"));
return certificates.toArray(new Certificate[0]);
}
catch (CertificateException e)
{
throw new RuntimeException("Unable to parse pinned certificates", e);
}
}
private void verifyJarEntry(JarEntry je, Certificate[] certs) throws VerificationException
{
switch (je.getName())
{
case "META-INF/JAGEXLTD.SF":
case "META-INF/JAGEXLTD.RSA":
// You can't sign the signing files
return;
default:
if (!Arrays.equals(je.getCertificates(), certs))
{
throw new VerificationException("Unable to verify jar entry: " + je.getName());
}
}
}
private void verifyWholeJar(JarInputStream jis, Certificate[] certs) throws IOException, VerificationException
{
for (JarEntry je; (je = jis.getNextJarEntry()) != null; )
{
jis.skip(Long.MAX_VALUE);
verifyJarEntry(je, certs);
}
}
}
| clientloader: don't fallback to Jagex hostnames when using fallback config
| runelite-client/src/main/java/net/runelite/client/rs/ClientLoader.java | clientloader: don't fallback to Jagex hostnames when using fallback config | <ide><path>unelite-client/src/main/java/net/runelite/client/rs/ClientLoader.java
<ide> {
<ide> log.warn("Failed to download gamepack from \"{}\"", url, e);
<ide>
<del> if (attempt >= NUM_ATTEMPTS)
<add> // With fallback config do 1 attempt (there are no additional urls to try)
<add> if (config.isFallback() || attempt >= NUM_ATTEMPTS)
<ide> {
<ide> throw e;
<ide> } |
|
Java | apache-2.0 | 53f956fb57dd5601d2e3ca9289207d21796cdc4d | 0 | bowenli86/flink,tillrohrmann/flink,kaibozhou/flink,zentol/flink,xccui/flink,StephanEwen/incubator-flink,jinglining/flink,jinglining/flink,jinglining/flink,sunjincheng121/flink,lincoln-lil/flink,zjureel/flink,godfreyhe/flink,godfreyhe/flink,GJL/flink,lincoln-lil/flink,kaibozhou/flink,zjureel/flink,twalthr/flink,wwjiang007/flink,tillrohrmann/flink,tzulitai/flink,zjureel/flink,zjureel/flink,aljoscha/flink,rmetzger/flink,godfreyhe/flink,kaibozhou/flink,apache/flink,godfreyhe/flink,kl0u/flink,hequn8128/flink,GJL/flink,sunjincheng121/flink,sunjincheng121/flink,tony810430/flink,kaibozhou/flink,tzulitai/flink,tony810430/flink,aljoscha/flink,bowenli86/flink,zentol/flink,tillrohrmann/flink,apache/flink,hequn8128/flink,wwjiang007/flink,wwjiang007/flink,twalthr/flink,aljoscha/flink,wwjiang007/flink,wwjiang007/flink,darionyaphet/flink,greghogan/flink,rmetzger/flink,xccui/flink,jinglining/flink,apache/flink,kl0u/flink,hequn8128/flink,sunjincheng121/flink,tillrohrmann/flink,gyfora/flink,godfreyhe/flink,clarkyzl/flink,gyfora/flink,clarkyzl/flink,xccui/flink,jinglining/flink,rmetzger/flink,apache/flink,lincoln-lil/flink,tzulitai/flink,greghogan/flink,tzulitai/flink,apache/flink,zentol/flink,twalthr/flink,twalthr/flink,bowenli86/flink,clarkyzl/flink,kaibozhou/flink,xccui/flink,GJL/flink,kl0u/flink,godfreyhe/flink,apache/flink,gyfora/flink,darionyaphet/flink,bowenli86/flink,StephanEwen/incubator-flink,zjureel/flink,zjureel/flink,clarkyzl/flink,kl0u/flink,zentol/flink,apache/flink,zentol/flink,rmetzger/flink,twalthr/flink,rmetzger/flink,darionyaphet/flink,StephanEwen/incubator-flink,tzulitai/flink,bowenli86/flink,sunjincheng121/flink,xccui/flink,greghogan/flink,StephanEwen/incubator-flink,tony810430/flink,rmetzger/flink,tillrohrmann/flink,StephanEwen/incubator-flink,gyfora/flink,zentol/flink,godfreyhe/flink,tillrohrmann/flink,GJL/flink,wwjiang007/flink,kl0u/flink,xccui/flink,clarkyzl/flink,kl0u/flink,hequn8128/flink,aljoscha/flink,GJL/flink,jinglining/flink,tony810430/flink,darionyaphet/flink,kaibozhou/flink,lincoln-lil/flink,zjureel/flink,aljoscha/flink,darionyaphet/flink,greghogan/flink,gyfora/flink,tony810430/flink,xccui/flink,aljoscha/flink,tillrohrmann/flink,tzulitai/flink,hequn8128/flink,lincoln-lil/flink,wwjiang007/flink,lincoln-lil/flink,gyfora/flink,tony810430/flink,greghogan/flink,greghogan/flink,gyfora/flink,tony810430/flink,hequn8128/flink,lincoln-lil/flink,StephanEwen/incubator-flink,twalthr/flink,GJL/flink,rmetzger/flink,bowenli86/flink,sunjincheng121/flink,twalthr/flink,zentol/flink | /*
* 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.
*/
package org.apache.flink.test.recovery;
import org.apache.flink.api.common.ExecutionMode;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Deadline;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.HighAvailabilityOptions;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.configuration.NettyShuffleEnvironmentOptions;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.concurrent.ScheduledExecutorServiceAdapter;
import org.apache.flink.runtime.dispatcher.DispatcherGateway;
import org.apache.flink.runtime.dispatcher.DispatcherId;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServicesUtils;
import org.apache.flink.runtime.leaderelection.TestingListener;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalService;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.RpcUtils;
import org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils;
import org.apache.flink.runtime.taskexecutor.TaskManagerRunner;
import org.apache.flink.runtime.testingUtils.TestingUtils;
import org.apache.flink.runtime.testutils.DispatcherProcess;
import org.apache.flink.runtime.testutils.ZooKeeperTestUtils;
import org.apache.flink.runtime.zookeeper.ZooKeeperTestEnvironment;
import org.apache.flink.util.Collector;
import org.apache.flink.util.TestLogger;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
/**
* Verify behaviour in case of JobManager process failure during job execution.
*
* <p>The test works with multiple job managers processes by spawning JVMs.
*
* <p>Initially, it starts two TaskManager (2 slots each) and two JobManager JVMs.
*
* <p>It submits a program with parallelism 4 and waits until all tasks are brought up.
* Coordination between the test and the tasks happens via checking for the existence of
* temporary files. It then kills the leading JobManager process. The recovery should restart the
* tasks on the new JobManager.
*
* <p>This follows the same structure as {@link AbstractTaskManagerProcessFailureRecoveryTest}.
*/
@SuppressWarnings("serial")
@RunWith(Parameterized.class)
public class JobManagerHAProcessFailureRecoveryITCase extends TestLogger {
private static ZooKeeperTestEnvironment zooKeeper;
private static final Duration TEST_TIMEOUT = Duration.ofMinutes(5);
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@BeforeClass
public static void setup() {
zooKeeper = new ZooKeeperTestEnvironment(1);
}
@Before
public void cleanUp() throws Exception {
zooKeeper.deleteAll();
}
@AfterClass
public static void tearDown() throws Exception {
if (zooKeeper != null) {
zooKeeper.shutdown();
}
}
protected static final String READY_MARKER_FILE_PREFIX = "ready_";
protected static final String FINISH_MARKER_FILE_PREFIX = "finish_";
protected static final String PROCEED_MARKER_FILE = "proceed";
protected static final int PARALLELISM = 4;
// --------------------------------------------------------------------------------------------
// Parametrization (run pipelined and batch)
// --------------------------------------------------------------------------------------------
private final ExecutionMode executionMode;
public JobManagerHAProcessFailureRecoveryITCase(ExecutionMode executionMode) {
this.executionMode = executionMode;
}
@Parameterized.Parameters(name = "ExecutionMode {0}")
public static Collection<Object[]> executionMode() {
return Arrays.asList(new Object[][]{
{ ExecutionMode.PIPELINED},
{ExecutionMode.BATCH}});
}
/**
* Test program with JobManager failure.
*
* @param zkQuorum ZooKeeper quorum to connect to
* @param coordinateDir Coordination directory
* @throws Exception
*/
private void testJobManagerFailure(String zkQuorum, final File coordinateDir, final File zookeeperStoragePath) throws Exception {
Configuration config = new Configuration();
config.setString(HighAvailabilityOptions.HA_MODE, "ZOOKEEPER");
config.setString(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM, zkQuorum);
config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, zookeeperStoragePath.getAbsolutePath());
ExecutionEnvironment env = ExecutionEnvironment.createRemoteEnvironment(
"leader", 1, config);
env.setParallelism(PARALLELISM);
env.setRestartStrategy(RestartStrategies.fixedDelayRestart(1, 0L));
env.getConfig().setExecutionMode(executionMode);
final long numElements = 100000L;
final DataSet<Long> result = env.generateSequence(1, numElements)
// make sure every mapper is involved (no one is skipped because of lazy split assignment)
.rebalance()
// the majority of the behavior is in the MapFunction
.map(new RichMapFunction<Long, Long>() {
private final File proceedFile = new File(coordinateDir, PROCEED_MARKER_FILE);
private boolean markerCreated = false;
private boolean checkForProceedFile = true;
@Override
public Long map(Long value) throws Exception {
if (!markerCreated) {
int taskIndex = getRuntimeContext().getIndexOfThisSubtask();
AbstractTaskManagerProcessFailureRecoveryTest.touchFile(
new File(coordinateDir, READY_MARKER_FILE_PREFIX + taskIndex));
markerCreated = true;
}
// check if the proceed file exists
if (checkForProceedFile) {
if (proceedFile.exists()) {
checkForProceedFile = false;
}
else {
// otherwise wait so that we make slow progress
Thread.sleep(100);
}
}
return value;
}
})
.reduce(new ReduceFunction<Long>() {
@Override
public Long reduce(Long value1, Long value2) {
return value1 + value2;
}
})
// The check is done in the mapper, because the client can currently not handle
// job manager losses/reconnects.
.flatMap(new RichFlatMapFunction<Long, Long>() {
@Override
public void flatMap(Long value, Collector<Long> out) throws Exception {
assertEquals(numElements * (numElements + 1L) / 2L, (long) value);
int taskIndex = getRuntimeContext().getIndexOfThisSubtask();
AbstractTaskManagerProcessFailureRecoveryTest.touchFile(
new File(coordinateDir, FINISH_MARKER_FILE_PREFIX + taskIndex));
}
});
result.output(new DiscardingOutputFormat<Long>());
env.execute();
}
@Test
public void testDispatcherProcessFailure() throws Exception {
final Time timeout = Time.seconds(30L);
final File zookeeperStoragePath = temporaryFolder.newFolder();
// Config
final int numberOfJobManagers = 2;
final int numberOfTaskManagers = 2;
final int numberOfSlotsPerTaskManager = 2;
assertEquals(PARALLELISM, numberOfTaskManagers * numberOfSlotsPerTaskManager);
// Job managers
final DispatcherProcess[] dispatcherProcesses = new DispatcherProcess[numberOfJobManagers];
// Task managers
TaskManagerRunner[] taskManagerRunners = new TaskManagerRunner[numberOfTaskManagers];
HighAvailabilityServices highAvailabilityServices = null;
LeaderRetrievalService leaderRetrievalService = null;
// Coordination between the processes goes through a directory
File coordinateTempDir = null;
// Cluster config
Configuration config = ZooKeeperTestUtils.createZooKeeperHAConfig(
zooKeeper.getConnectString(), zookeeperStoragePath.getPath());
// Task manager configuration
config.set(TaskManagerOptions.MANAGED_MEMORY_SIZE, MemorySize.parse("4m"));
config.setInteger(NettyShuffleEnvironmentOptions.NETWORK_NUM_BUFFERS, 100);
config.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 2);
config.set(TaskManagerOptions.TOTAL_FLINK_MEMORY, MemorySize.parse("512m"));
final RpcService rpcService = AkkaRpcServiceUtils.createRpcService("localhost", 0, config);
try {
final Deadline deadline = Deadline.fromNow(TEST_TIMEOUT);
// Coordination directory
coordinateTempDir = temporaryFolder.newFolder();
// Start first process
dispatcherProcesses[0] = new DispatcherProcess(0, config);
dispatcherProcesses[0].startProcess();
highAvailabilityServices = HighAvailabilityServicesUtils.createAvailableOrEmbeddedServices(
config,
TestingUtils.defaultExecutor());
// Start the task manager process
for (int i = 0; i < numberOfTaskManagers; i++) {
taskManagerRunners[i] = new TaskManagerRunner(config, ResourceID.generate());
taskManagerRunners[i].start();
}
// Leader listener
TestingListener leaderListener = new TestingListener();
leaderRetrievalService = highAvailabilityServices.getDispatcherLeaderRetriever();
leaderRetrievalService.start(leaderListener);
// Initial submission
leaderListener.waitForNewLeader(deadline.timeLeft().toMillis());
String leaderAddress = leaderListener.getAddress();
UUID leaderId = leaderListener.getLeaderSessionID();
final CompletableFuture<DispatcherGateway> dispatcherGatewayFuture = rpcService.connect(
leaderAddress,
DispatcherId.fromUuid(leaderId),
DispatcherGateway.class);
final DispatcherGateway dispatcherGateway = dispatcherGatewayFuture.get();
// Wait for all task managers to connect to the leading job manager
waitForTaskManagers(numberOfTaskManagers, dispatcherGateway, deadline.timeLeft());
final File coordinateDirClosure = coordinateTempDir;
final Throwable[] errorRef = new Throwable[1];
// we trigger program execution in a separate thread
Thread programTrigger = new Thread("Program Trigger") {
@Override
public void run() {
try {
testJobManagerFailure(zooKeeper.getConnectString(), coordinateDirClosure, zookeeperStoragePath);
}
catch (Throwable t) {
t.printStackTrace();
errorRef[0] = t;
}
}
};
//start the test program
programTrigger.start();
// wait until all marker files are in place, indicating that all tasks have started
AbstractTaskManagerProcessFailureRecoveryTest.waitForMarkerFiles(coordinateTempDir,
READY_MARKER_FILE_PREFIX, PARALLELISM, deadline.timeLeft().toMillis());
// Kill one of the job managers and trigger recovery
dispatcherProcesses[0].destroy();
dispatcherProcesses[1] = new DispatcherProcess(1, config);
dispatcherProcesses[1].startProcess();
// we create the marker file which signals the program functions tasks that they can complete
AbstractTaskManagerProcessFailureRecoveryTest.touchFile(new File(coordinateTempDir, PROCEED_MARKER_FILE));
programTrigger.join(deadline.timeLeft().toMillis());
// We wait for the finish marker file. We don't wait for the program trigger, because
// we submit in detached mode.
AbstractTaskManagerProcessFailureRecoveryTest.waitForMarkerFiles(coordinateTempDir,
FINISH_MARKER_FILE_PREFIX, 1, deadline.timeLeft().toMillis());
// check that the program really finished
assertFalse("The program did not finish in time", programTrigger.isAlive());
// check whether the program encountered an error
if (errorRef[0] != null) {
Throwable error = errorRef[0];
error.printStackTrace();
fail("The program encountered a " + error.getClass().getSimpleName() + " : " + error.getMessage());
}
}
catch (Throwable t) {
// Print early (in some situations the process logs get too big
// for Travis and the root problem is not shown)
t.printStackTrace();
for (DispatcherProcess p : dispatcherProcesses) {
if (p != null) {
p.printProcessLog();
}
}
throw t;
}
finally {
for (int i = 0; i < numberOfTaskManagers; i++) {
if (taskManagerRunners[i] != null) {
taskManagerRunners[i].close();
}
}
if (leaderRetrievalService != null) {
leaderRetrievalService.stop();
}
for (DispatcherProcess dispatcherProcess : dispatcherProcesses) {
if (dispatcherProcess != null) {
dispatcherProcess.destroy();
}
}
if (highAvailabilityServices != null) {
highAvailabilityServices.closeAndCleanupAllData();
}
RpcUtils.terminateRpcService(rpcService, timeout);
// Delete coordination directory
if (coordinateTempDir != null) {
try {
FileUtils.deleteDirectory(coordinateTempDir);
}
catch (Throwable ignored) {
}
}
}
}
private void waitForTaskManagers(int numberOfTaskManagers, DispatcherGateway dispatcherGateway, Duration timeLeft) throws ExecutionException, InterruptedException {
FutureUtils.retrySuccessfulWithDelay(
() -> dispatcherGateway.requestClusterOverview(Time.milliseconds(timeLeft.toMillis())),
Time.milliseconds(50L),
org.apache.flink.api.common.time.Deadline.fromNow(Duration.ofMillis(timeLeft.toMillis())),
clusterOverview -> clusterOverview.getNumTaskManagersConnected() >= numberOfTaskManagers,
new ScheduledExecutorServiceAdapter(Executors.newSingleThreadScheduledExecutor()))
.get();
}
}
| flink-tests/src/test/java/org/apache/flink/test/recovery/JobManagerHAProcessFailureRecoveryITCase.java | /*
* 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.
*/
package org.apache.flink.test.recovery;
import org.apache.flink.api.common.ExecutionMode;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.HighAvailabilityOptions;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.configuration.NettyShuffleEnvironmentOptions;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.concurrent.ScheduledExecutorServiceAdapter;
import org.apache.flink.runtime.dispatcher.DispatcherGateway;
import org.apache.flink.runtime.dispatcher.DispatcherId;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServicesUtils;
import org.apache.flink.runtime.leaderelection.TestingListener;
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalService;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.RpcUtils;
import org.apache.flink.runtime.rpc.akka.AkkaRpcServiceUtils;
import org.apache.flink.runtime.taskexecutor.TaskManagerRunner;
import org.apache.flink.runtime.testingUtils.TestingUtils;
import org.apache.flink.runtime.testutils.DispatcherProcess;
import org.apache.flink.runtime.testutils.ZooKeeperTestUtils;
import org.apache.flink.runtime.zookeeper.ZooKeeperTestEnvironment;
import org.apache.flink.util.Collector;
import org.apache.flink.util.TestLogger;
import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import scala.concurrent.duration.Deadline;
import scala.concurrent.duration.FiniteDuration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
/**
* Verify behaviour in case of JobManager process failure during job execution.
*
* <p>The test works with multiple job managers processes by spawning JVMs.
*
* <p>Initially, it starts two TaskManager (2 slots each) and two JobManager JVMs.
*
* <p>It submits a program with parallelism 4 and waits until all tasks are brought up.
* Coordination between the test and the tasks happens via checking for the existence of
* temporary files. It then kills the leading JobManager process. The recovery should restart the
* tasks on the new JobManager.
*
* <p>This follows the same structure as {@link AbstractTaskManagerProcessFailureRecoveryTest}.
*/
@SuppressWarnings("serial")
@RunWith(Parameterized.class)
public class JobManagerHAProcessFailureRecoveryITCase extends TestLogger {
private static ZooKeeperTestEnvironment zooKeeper;
private static final FiniteDuration TestTimeOut = new FiniteDuration(5, TimeUnit.MINUTES);
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@BeforeClass
public static void setup() {
zooKeeper = new ZooKeeperTestEnvironment(1);
}
@Before
public void cleanUp() throws Exception {
zooKeeper.deleteAll();
}
@AfterClass
public static void tearDown() throws Exception {
if (zooKeeper != null) {
zooKeeper.shutdown();
}
}
protected static final String READY_MARKER_FILE_PREFIX = "ready_";
protected static final String FINISH_MARKER_FILE_PREFIX = "finish_";
protected static final String PROCEED_MARKER_FILE = "proceed";
protected static final int PARALLELISM = 4;
// --------------------------------------------------------------------------------------------
// Parametrization (run pipelined and batch)
// --------------------------------------------------------------------------------------------
private final ExecutionMode executionMode;
public JobManagerHAProcessFailureRecoveryITCase(ExecutionMode executionMode) {
this.executionMode = executionMode;
}
@Parameterized.Parameters(name = "ExecutionMode {0}")
public static Collection<Object[]> executionMode() {
return Arrays.asList(new Object[][]{
{ ExecutionMode.PIPELINED},
{ExecutionMode.BATCH}});
}
/**
* Test program with JobManager failure.
*
* @param zkQuorum ZooKeeper quorum to connect to
* @param coordinateDir Coordination directory
* @throws Exception
*/
private void testJobManagerFailure(String zkQuorum, final File coordinateDir, final File zookeeperStoragePath) throws Exception {
Configuration config = new Configuration();
config.setString(HighAvailabilityOptions.HA_MODE, "ZOOKEEPER");
config.setString(HighAvailabilityOptions.HA_ZOOKEEPER_QUORUM, zkQuorum);
config.setString(HighAvailabilityOptions.HA_STORAGE_PATH, zookeeperStoragePath.getAbsolutePath());
ExecutionEnvironment env = ExecutionEnvironment.createRemoteEnvironment(
"leader", 1, config);
env.setParallelism(PARALLELISM);
env.setRestartStrategy(RestartStrategies.fixedDelayRestart(1, 0L));
env.getConfig().setExecutionMode(executionMode);
final long numElements = 100000L;
final DataSet<Long> result = env.generateSequence(1, numElements)
// make sure every mapper is involved (no one is skipped because of lazy split assignment)
.rebalance()
// the majority of the behavior is in the MapFunction
.map(new RichMapFunction<Long, Long>() {
private final File proceedFile = new File(coordinateDir, PROCEED_MARKER_FILE);
private boolean markerCreated = false;
private boolean checkForProceedFile = true;
@Override
public Long map(Long value) throws Exception {
if (!markerCreated) {
int taskIndex = getRuntimeContext().getIndexOfThisSubtask();
AbstractTaskManagerProcessFailureRecoveryTest.touchFile(
new File(coordinateDir, READY_MARKER_FILE_PREFIX + taskIndex));
markerCreated = true;
}
// check if the proceed file exists
if (checkForProceedFile) {
if (proceedFile.exists()) {
checkForProceedFile = false;
}
else {
// otherwise wait so that we make slow progress
Thread.sleep(100);
}
}
return value;
}
})
.reduce(new ReduceFunction<Long>() {
@Override
public Long reduce(Long value1, Long value2) {
return value1 + value2;
}
})
// The check is done in the mapper, because the client can currently not handle
// job manager losses/reconnects.
.flatMap(new RichFlatMapFunction<Long, Long>() {
@Override
public void flatMap(Long value, Collector<Long> out) throws Exception {
assertEquals(numElements * (numElements + 1L) / 2L, (long) value);
int taskIndex = getRuntimeContext().getIndexOfThisSubtask();
AbstractTaskManagerProcessFailureRecoveryTest.touchFile(
new File(coordinateDir, FINISH_MARKER_FILE_PREFIX + taskIndex));
}
});
result.output(new DiscardingOutputFormat<Long>());
env.execute();
}
@Test
public void testDispatcherProcessFailure() throws Exception {
final Time timeout = Time.seconds(30L);
final File zookeeperStoragePath = temporaryFolder.newFolder();
// Config
final int numberOfJobManagers = 2;
final int numberOfTaskManagers = 2;
final int numberOfSlotsPerTaskManager = 2;
assertEquals(PARALLELISM, numberOfTaskManagers * numberOfSlotsPerTaskManager);
// Job managers
final DispatcherProcess[] dispatcherProcesses = new DispatcherProcess[numberOfJobManagers];
// Task managers
TaskManagerRunner[] taskManagerRunners = new TaskManagerRunner[numberOfTaskManagers];
HighAvailabilityServices highAvailabilityServices = null;
LeaderRetrievalService leaderRetrievalService = null;
// Coordination between the processes goes through a directory
File coordinateTempDir = null;
// Cluster config
Configuration config = ZooKeeperTestUtils.createZooKeeperHAConfig(
zooKeeper.getConnectString(), zookeeperStoragePath.getPath());
// Task manager configuration
config.set(TaskManagerOptions.MANAGED_MEMORY_SIZE, MemorySize.parse("4m"));
config.setInteger(NettyShuffleEnvironmentOptions.NETWORK_NUM_BUFFERS, 100);
config.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 2);
config.set(TaskManagerOptions.TOTAL_FLINK_MEMORY, MemorySize.parse("512m"));
final RpcService rpcService = AkkaRpcServiceUtils.createRpcService("localhost", 0, config);
try {
final Deadline deadline = TestTimeOut.fromNow();
// Coordination directory
coordinateTempDir = temporaryFolder.newFolder();
// Start first process
dispatcherProcesses[0] = new DispatcherProcess(0, config);
dispatcherProcesses[0].startProcess();
highAvailabilityServices = HighAvailabilityServicesUtils.createAvailableOrEmbeddedServices(
config,
TestingUtils.defaultExecutor());
// Start the task manager process
for (int i = 0; i < numberOfTaskManagers; i++) {
taskManagerRunners[i] = new TaskManagerRunner(config, ResourceID.generate());
taskManagerRunners[i].start();
}
// Leader listener
TestingListener leaderListener = new TestingListener();
leaderRetrievalService = highAvailabilityServices.getDispatcherLeaderRetriever();
leaderRetrievalService.start(leaderListener);
// Initial submission
leaderListener.waitForNewLeader(deadline.timeLeft().toMillis());
String leaderAddress = leaderListener.getAddress();
UUID leaderId = leaderListener.getLeaderSessionID();
final CompletableFuture<DispatcherGateway> dispatcherGatewayFuture = rpcService.connect(
leaderAddress,
DispatcherId.fromUuid(leaderId),
DispatcherGateway.class);
final DispatcherGateway dispatcherGateway = dispatcherGatewayFuture.get();
// Wait for all task managers to connect to the leading job manager
waitForTaskManagers(numberOfTaskManagers, dispatcherGateway, deadline.timeLeft());
final File coordinateDirClosure = coordinateTempDir;
final Throwable[] errorRef = new Throwable[1];
// we trigger program execution in a separate thread
Thread programTrigger = new Thread("Program Trigger") {
@Override
public void run() {
try {
testJobManagerFailure(zooKeeper.getConnectString(), coordinateDirClosure, zookeeperStoragePath);
}
catch (Throwable t) {
t.printStackTrace();
errorRef[0] = t;
}
}
};
//start the test program
programTrigger.start();
// wait until all marker files are in place, indicating that all tasks have started
AbstractTaskManagerProcessFailureRecoveryTest.waitForMarkerFiles(coordinateTempDir,
READY_MARKER_FILE_PREFIX, PARALLELISM, deadline.timeLeft().toMillis());
// Kill one of the job managers and trigger recovery
dispatcherProcesses[0].destroy();
dispatcherProcesses[1] = new DispatcherProcess(1, config);
dispatcherProcesses[1].startProcess();
// we create the marker file which signals the program functions tasks that they can complete
AbstractTaskManagerProcessFailureRecoveryTest.touchFile(new File(coordinateTempDir, PROCEED_MARKER_FILE));
programTrigger.join(deadline.timeLeft().toMillis());
// We wait for the finish marker file. We don't wait for the program trigger, because
// we submit in detached mode.
AbstractTaskManagerProcessFailureRecoveryTest.waitForMarkerFiles(coordinateTempDir,
FINISH_MARKER_FILE_PREFIX, 1, deadline.timeLeft().toMillis());
// check that the program really finished
assertFalse("The program did not finish in time", programTrigger.isAlive());
// check whether the program encountered an error
if (errorRef[0] != null) {
Throwable error = errorRef[0];
error.printStackTrace();
fail("The program encountered a " + error.getClass().getSimpleName() + " : " + error.getMessage());
}
}
catch (Throwable t) {
// Print early (in some situations the process logs get too big
// for Travis and the root problem is not shown)
t.printStackTrace();
for (DispatcherProcess p : dispatcherProcesses) {
if (p != null) {
p.printProcessLog();
}
}
throw t;
}
finally {
for (int i = 0; i < numberOfTaskManagers; i++) {
if (taskManagerRunners[i] != null) {
taskManagerRunners[i].close();
}
}
if (leaderRetrievalService != null) {
leaderRetrievalService.stop();
}
for (DispatcherProcess dispatcherProcess : dispatcherProcesses) {
if (dispatcherProcess != null) {
dispatcherProcess.destroy();
}
}
if (highAvailabilityServices != null) {
highAvailabilityServices.closeAndCleanupAllData();
}
RpcUtils.terminateRpcService(rpcService, timeout);
// Delete coordination directory
if (coordinateTempDir != null) {
try {
FileUtils.deleteDirectory(coordinateTempDir);
}
catch (Throwable ignored) {
}
}
}
}
private void waitForTaskManagers(int numberOfTaskManagers, DispatcherGateway dispatcherGateway, FiniteDuration timeLeft) throws ExecutionException, InterruptedException {
FutureUtils.retrySuccessfulWithDelay(
() -> dispatcherGateway.requestClusterOverview(Time.milliseconds(timeLeft.toMillis())),
Time.milliseconds(50L),
org.apache.flink.api.common.time.Deadline.fromNow(Duration.ofMillis(timeLeft.toMillis())),
clusterOverview -> clusterOverview.getNumTaskManagersConnected() >= numberOfTaskManagers,
new ScheduledExecutorServiceAdapter(Executors.newSingleThreadScheduledExecutor()))
.get();
}
}
| [FLINK-10819] Replace with the Flink's Deadline implementation
Remove Scala's Deadline and replace it with Flink's own version.
This closes #10950.
| flink-tests/src/test/java/org/apache/flink/test/recovery/JobManagerHAProcessFailureRecoveryITCase.java | [FLINK-10819] Replace with the Flink's Deadline implementation | <ide><path>link-tests/src/test/java/org/apache/flink/test/recovery/JobManagerHAProcessFailureRecoveryITCase.java
<ide> import org.apache.flink.api.common.functions.RichFlatMapFunction;
<ide> import org.apache.flink.api.common.functions.RichMapFunction;
<ide> import org.apache.flink.api.common.restartstrategy.RestartStrategies;
<add>import org.apache.flink.api.common.time.Deadline;
<ide> import org.apache.flink.api.common.time.Time;
<ide> import org.apache.flink.api.java.DataSet;
<ide> import org.apache.flink.api.java.ExecutionEnvironment;
<ide> import java.util.concurrent.CompletableFuture;
<ide> import java.util.concurrent.ExecutionException;
<ide> import java.util.concurrent.Executors;
<del>import java.util.concurrent.TimeUnit;
<del>
<del>import scala.concurrent.duration.Deadline;
<del>import scala.concurrent.duration.FiniteDuration;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertFalse;
<ide>
<ide> private static ZooKeeperTestEnvironment zooKeeper;
<ide>
<del> private static final FiniteDuration TestTimeOut = new FiniteDuration(5, TimeUnit.MINUTES);
<add> private static final Duration TEST_TIMEOUT = Duration.ofMinutes(5);
<ide>
<ide> @Rule
<ide> public final TemporaryFolder temporaryFolder = new TemporaryFolder();
<ide> final RpcService rpcService = AkkaRpcServiceUtils.createRpcService("localhost", 0, config);
<ide>
<ide> try {
<del> final Deadline deadline = TestTimeOut.fromNow();
<add> final Deadline deadline = Deadline.fromNow(TEST_TIMEOUT);
<ide>
<ide> // Coordination directory
<ide> coordinateTempDir = temporaryFolder.newFolder();
<ide> }
<ide> }
<ide>
<del> private void waitForTaskManagers(int numberOfTaskManagers, DispatcherGateway dispatcherGateway, FiniteDuration timeLeft) throws ExecutionException, InterruptedException {
<add> private void waitForTaskManagers(int numberOfTaskManagers, DispatcherGateway dispatcherGateway, Duration timeLeft) throws ExecutionException, InterruptedException {
<ide> FutureUtils.retrySuccessfulWithDelay(
<ide> () -> dispatcherGateway.requestClusterOverview(Time.milliseconds(timeLeft.toMillis())),
<ide> Time.milliseconds(50L), |
|
Java | agpl-3.0 | 1e91e72b1fc5fa812e8ea4d015c25a0168b87f30 | 0 | y0ke/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,y0ke/actor-platform,y0ke/actor-platform,EaglesoftZJ/actor-platform,y0ke/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,y0ke/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,y0ke/actor-platform,y0ke/actor-platform,y0ke/actor-platform | package im.actor.sdk.controllers.conversation;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import im.actor.sdk.ActorSDK;
import im.actor.sdk.ActorStyle;
import im.actor.sdk.R;
import im.actor.sdk.controllers.activity.BaseActivity;
import im.actor.sdk.util.KeyboardHelper;
import im.actor.sdk.view.TintImageView;
import im.actor.sdk.view.emoji.keyboard.BaseKeyboard;
import im.actor.sdk.view.emoji.keyboard.KeyboardStatusListener;
import im.actor.sdk.view.emoji.keyboard.emoji.EmojiKeyboard;
import static im.actor.sdk.util.ActorSDKMessenger.messenger;
public abstract class ActorEditTextActivity extends BaseActivity {
//////////////////////////////////
// Input panel
//////////////////////////////////
// Message edit text
protected EditText messageEditText;
// Send message button
protected TintImageView sendButton;
// Attach button
protected ImageButton attachButton;
// Removed from group panel
protected View removedFromGroup;
// Helper for hide/show keyboard
protected KeyboardHelper keyboardUtils;
// Emoji keyboard
protected EmojiKeyboard emojiKeyboard;
protected ImageView emojiButton;
protected FrameLayout sendContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawable(new ColorDrawable(ActorSDK.sharedActor().style.getMainBackgroundColor()));
// Setting main layout
setContentView(R.layout.activity_dialog);
// Setting fragment
setFragment(savedInstanceState);
ActorStyle style = ActorSDK.sharedActor().style;
// Message container
FrameLayout messageContainer = (FrameLayout) findViewById(R.id.fl_send_panel);
messageContainer.setBackgroundColor(style.getMainBackgroundColor());
// Message Body
messageEditText = (EditText) findViewById(R.id.et_message);
messageEditText.setTextColor(style.getTextPrimaryColor());
messageEditText.setHintTextColor(style.getTextHintColor());
// messageEditText.addTextChangedListener(new TextWatcherImp());
// Handling selection changed
// messageEditText.setOnSelectionListener(new SelectionListenerEditText.OnSelectedListener() {
// @Override
// public void onSelected(int selStart, int selEnd) {
// //TODO: Fix full select
// Editable text = messageEditText.getText();
// if (selEnd != selStart && text.charAt(selStart) == '@') {
// if (text.charAt(selEnd - 1) == MENTION_BOUNDS_CHR) {
// messageEditText.setSelection(selStart + 2, selEnd - 1);
// } else if (text.length() >= 3 && text.charAt(selEnd - 2) == MENTION_BOUNDS_CHR) {
// messageEditText.setSelection(selStart + 2, selEnd - 2);
// }
// }
// }
// });
// Hardware keyboard events
messageEditText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int keycode, KeyEvent keyEvent) {
if (messenger().isSendByEnterEnabled()) {
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keycode == KeyEvent.KEYCODE_ENTER) {
onSendButtonPressed();
return true;
}
}
return false;
}
});
// Software keyboard events
messageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_SEND) {
onSendButtonPressed();
return true;
}
if (i == EditorInfo.IME_ACTION_DONE) {
onSendButtonPressed();
return true;
}
if (messenger().isSendByEnterEnabled()) {
if (keyEvent != null && i == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
onSendButtonPressed();
return true;
}
}
return false;
}
});
// Send Button
sendButton = (TintImageView) findViewById(R.id.ib_send);
sendButton.setResource(R.drawable.conv_send);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onSendButtonPressed();
}
});
// Attach Button
attachButton = (ImageButton) findViewById(R.id.ib_attach);
attachButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onAttachButtonClicked();
}
});
// Kick panel
removedFromGroup = findViewById(R.id.kickedFromChat);
removedFromGroup.setBackgroundColor(ActorSDK.sharedActor().style.getMainBackgroundColor());
((TextView) removedFromGroup.findViewById(R.id.kicked_text)).setTextColor(style.getMainColor());
// Emoji keyboard
emojiButton = (ImageView) findViewById(R.id.ib_emoji);
emojiKeyboard = new EmojiKeyboard(this);
emojiKeyboard.setKeyboardStatusListener(new KeyboardStatusListener() {
@Override
public void onDismiss() {
emojiButton.setImageResource(R.drawable.ic_emoji);
}
@Override
public void onShow() {
emojiButton.setImageResource(R.drawable.ic_keyboard);
}
});
emojiButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
emojiKeyboard.toggle(messageEditText);
}
});
sendContainer = (FrameLayout) findViewById(R.id.sendContainer);
// Keyboard helper for show/hide keyboard
keyboardUtils = new KeyboardHelper(this);
}
protected void setFragment(Bundle savedInstanceState) {
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.messagesFragment, onCreateFragment())
.commit();
}
}
protected abstract Fragment onCreateFragment();
protected void onSendButtonPressed() {
}
protected void onAttachButtonClicked() {
}
@Override
protected void onPause() {
super.onPause();
// Destroy emoji keyboard
emojiKeyboard.destroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BaseKeyboard.OVERLAY_PERMISSION_REQ_CODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Toast.makeText(this, "Ooops, emoji Keyboard needs overlay permission", Toast.LENGTH_LONG).show();
} else {
emojiKeyboard.showChecked();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onDestroy() {
super.onDestroy();
emojiKeyboard.release();
}
}
| actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/conversation/ActorEditTextActivity.java | package im.actor.sdk.controllers.conversation;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import im.actor.sdk.ActorSDK;
import im.actor.sdk.ActorStyle;
import im.actor.sdk.R;
import im.actor.sdk.controllers.activity.BaseActivity;
import im.actor.sdk.util.KeyboardHelper;
import im.actor.sdk.view.TintImageView;
import im.actor.sdk.view.emoji.keyboard.BaseKeyboard;
import im.actor.sdk.view.emoji.keyboard.KeyboardStatusListener;
import im.actor.sdk.view.emoji.keyboard.emoji.EmojiKeyboard;
import static im.actor.sdk.util.ActorSDKMessenger.messenger;
public abstract class ActorEditTextActivity extends BaseActivity {
//////////////////////////////////
// Input panel
//////////////////////////////////
// Message edit text
protected EditText messageEditText;
// Send message button
protected TintImageView sendButton;
// Attach button
protected ImageButton attachButton;
// Removed from group panel
protected View removedFromGroup;
// Helper for hide/show keyboard
protected KeyboardHelper keyboardUtils;
// Emoji keyboard
protected EmojiKeyboard emojiKeyboard;
protected ImageView emojiButton;
protected FrameLayout sendContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setting transparent BG for keyboard open optimization
getWindow().setBackgroundDrawable(null);
// Setting main layout
setContentView(R.layout.activity_dialog);
// Setting fragment
setFragment(savedInstanceState);
ActorStyle style = ActorSDK.sharedActor().style;
// Message container
FrameLayout messageContainer = (FrameLayout) findViewById(R.id.fl_send_panel);
messageContainer.setBackgroundColor(style.getMainBackgroundColor());
// Message Body
messageEditText = (EditText) findViewById(R.id.et_message);
messageEditText.setTextColor(style.getTextPrimaryColor());
messageEditText.setHintTextColor(style.getTextHintColor());
// messageEditText.addTextChangedListener(new TextWatcherImp());
// Handling selection changed
// messageEditText.setOnSelectionListener(new SelectionListenerEditText.OnSelectedListener() {
// @Override
// public void onSelected(int selStart, int selEnd) {
// //TODO: Fix full select
// Editable text = messageEditText.getText();
// if (selEnd != selStart && text.charAt(selStart) == '@') {
// if (text.charAt(selEnd - 1) == MENTION_BOUNDS_CHR) {
// messageEditText.setSelection(selStart + 2, selEnd - 1);
// } else if (text.length() >= 3 && text.charAt(selEnd - 2) == MENTION_BOUNDS_CHR) {
// messageEditText.setSelection(selStart + 2, selEnd - 2);
// }
// }
// }
// });
// Hardware keyboard events
messageEditText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int keycode, KeyEvent keyEvent) {
if (messenger().isSendByEnterEnabled()) {
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keycode == KeyEvent.KEYCODE_ENTER) {
onSendButtonPressed();
return true;
}
}
return false;
}
});
// Software keyboard events
messageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_SEND) {
onSendButtonPressed();
return true;
}
if (i == EditorInfo.IME_ACTION_DONE) {
onSendButtonPressed();
return true;
}
if (messenger().isSendByEnterEnabled()) {
if (keyEvent != null && i == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
onSendButtonPressed();
return true;
}
}
return false;
}
});
// Send Button
sendButton = (TintImageView) findViewById(R.id.ib_send);
sendButton.setResource(R.drawable.conv_send);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onSendButtonPressed();
}
});
// Attach Button
attachButton = (ImageButton) findViewById(R.id.ib_attach);
attachButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onAttachButtonClicked();
}
});
// Kick panel
removedFromGroup = findViewById(R.id.kickedFromChat);
removedFromGroup.setBackgroundColor(ActorSDK.sharedActor().style.getMainBackgroundColor());
((TextView) removedFromGroup.findViewById(R.id.kicked_text)).setTextColor(style.getMainColor());
// Emoji keyboard
emojiButton = (ImageView) findViewById(R.id.ib_emoji);
emojiKeyboard = new EmojiKeyboard(this);
emojiKeyboard.setKeyboardStatusListener(new KeyboardStatusListener() {
@Override
public void onDismiss() {
emojiButton.setImageResource(R.drawable.ic_emoji);
}
@Override
public void onShow() {
emojiButton.setImageResource(R.drawable.ic_keyboard);
}
});
emojiButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
emojiKeyboard.toggle(messageEditText);
}
});
sendContainer = (FrameLayout) findViewById(R.id.sendContainer);
// Keyboard helper for show/hide keyboard
keyboardUtils = new KeyboardHelper(this);
}
protected void setFragment(Bundle savedInstanceState) {
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.messagesFragment, onCreateFragment())
.commit();
}
}
protected abstract Fragment onCreateFragment();
protected void onSendButtonPressed() {
}
protected void onAttachButtonClicked() {
}
@Override
protected void onPause() {
super.onPause();
// Destroy emoji keyboard
emojiKeyboard.destroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == BaseKeyboard.OVERLAY_PERMISSION_REQ_CODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Toast.makeText(this, "Ooops, emoji Keyboard needs overlay permission", Toast.LENGTH_LONG).show();
} else {
emojiKeyboard.showChecked();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onDestroy() {
super.onDestroy();
emojiKeyboard.release();
}
}
| fix(android): remove blink on keyboard open
| actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/conversation/ActorEditTextActivity.java | fix(android): remove blink on keyboard open | <ide><path>ctor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/conversation/ActorEditTextActivity.java
<ide> package im.actor.sdk.controllers.conversation;
<ide>
<ide> import android.content.Intent;
<add>import android.graphics.drawable.ColorDrawable;
<ide> import android.os.Build;
<ide> import android.os.Bundle;
<ide> import android.provider.Settings;
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide>
<del> // Setting transparent BG for keyboard open optimization
<del> getWindow().setBackgroundDrawable(null);
<add> getWindow().setBackgroundDrawable(new ColorDrawable(ActorSDK.sharedActor().style.getMainBackgroundColor()));
<ide>
<ide> // Setting main layout
<ide> setContentView(R.layout.activity_dialog); |
|
Java | apache-2.0 | 7eb8bb5aa14c950c4338dc5373b9beb8c94ae7a3 | 0 | lettuce-io/lettuce-core,lettuce-io/lettuce-core,lettuce-io/lettuce-core,lettuce-io/lettuce-core,mp911de/lettuce,mp911de/lettuce | /*
* Copyright 2017-2018 the original author or authors.
*
* 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.
*/
package io.lettuce.core.output;
import java.util.*;
/**
* @author Mark Paluch
*/
class OutputFactory {
static <T> List<T> newList(int capacity) {
if (capacity < 1) {
return Collections.emptyList();
}
return new ArrayList<>(Math.max(1, capacity));
}
static <V> Set<V> newSet(int capacity) {
if (capacity < 1) {
return Collections.emptySet();
}
return new LinkedHashSet<>(capacity, 1);
}
}
| src/main/java/io/lettuce/core/output/OutputFactory.java | /*
* Copyright 2017-2018 the original author or authors.
*
* 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.
*/
package io.lettuce.core.output;
import java.util.*;
/**
* @author Mark Paluch
*/
class OutputFactory {
static <T> List<T> newList(int capacity) {
if (capacity < 1) {
return Collections.emptyList();
}
return new ArrayList<>(Math.max(1, capacity));
}
static <V> Set<V> newSet(int capacity) {
if (capacity < 1) {
return Collections.emptySet();
}
return new HashSet<>(capacity, 1);
}
}
| Retain response order for Set responses #823
Lettuce now retains the response order for set results such as smembers. Previously, we used a plain HashSet that did not honor insertion order. Now we're using LinkedHashSet that retains the insertion order for unique elements.
| src/main/java/io/lettuce/core/output/OutputFactory.java | Retain response order for Set responses #823 | <ide><path>rc/main/java/io/lettuce/core/output/OutputFactory.java
<ide> return Collections.emptySet();
<ide> }
<ide>
<del> return new HashSet<>(capacity, 1);
<add> return new LinkedHashSet<>(capacity, 1);
<ide> }
<ide> } |
|
Java | bsd-3-clause | 10dc86ea876ddb5174ca6a72aadf7f78b026da5b | 0 | jthrun/sdl_android,smartdevicelink/sdl_android,914802951/sdl_android,anildahiya/sdl_android,jthrun/sdl_android | package com.smartdevicelink.test.rpc.notifications;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import com.smartdevicelink.marshal.JsonRPCMarshaller;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCMessage;
import com.smartdevicelink.proxy.rpc.AirbagStatus;
import com.smartdevicelink.proxy.rpc.BeltStatus;
import com.smartdevicelink.proxy.rpc.BodyInformation;
import com.smartdevicelink.proxy.rpc.ClusterModeStatus;
import com.smartdevicelink.proxy.rpc.DeviceStatus;
import com.smartdevicelink.proxy.rpc.ECallInfo;
import com.smartdevicelink.proxy.rpc.EmergencyEvent;
import com.smartdevicelink.proxy.rpc.GPSData;
import com.smartdevicelink.proxy.rpc.HeadLampStatus;
import com.smartdevicelink.proxy.rpc.MyKey;
import com.smartdevicelink.proxy.rpc.OnVehicleData;
import com.smartdevicelink.proxy.rpc.SingleTireStatus;
import com.smartdevicelink.proxy.rpc.TireStatus;
import com.smartdevicelink.proxy.rpc.enums.ComponentVolumeStatus;
import com.smartdevicelink.proxy.rpc.enums.PRNDL;
import com.smartdevicelink.proxy.rpc.enums.VehicleDataEventStatus;
import com.smartdevicelink.proxy.rpc.enums.WiperStatus;
import com.smartdevicelink.test.BaseRpcTests;
import com.smartdevicelink.test.utils.JsonUtils;
import com.smartdevicelink.test.utils.Validator;
import com.smartdevicelink.test.utils.VehicleDataHelper;
public class OnVehicleDataTests extends BaseRpcTests{
@Override
protected RPCMessage createMessage(){
return VehicleDataHelper.VEHICLE_DATA;
}
@Override
protected String getMessageType(){
return RPCMessage.KEY_NOTIFICATION;
}
@Override
protected String getCommandType(){
return FunctionID.ON_VEHICLE_DATA;
}
@Override
protected JSONObject getExpectedParameters(int sdlVersion){
JSONObject result = new JSONObject();
try{
result.put(OnVehicleData.KEY_SPEED, VehicleDataHelper.SPEED);
result.put(OnVehicleData.KEY_RPM, VehicleDataHelper.RPM);
result.put(OnVehicleData.KEY_EXTERNAL_TEMPERATURE, VehicleDataHelper.EXTERNAL_TEMPERATURE);
result.put(OnVehicleData.KEY_FUEL_LEVEL, VehicleDataHelper.FUEL_LEVEL);
result.put(OnVehicleData.KEY_VIN, VehicleDataHelper.VIN);
result.put(OnVehicleData.KEY_PRNDL, VehicleDataHelper.PRNDL_FINAL);
result.put(OnVehicleData.KEY_TIRE_PRESSURE, VehicleDataHelper.TIRE_PRESSURE.serializeJSON());
result.put(OnVehicleData.KEY_ENGINE_TORQUE, VehicleDataHelper.ENGINE_TORQUE);
result.put(OnVehicleData.KEY_ODOMETER, VehicleDataHelper.ODOMETER);
result.put(OnVehicleData.KEY_GPS, VehicleDataHelper.GPS.serializeJSON());
result.put(OnVehicleData.KEY_FUEL_LEVEL_STATE, VehicleDataHelper.FUEL_LEVEL_STATE);
result.put(OnVehicleData.KEY_INSTANT_FUEL_CONSUMPTION, VehicleDataHelper.INSTANT_FUEL_CONSUMPTION);
result.put(OnVehicleData.KEY_BELT_STATUS, VehicleDataHelper.BELT_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_BODY_INFORMATION, VehicleDataHelper.BODY_INFORMATION.serializeJSON());
result.put(OnVehicleData.KEY_DEVICE_STATUS, VehicleDataHelper.DEVICE_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_DRIVER_BRAKING, VehicleDataHelper.DRIVER_BRAKING);
result.put(OnVehicleData.KEY_WIPER_STATUS, VehicleDataHelper.WIPER_STATUS);
result.put(OnVehicleData.KEY_HEAD_LAMP_STATUS, VehicleDataHelper.HEAD_LAMP_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_ACC_PEDAL_POSITION, VehicleDataHelper.ACC_PEDAL_POSITION);
result.put(OnVehicleData.KEY_STEERING_WHEEL_ANGLE, VehicleDataHelper.STEERING_WHEEL_ANGLE);
result.put(OnVehicleData.KEY_E_CALL_INFO, VehicleDataHelper.E_CALL_INFO.serializeJSON());
result.put(OnVehicleData.KEY_AIRBAG_STATUS, VehicleDataHelper.AIRBAG_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_EMERGENCY_EVENT, VehicleDataHelper.EMERGENCY_EVENT.serializeJSON());
result.put(OnVehicleData.KEY_CLUSTER_MODE_STATUS, VehicleDataHelper.CLUSTER_MODE_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_MY_KEY, VehicleDataHelper.MY_KEY.serializeJSON());
}catch(JSONException e){
//do nothing
}
return result;
}
public void testSpeed() {
Double copy = ( (OnVehicleData) msg).getSpeed();
assertEquals("Speed does not match input speed", VehicleDataHelper.SPEED, copy);
}
public void testRpm() {
int copy = ( (OnVehicleData) msg).getRpm();
assertEquals("RPM does not match input RPM", VehicleDataHelper.RPM, copy);
}
public void testExternalTemperature() {
Double copy = ( (OnVehicleData) msg).getExternalTemperature();
assertEquals("External temperature does not match input external temperature", VehicleDataHelper.EXTERNAL_TEMPERATURE, copy);
}
public void testFuelLevel() {
Double copy = ( (OnVehicleData) msg).getFuelLevel();
assertEquals("Fuel level does not match input fuel level", VehicleDataHelper.FUEL_LEVEL, copy);
}
public void testVin() {
String copy = ( (OnVehicleData) msg).getVin();
assertEquals("VIN does not match input VIN", VehicleDataHelper.VIN, copy);
}
public void testPRNDL() {
PRNDL copy = ( (OnVehicleData) msg).getPrndl();
assertEquals("PRNDL does not match input PRNDL", VehicleDataHelper.PRNDL_FINAL, copy);
}
public void testTirePressure() {
TireStatus copy = ( (OnVehicleData) msg).getTirePressure();
assertNotSame("Tire pressure was not defensive copied", VehicleDataHelper.TIRE_PRESSURE, copy);
assertTrue("Tire pressure does not match input tire pressure", Validator.validateTireStatus(VehicleDataHelper.TIRE_PRESSURE, copy));
}
public void testEngineTorque() {
Double copy = ( (OnVehicleData) msg).getEngineTorque();
assertEquals("Engine torque does not match input engine torque", VehicleDataHelper.ENGINE_TORQUE, copy);
}
public void testOdometer() {
int copy = ( (OnVehicleData) msg).getOdometer();
assertEquals("Odometer does not match input odometer", VehicleDataHelper.ODOMETER, copy);
}
public void testGps() {
GPSData copy = ( (OnVehicleData) msg).getGps();
assertNotSame("GPS was not defensive copied", VehicleDataHelper.TIRE_PRESSURE, copy);
assertTrue("GPS does not match input GPS", Validator.validateGpsData(VehicleDataHelper.GPS, copy));
}
public void testFuelLevel_State() {
ComponentVolumeStatus copy = ( (OnVehicleData) msg).getFuelLevel_State();
assertEquals("Fuel level does not match input fuel level", VehicleDataHelper.FUEL_LEVEL_STATE, copy);
}
public void testInstantFuelConsumption() {
Double copy = ( (OnVehicleData) msg).getInstantFuelConsumption();
assertEquals("Instant fuel consumption does not match input instant fuel consumption", VehicleDataHelper.INSTANT_FUEL_CONSUMPTION, copy);
}
public void testBeltStatus() {
BeltStatus copy = ( (OnVehicleData) msg).getBeltStatus();
assertNotSame("Belt status was not defensive copied", VehicleDataHelper.BELT_STATUS, copy);
assertTrue("Belt status does not match input belt status", Validator.validateBeltStatus(VehicleDataHelper.BELT_STATUS, copy));
}
public void testBodyInformation() {
BodyInformation copy = ( (OnVehicleData) msg).getBodyInformation();
assertNotSame("Body information was not defensive copied", VehicleDataHelper.BODY_INFORMATION, copy);
assertTrue("Body information does not match input body information", Validator.validateBodyInformation(VehicleDataHelper.BODY_INFORMATION, copy));
}
public void testDeviceStatus() {
DeviceStatus copy = ( (OnVehicleData) msg).getDeviceStatus();
assertNotSame("Device status was not defensive copied", VehicleDataHelper.DEVICE_STATUS, copy);
assertTrue("Device status does not match input device status", Validator.validateDeviceStatus(VehicleDataHelper.DEVICE_STATUS, copy));
}
public void testDriverBraking() {
VehicleDataEventStatus copy = ( (OnVehicleData) msg).getDriverBraking();
assertEquals("Driver braking does not match input driver braking", VehicleDataHelper.DRIVER_BRAKING, copy);
}
public void testWiperStatus() {
WiperStatus copy = ( (OnVehicleData) msg).getWiperStatus();
assertEquals("Wiper status does not match input wiper status", VehicleDataHelper.WIPER_STATUS, copy);
}
public void testHeadLampStatus() {
HeadLampStatus copy = ( (OnVehicleData) msg).getHeadLampStatus();
assertNotSame("Head lamp status was not defensive copied", VehicleDataHelper.HEAD_LAMP_STATUS, copy);
assertTrue("Head lamp status does not match input head lamp status", Validator.validateHeadLampStatus(VehicleDataHelper.HEAD_LAMP_STATUS, copy));
}
public void testAccPedalPosition() {
Double copy = ( (OnVehicleData) msg).getAccPedalPosition();
assertEquals("Acc pedal position does not match input acc pedal position", VehicleDataHelper.ACC_PEDAL_POSITION, copy);
}
public void testSteeringWheelAngle() {
Double copy = ( (OnVehicleData) msg).getSteeringWheelAngle();
assertEquals("Steering wheel angle does not match input steering wheel angle", VehicleDataHelper.STEERING_WHEEL_ANGLE, copy);
}
public void testECallInfo() {
ECallInfo copy = ( (OnVehicleData) msg).getECallInfo();
assertNotSame("Emergency call info was not defensive copied", VehicleDataHelper.E_CALL_INFO, copy);
assertTrue("Emergency call info does not match input emergency call info", Validator.validateECallInfo(VehicleDataHelper.E_CALL_INFO, copy));
}
public void testAirbagStatus() {
AirbagStatus copy = ( (OnVehicleData) msg).getAirbagStatus();
assertNotSame("Airbag status was not defensive copied", VehicleDataHelper.AIRBAG_STATUS, copy);
assertTrue("Airbag status does not match input airbag status", Validator.validateAirbagStatus(VehicleDataHelper.AIRBAG_STATUS, copy));
}
public void testEmergencyEvent() {
EmergencyEvent copy = ( (OnVehicleData) msg).getEmergencyEvent();
assertNotSame("Emergency event was not defensive copied", VehicleDataHelper.EMERGENCY_EVENT, copy);
assertTrue("Emergency event does not match input emergency event", Validator.validateEmergencyEvent(VehicleDataHelper.EMERGENCY_EVENT, copy));
}
public void testClusterModeStatus() {
ClusterModeStatus copy = ( (OnVehicleData) msg).getClusterModeStatus();
assertNotSame("Cluster mode status was not defensive copied", VehicleDataHelper.CLUSTER_MODE_STATUS, copy);
assertTrue("Cluster mode status does not match cluster mode status", Validator.validateClusterModeStatus(VehicleDataHelper.CLUSTER_MODE_STATUS, copy));
}
public void testMyKey() {
MyKey copy = ( (OnVehicleData) msg).getMyKey();
assertNotSame("My key was not defensive copied", VehicleDataHelper.MY_KEY, copy);
assertTrue("My key does not match my key", Validator.validateMyKey(VehicleDataHelper.MY_KEY, copy));
}
public void testJson() {
JSONObject reference = new JSONObject();
//objects needed on the first level
JSONObject tireStatusObj = new JSONObject();
JSONObject GPSDataObj = new JSONObject();
JSONObject beltStatusObj = new JSONObject();
JSONObject bodyInformationObj = new JSONObject();
JSONObject deviceStatusObj = new JSONObject();
JSONObject headLampStatusObj = new JSONObject();
JSONObject ECallInfoObj = new JSONObject();
JSONObject airbagStatusObj = new JSONObject();
JSONObject emergencyEventObj = new JSONObject();
JSONObject clusterModeStatusObj = new JSONObject();
JSONObject myKeyObj = new JSONObject();
try {
//set up the JSONObject to represent OnVehicleData
//TIRE_PRESSURE
tireStatusObj.put(TireStatus.KEY_PRESSURE_TELL_TALE, VehicleDataHelper.TIRE_PRESSURE_TELL_TALE);
JSONObject tireLeftFront = new JSONObject();
tireLeftFront.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_LEFT_FRONT);
tireStatusObj.put(TireStatus.KEY_LEFT_FRONT, tireLeftFront);
JSONObject tireRightFront = new JSONObject();
tireRightFront.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_RIGHT_FRONT);
tireStatusObj.put(TireStatus.KEY_RIGHT_FRONT, tireRightFront);
JSONObject tireLeftRear = new JSONObject();
tireLeftRear.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_LEFT_REAR);
tireStatusObj.put(TireStatus.KEY_LEFT_REAR, tireLeftRear);
JSONObject tireRightRear = new JSONObject();
tireRightRear.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_RIGHT_REAR);
tireStatusObj.put(TireStatus.KEY_RIGHT_REAR, tireRightRear);
JSONObject tireInnerLeftRear = new JSONObject();
tireInnerLeftRear.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_INNER_LEFT_REAR);
tireStatusObj.put(TireStatus.KEY_INNER_LEFT_REAR, tireInnerLeftRear);
JSONObject tireInnerRightRear = new JSONObject();
tireInnerRightRear.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_INNER_RIGHT_REAR);
tireStatusObj.put(TireStatus.KEY_INNER_RIGHT_REAR, tireInnerRightRear);
//GPS
GPSDataObj.put(GPSData.KEY_LONGITUDE_DEGREES, VehicleDataHelper.GPS_LONGITUDE);
GPSDataObj.put(GPSData.KEY_LATITUDE_DEGREES, VehicleDataHelper.GPS_LATITUDE);
GPSDataObj.put(GPSData.KEY_UTC_YEAR, VehicleDataHelper.GPS_YEAR);
GPSDataObj.put(GPSData.KEY_UTC_MONTH, VehicleDataHelper.GPS_MONTH);
GPSDataObj.put(GPSData.KEY_UTC_DAY, VehicleDataHelper.GPS_DAY);
GPSDataObj.put(GPSData.KEY_UTC_HOURS, VehicleDataHelper.GPS_HOURS);
GPSDataObj.put(GPSData.KEY_UTC_MINUTES, VehicleDataHelper.GPS_MINUTES);
GPSDataObj.put(GPSData.KEY_UTC_SECONDS, VehicleDataHelper.GPS_SECONDS);
GPSDataObj.put(GPSData.KEY_COMPASS_DIRECTION, VehicleDataHelper.GPS_DIRECTION);
GPSDataObj.put(GPSData.KEY_PDOP, VehicleDataHelper.GPS_PDOP);
GPSDataObj.put(GPSData.KEY_VDOP, VehicleDataHelper.GPS_VDOP);
GPSDataObj.put(GPSData.KEY_HDOP, VehicleDataHelper.GPS_HDOP);
GPSDataObj.put(GPSData.KEY_ACTUAL, VehicleDataHelper.GPS_ACTUAL);
GPSDataObj.put(GPSData.KEY_SATELLITES, VehicleDataHelper.GPS_SATELLITES);
GPSDataObj.put(GPSData.KEY_DIMENSION, VehicleDataHelper.GPS_DIMENSION);
GPSDataObj.put(GPSData.KEY_ALTITUDE, VehicleDataHelper.GPS_ALTITUDE);
GPSDataObj.put(GPSData.KEY_HEADING, VehicleDataHelper.GPS_HEADING);
GPSDataObj.put(GPSData.KEY_SPEED, VehicleDataHelper.GPS_SPEED);
//BELT_STATUS
beltStatusObj.put(BeltStatus.KEY_DRIVER_BELT_DEPLOYED, VehicleDataHelper.BELT_STATUS_DRIVER_DEPLOYED);
beltStatusObj.put(BeltStatus.KEY_PASSENGER_BELT_DEPLOYED, VehicleDataHelper.BELT_STATUS_PASSENGER_DEPLOYED);
beltStatusObj.put(BeltStatus.KEY_PASSENGER_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_PASSENGER_BELTED);
beltStatusObj.put(BeltStatus.KEY_DRIVER_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_DRIVER_BELTED);
beltStatusObj.put(BeltStatus.KEY_LEFT_ROW_2_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_LEFT_ROW_2_BELTED);
beltStatusObj.put(BeltStatus.KEY_PASSENGER_CHILD_DETECTED, VehicleDataHelper.BELT_STATUS_PASSENGER_CHILD);
beltStatusObj.put(BeltStatus.KEY_RIGHT_ROW_2_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_RIGHT_ROW_2_BELTED);
beltStatusObj.put(BeltStatus.KEY_MIDDLE_ROW_2_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_MIDDLE_ROW_2_BELTED);
beltStatusObj.put(BeltStatus.KEY_MIDDLE_ROW_3_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_MIDDLE_ROW_3_BELTED);
beltStatusObj.put(BeltStatus.KEY_LEFT_ROW_3_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_LEFT_ROW_3_BELTED);
beltStatusObj.put(BeltStatus.KEY_RIGHT_ROW_3_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_RIGHT_ROW_3_BELTED);
beltStatusObj.put(BeltStatus.KEY_REAR_INFLATABLE_BELTED, VehicleDataHelper.BELT_STATUS_LEFT_REAR_INFLATABLE_BELTED);
beltStatusObj.put(BeltStatus.KEY_RIGHT_REAR_INFLATABLE_BELTED, VehicleDataHelper.BELT_STATUS_RIGHT_REAR_INFLATABLE_BELTED);
beltStatusObj.put(BeltStatus.KEY_MIDDLE_ROW_1_BELT_DEPLOYED, VehicleDataHelper.BELT_STATUS_MIDDLE_ROW_1_DEPLOYED);
beltStatusObj.put(BeltStatus.KEY_MIDDLE_ROW_1_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_MIDDLE_ROW_1_BELTED);
//BODY_INFORMATION
bodyInformationObj.put(BodyInformation.KEY_PARK_BRAKE_ACTIVE, VehicleDataHelper.BODY_INFORMATION_PARK_BRAKE);
bodyInformationObj.put(BodyInformation.KEY_IGNITION_STABLE_STATUS, VehicleDataHelper.BODY_INFORMATION_IGNITION_STATUS);
bodyInformationObj.put(BodyInformation.KEY_IGNITION_STATUS, VehicleDataHelper.BODY_INFORMATION_IGNITION_STABLE_STATUS);
bodyInformationObj.put(BodyInformation.KEY_DRIVER_DOOR_AJAR, VehicleDataHelper.BODY_INFORMATION_DRIVER_AJAR);
bodyInformationObj.put(BodyInformation.KEY_PASSENGER_DOOR_AJAR, VehicleDataHelper.BODY_INFORMATION_PASSENGER_AJAR);
bodyInformationObj.put(BodyInformation.KEY_REAR_LEFT_DOOR_AJAR, VehicleDataHelper.BODY_INFORMATION_REAR_LEFT_AJAR);
bodyInformationObj.put(BodyInformation.KEY_REAR_RIGHT_DOOR_AJAR, VehicleDataHelper.BODY_INFORMATION_REAR_RIGHT_AJAR);
//DEVICE_STATUS
deviceStatusObj.put(DeviceStatus.KEY_VOICE_REC_ON, VehicleDataHelper.DEVICE_STATUS_VOICE_REC);
deviceStatusObj.put(DeviceStatus.KEY_BT_ICON_ON, VehicleDataHelper.DEVICE_STATUS_BT_ICON);
deviceStatusObj.put(DeviceStatus.KEY_CALL_ACTIVE, VehicleDataHelper.DEVICE_STATUS_CALL_ACTIVE);
deviceStatusObj.put(DeviceStatus.KEY_PHONE_ROAMING, VehicleDataHelper.DEVICE_STATUS_PHONE_ROAMING);
deviceStatusObj.put(DeviceStatus.KEY_TEXT_MSG_AVAILABLE, VehicleDataHelper.DEVICE_STATUS_TEXT_MSG_AVAILABLE);
deviceStatusObj.put(DeviceStatus.KEY_BATT_LEVEL_STATUS, VehicleDataHelper.DEVICE_STATUS_BATT_LEVEL_STATUS);
deviceStatusObj.put(DeviceStatus.KEY_STEREO_AUDIO_OUTPUT_MUTED, VehicleDataHelper.DEVICE_STATUS_STEREO_MUTED);
deviceStatusObj.put(DeviceStatus.KEY_MONO_AUDIO_OUTPUT_MUTED, VehicleDataHelper.DEVICE_STATUS_MONO_MUTED);
deviceStatusObj.put(DeviceStatus.KEY_SIGNAL_LEVEL_STATUS, VehicleDataHelper.DEVICE_STATUS_SIGNAL_LEVEL_STATUS);
deviceStatusObj.put(DeviceStatus.KEY_PRIMARY_AUDIO_SOURCE, VehicleDataHelper.DEVICE_STATUS_PRIMARY_AUDIO);
deviceStatusObj.put(DeviceStatus.KEY_E_CALL_EVENT_ACTIVE, VehicleDataHelper.DEVICE_STATUS_E_CALL_ACTIVE);
//HEAD_LAMP_STATUS
headLampStatusObj.put(HeadLampStatus.KEY_AMBIENT_LIGHT_SENSOR_STATUS, VehicleDataHelper.HEAD_LAMP_STATUS_AMBIENT_STATUS);
headLampStatusObj.put(HeadLampStatus.KEY_HIGH_BEAMS_ON, VehicleDataHelper.HEAD_LAMP_HIGH_BEAMS);
headLampStatusObj.put(HeadLampStatus.KEY_LOW_BEAMS_ON, VehicleDataHelper.HEAD_LAMP_LOW_BEAMS);
//E_CALL_INFO
ECallInfoObj.put(ECallInfo.KEY_E_CALL_NOTIFICATION_STATUS, VehicleDataHelper.E_CALL_INFO_E_CALL_NOTIFICATION_STATUS);
ECallInfoObj.put(ECallInfo.KEY_AUX_E_CALL_NOTIFICATION_STATUS, VehicleDataHelper.E_CALL_INFO_AUX_E_CALL_NOTIFICATION_STATUS);
ECallInfoObj.put(ECallInfo.KEY_E_CALL_CONFIRMATION_STATUS, VehicleDataHelper.E_CALL_INFO_CONFIRMATION_STATUS);
//AIRBAG_STATUS
airbagStatusObj.put(AirbagStatus.KEY_DRIVER_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_DRIVER_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_DRIVER_SIDE_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_DRIVER_SIDE_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_DRIVER_CURTAIN_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_DRIVER_CURTAIN_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_DRIVER_KNEE_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_DRIVER_KNEE_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_PASSENGER_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_PASSENGER_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_PASSENGER_SIDE_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_PASSENGER_SIDE_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_PASSENGER_CURTAIN_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_PASSENGER_CURTAIN_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_PASSENGER_KNEE_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_PASSENGER_KNEE_DEPLOYED);
//EMERGENCY_EVENT
emergencyEventObj.put(EmergencyEvent.KEY_EMERGENCY_EVENT_TYPE, VehicleDataHelper.EMERGENCY_EVENT_TYPE);
emergencyEventObj.put(EmergencyEvent.KEY_FUEL_CUTOFF_STATUS, VehicleDataHelper.EMERGENCY_EVENT_FUEL_CUTOFF_STATUS);
emergencyEventObj.put(EmergencyEvent.KEY_ROLLOVER_EVENT, VehicleDataHelper.EMERGENCY_EVENT_ROLLOVER_EVENT);
emergencyEventObj.put(EmergencyEvent.KEY_MAXIMUM_CHANGE_VELOCITY, VehicleDataHelper.EMERGENCY_EVENT_MAX_CHANGE_VELOCITY);
emergencyEventObj.put(EmergencyEvent.KEY_MULTIPLE_EVENTS, VehicleDataHelper.EMERGENCY_EVENT_MULTIPLE_EVENTS);
//CLUSTER_MODE_STATUS
clusterModeStatusObj.put(ClusterModeStatus.KEY_POWER_MODE_ACTIVE, VehicleDataHelper.CLUSTER_MODE_STATUS_POWER_MODE_ACTIVE);
clusterModeStatusObj.put(ClusterModeStatus.KEY_POWER_MODE_QUALIFICATION_STATUS, VehicleDataHelper.CLUSTER_MODE_STATUS_POWER_MODE_QUALIFICATION_STATUS);
clusterModeStatusObj.put(ClusterModeStatus.KEY_CAR_MODE_STATUS, VehicleDataHelper.CLUSTER_MODE_STATUS_CAR_MODE_STATUS);
clusterModeStatusObj.put(ClusterModeStatus.KEY_POWER_MODE_STATUS, VehicleDataHelper.CLUSTER_MODE_STATUS_POWER_MODE_STATUS);
//MY_KEY
myKeyObj.put(MyKey.KEY_E_911_OVERRIDE, VehicleDataHelper.MY_KEY_E_911_OVERRIDE);
reference.put(OnVehicleData.KEY_SPEED, VehicleDataHelper.SPEED);
reference.put(OnVehicleData.KEY_RPM, VehicleDataHelper.RPM);
reference.put(OnVehicleData.KEY_EXTERNAL_TEMPERATURE, VehicleDataHelper.EXTERNAL_TEMPERATURE);
reference.put(OnVehicleData.KEY_FUEL_LEVEL, VehicleDataHelper.FUEL_LEVEL);
reference.put(OnVehicleData.KEY_VIN, VehicleDataHelper.VIN);
reference.put(OnVehicleData.KEY_PRNDL, VehicleDataHelper.PRNDL_FINAL);
reference.put(OnVehicleData.KEY_TIRE_PRESSURE, tireStatusObj);
reference.put(OnVehicleData.KEY_ENGINE_TORQUE, VehicleDataHelper.ENGINE_TORQUE);
reference.put(OnVehicleData.KEY_ODOMETER, VehicleDataHelper.ODOMETER);
reference.put(OnVehicleData.KEY_GPS, GPSDataObj);
reference.put(OnVehicleData.KEY_FUEL_LEVEL_STATE, VehicleDataHelper.FUEL_LEVEL_STATE);
reference.put(OnVehicleData.KEY_INSTANT_FUEL_CONSUMPTION, VehicleDataHelper.INSTANT_FUEL_CONSUMPTION);
reference.put(OnVehicleData.KEY_BELT_STATUS, beltStatusObj);
reference.put(OnVehicleData.KEY_BODY_INFORMATION, bodyInformationObj);
reference.put(OnVehicleData.KEY_DEVICE_STATUS, deviceStatusObj);
reference.put(OnVehicleData.KEY_DRIVER_BRAKING, VehicleDataHelper.DRIVER_BRAKING);
reference.put(OnVehicleData.KEY_WIPER_STATUS, VehicleDataHelper.WIPER_STATUS);
reference.put(OnVehicleData.KEY_HEAD_LAMP_STATUS, headLampStatusObj);
reference.put(OnVehicleData.KEY_ACC_PEDAL_POSITION, VehicleDataHelper.ACC_PEDAL_POSITION);
reference.put(OnVehicleData.KEY_STEERING_WHEEL_ANGLE, VehicleDataHelper.STEERING_WHEEL_ANGLE);
reference.put(OnVehicleData.KEY_E_CALL_INFO, ECallInfoObj);
reference.put(OnVehicleData.KEY_AIRBAG_STATUS, airbagStatusObj);
reference.put(OnVehicleData.KEY_EMERGENCY_EVENT, emergencyEventObj);
reference.put(OnVehicleData.KEY_CLUSTER_MODE_STATUS, clusterModeStatusObj);
reference.put(OnVehicleData.KEY_MY_KEY, myKeyObj);
JSONObject underTest = msg.serializeJSON();
//go inside underTest and only return the JSONObject inside the parameters key inside the notification key
underTest = underTest.getJSONObject("notification").getJSONObject("parameters");
assertEquals("JSON size didn't match expected size.", reference.length(), underTest.length());
Iterator<?> iterator = reference.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if (key.equals(OnVehicleData.KEY_TIRE_PRESSURE)) {
JSONObject tirePressureReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject tirePressureTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateTireStatus(
new TireStatus(JsonRPCMarshaller.deserializeJSONObject(tirePressureReference)),
new TireStatus(JsonRPCMarshaller.deserializeJSONObject(tirePressureTest))));
}
else if (key.equals(OnVehicleData.KEY_GPS)) {
JSONObject GPSObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject GPSObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateGpsData(
new GPSData(JsonRPCMarshaller.deserializeJSONObject(GPSObjReference)),
new GPSData(JsonRPCMarshaller.deserializeJSONObject(GPSObjTest))));
}
else if (key.equals(OnVehicleData.KEY_BELT_STATUS)) {
JSONObject beltObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject beltObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateBeltStatus(
new BeltStatus(JsonRPCMarshaller.deserializeJSONObject(beltObjReference)),
new BeltStatus(JsonRPCMarshaller.deserializeJSONObject(beltObjTest))));
}
else if (key.equals(OnVehicleData.KEY_BODY_INFORMATION)) {
JSONObject bodyInfoObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject bodyInfoObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateBodyInformation(
new BodyInformation(JsonRPCMarshaller.deserializeJSONObject(bodyInfoObjReference)),
new BodyInformation(JsonRPCMarshaller.deserializeJSONObject(bodyInfoObjTest))));
}
else if (key.equals(OnVehicleData.KEY_DEVICE_STATUS)) {
JSONObject deviceObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject deviceObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateDeviceStatus(
new DeviceStatus(JsonRPCMarshaller.deserializeJSONObject(deviceObjReference)),
new DeviceStatus(JsonRPCMarshaller.deserializeJSONObject(deviceObjTest))));
}
else if (key.equals(OnVehicleData.KEY_HEAD_LAMP_STATUS)) {
JSONObject headLampObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject headLampObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateHeadLampStatus(
new HeadLampStatus(JsonRPCMarshaller.deserializeJSONObject(headLampObjReference)),
new HeadLampStatus(JsonRPCMarshaller.deserializeJSONObject(headLampObjTest))));
}
else if (key.equals(OnVehicleData.KEY_E_CALL_INFO)) {
JSONObject callInfoObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject callInfoObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateECallInfo(
new ECallInfo(JsonRPCMarshaller.deserializeJSONObject(callInfoObjReference)),
new ECallInfo(JsonRPCMarshaller.deserializeJSONObject(callInfoObjTest))));
}
else if (key.equals(OnVehicleData.KEY_AIRBAG_STATUS)) {
JSONObject airbagObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject airbagObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateAirbagStatus(
new AirbagStatus(JsonRPCMarshaller.deserializeJSONObject(airbagObjReference)),
new AirbagStatus(JsonRPCMarshaller.deserializeJSONObject(airbagObjTest))));
}
else if (key.equals(OnVehicleData.KEY_EMERGENCY_EVENT)) {
JSONObject emergencyObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject emergencyObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateEmergencyEvent(
new EmergencyEvent(JsonRPCMarshaller.deserializeJSONObject(emergencyObjReference)),
new EmergencyEvent(JsonRPCMarshaller.deserializeJSONObject(emergencyObjTest))));
}
else if (key.equals(OnVehicleData.KEY_CLUSTER_MODE_STATUS)) {
JSONObject clusterModeObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject clusterModeObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateClusterModeStatus(
new ClusterModeStatus(JsonRPCMarshaller.deserializeJSONObject(clusterModeObjReference)),
new ClusterModeStatus(JsonRPCMarshaller.deserializeJSONObject(clusterModeObjTest))));
}
else if (key.equals(OnVehicleData.KEY_MY_KEY)) {
JSONObject myKeyObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject myKeyObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateMyKey(
new MyKey(JsonRPCMarshaller.deserializeJSONObject(myKeyObjReference)),
new MyKey(JsonRPCMarshaller.deserializeJSONObject(myKeyObjTest))));
}
else {
assertEquals("JSON value didn't match expected value for key \"" + key + "\".",
JsonUtils.readObjectFromJsonObject(reference, key),
JsonUtils.readObjectFromJsonObject(underTest, key));
}
}
} catch (JSONException e) {
/* do nothing */
}
}
public void testNull(){
OnVehicleData msg = new OnVehicleData();
assertNotNull("Null object creation failed.", msg);
testNullBase(msg);
assertNull("Speed wasn't set, but getter method returned an object.", msg.getSpeed());
assertNull("RPM wasn't set, but getter method returned an object.", msg.getRpm());
assertNull("External temperature wasn't set, but getter method returned an object.", msg.getExternalTemperature());
assertNull("Fuel level wasn't set, but getter method returned an object.", msg.getFuelLevel());
assertNull("VIN wasn't set, but getter method returned an object.", msg.getVin());
assertNull("PRNDL wasn't set, but getter method returned an object.", msg.getPrndl());
assertNull("Tire pressure wasn't set, but getter method returned an object.", msg.getTirePressure());
assertNull("Engine torque wasn't set, but getter method returned an object.", msg.getEngineTorque());
assertNull("Odometer wasn't set, but getter method returned an object.", msg.getOdometer());
assertNull("GPS wasn't set, but getter method returned an object.", msg.getGps());
assertNull("Fuel level state wasn't set, but getter method returned an object.", msg.getFuelLevel_State());
assertNull("Instant fuel consumption wasn't set, but getter method returned an object.", msg.getInstantFuelConsumption());
assertNull("Belt status wasn't set, but getter method returned an object.", msg.getBeltStatus());
assertNull("Body information wasn't set, but getter method returned an object.", msg.getBodyInformation());
assertNull("Device status wasn't set, but getter method returned an object.", msg.getDeviceStatus());
assertNull("Driver braking wasn't set, but getter method returned an object.", msg.getDriverBraking());
assertNull("Wiper status wasn't set, but getter method returned an object.", msg.getWiperStatus());
assertNull("Head lamp status wasn't set, but getter method returned an object.", msg.getHeadLampStatus());
assertNull("Acceleration pedal position wasn't set, but getter method returned an object.", msg.getAccPedalPosition());
assertNull("Steering wheel angle wasn't set, but getter method returned an object.", msg.getSteeringWheelAngle());
assertNull("Emergency call info wasn't set, but getter method returned an object.", msg.getECallInfo());
assertNull("Airbag status wasn't set, but getter method returned an object.", msg.getAirbagStatus());
assertNull("Emergency event wasn't set, but getter method returned an object.", msg.getEmergencyEvent());
assertNull("Cluster mode status wasn't set, but getter method returned an object.", msg.getClusterModeStatus());
assertNull("My key wasn't set, but getter method returned an object.", msg.getMyKey());
}
}
| sdl_android_tests/src/com/smartdevicelink/test/rpc/notifications/OnVehicleDataTests.java | package com.smartdevicelink.test.rpc.notifications;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import com.smartdevicelink.marshal.JsonRPCMarshaller;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCMessage;
import com.smartdevicelink.proxy.rpc.AirbagStatus;
import com.smartdevicelink.proxy.rpc.BeltStatus;
import com.smartdevicelink.proxy.rpc.BodyInformation;
import com.smartdevicelink.proxy.rpc.ClusterModeStatus;
import com.smartdevicelink.proxy.rpc.DeviceStatus;
import com.smartdevicelink.proxy.rpc.ECallInfo;
import com.smartdevicelink.proxy.rpc.EmergencyEvent;
import com.smartdevicelink.proxy.rpc.GPSData;
import com.smartdevicelink.proxy.rpc.HeadLampStatus;
import com.smartdevicelink.proxy.rpc.MyKey;
import com.smartdevicelink.proxy.rpc.OnVehicleData;
import com.smartdevicelink.proxy.rpc.SingleTireStatus;
import com.smartdevicelink.proxy.rpc.TireStatus;
import com.smartdevicelink.proxy.rpc.enums.ComponentVolumeStatus;
import com.smartdevicelink.proxy.rpc.enums.PRNDL;
import com.smartdevicelink.proxy.rpc.enums.VehicleDataEventStatus;
import com.smartdevicelink.proxy.rpc.enums.WiperStatus;
import com.smartdevicelink.test.BaseRpcTests;
import com.smartdevicelink.test.utils.JsonUtils;
import com.smartdevicelink.test.utils.Validator;
import com.smartdevicelink.test.utils.VehicleDataHelper;
public class OnVehicleDataTests extends BaseRpcTests{
@Override
protected RPCMessage createMessage(){
return VehicleDataHelper.VEHICLE_DATA;
}
@Override
protected String getMessageType(){
return RPCMessage.KEY_NOTIFICATION;
}
@Override
protected String getCommandType(){
return FunctionID.ON_VEHICLE_DATA;
}
@Override
protected JSONObject getExpectedParameters(int sdlVersion){
JSONObject result = new JSONObject();
try{
result.put(OnVehicleData.KEY_SPEED, VehicleDataHelper.SPEED);
result.put(OnVehicleData.KEY_RPM, VehicleDataHelper.RPM);
result.put(OnVehicleData.KEY_EXTERNAL_TEMPERATURE, VehicleDataHelper.EXTERNAL_TEMPERATURE);
result.put(OnVehicleData.KEY_FUEL_LEVEL, VehicleDataHelper.FUEL_LEVEL);
result.put(OnVehicleData.KEY_VIN, VehicleDataHelper.VIN);
result.put(OnVehicleData.KEY_PRNDL, VehicleDataHelper.PRNDL_FINAL);
result.put(OnVehicleData.KEY_TIRE_PRESSURE, VehicleDataHelper.TIRE_PRESSURE.serializeJSON());
result.put(OnVehicleData.KEY_ENGINE_TORQUE, VehicleDataHelper.ENGINE_TORQUE);
result.put(OnVehicleData.KEY_ODOMETER, VehicleDataHelper.ODOMETER);
result.put(OnVehicleData.KEY_GPS, VehicleDataHelper.GPS.serializeJSON());
result.put(OnVehicleData.KEY_FUEL_LEVEL_STATE, VehicleDataHelper.FUEL_LEVEL_STATE);
result.put(OnVehicleData.KEY_INSTANT_FUEL_CONSUMPTION, VehicleDataHelper.INSTANT_FUEL_CONSUMPTION);
result.put(OnVehicleData.KEY_BELT_STATUS, VehicleDataHelper.BELT_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_BODY_INFORMATION, VehicleDataHelper.BODY_INFORMATION.serializeJSON());
result.put(OnVehicleData.KEY_DEVICE_STATUS, VehicleDataHelper.DEVICE_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_DRIVER_BRAKING, VehicleDataHelper.DRIVER_BRAKING);
result.put(OnVehicleData.KEY_WIPER_STATUS, VehicleDataHelper.WIPER_STATUS);
result.put(OnVehicleData.KEY_HEAD_LAMP_STATUS, VehicleDataHelper.HEAD_LAMP_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_ACC_PEDAL_POSITION, VehicleDataHelper.ACC_PEDAL_POSITION);
result.put(OnVehicleData.KEY_STEERING_WHEEL_ANGLE, VehicleDataHelper.STEERING_WHEEL_ANGLE);
result.put(OnVehicleData.KEY_E_CALL_INFO, VehicleDataHelper.E_CALL_INFO.serializeJSON());
result.put(OnVehicleData.KEY_AIRBAG_STATUS, VehicleDataHelper.AIRBAG_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_EMERGENCY_EVENT, VehicleDataHelper.EMERGENCY_EVENT.serializeJSON());
result.put(OnVehicleData.KEY_CLUSTER_MODE_STATUS, VehicleDataHelper.CLUSTER_MODE_STATUS.serializeJSON());
result.put(OnVehicleData.KEY_MY_KEY, VehicleDataHelper.MY_KEY.serializeJSON());
}catch(JSONException e){
//do nothing
}
return result;
}
public void testSpeed() {
Double copy = ( (OnVehicleData) msg).getSpeed();
assertEquals("Speed does not match input speed", VehicleDataHelper.SPEED, copy);
}
public void testRpm() {
int copy = ( (OnVehicleData) msg).getRpm();
assertEquals("RPM does not match input RPM", VehicleDataHelper.RPM, copy);
}
public void testExternalTemperature() {
Double copy = ( (OnVehicleData) msg).getExternalTemperature();
assertEquals("External temperature does not match input external temperature", VehicleDataHelper.EXTERNAL_TEMPERATURE, copy);
}
public void testFuelLevel() {
Double copy = ( (OnVehicleData) msg).getFuelLevel();
assertEquals("Fuel level does not match input fuel level", VehicleDataHelper.FUEL_LEVEL, copy);
}
public void testVin() {
String copy = ( (OnVehicleData) msg).getVin();
assertEquals("VIN does not match input VIN", VehicleDataHelper.VIN, copy);
}
public void testPRNDL() {
PRNDL copy = ( (OnVehicleData) msg).getPrndl();
assertEquals("PRNDL does not match input PRNDL", VehicleDataHelper.PRNDL_FINAL, copy);
}
public void testTirePressure() {
TireStatus copy = ( (OnVehicleData) msg).getTirePressure();
assertNotSame("Tire pressure was not defensive copied", VehicleDataHelper.TIRE_PRESSURE, copy);
assertTrue("Tire pressure does not match input tire pressure", Validator.validateTireStatus(VehicleDataHelper.TIRE_PRESSURE, copy));
}
public void testEngineTorque() {
Double copy = ( (OnVehicleData) msg).getEngineTorque();
assertEquals("Engine torque does not match input engine torque", VehicleDataHelper.ENGINE_TORQUE, copy);
}
public void testOdometer() {
int copy = ( (OnVehicleData) msg).getOdometer();
assertEquals("Odometer does not match input odometer", VehicleDataHelper.ODOMETER, copy);
}
public void testGps() {
GPSData copy = ( (OnVehicleData) msg).getGps();
assertNotSame("GPS was not defensive copied", VehicleDataHelper.TIRE_PRESSURE, copy);
assertTrue("GPS does not match input GPS", Validator.validateGpsData(VehicleDataHelper.GPS, copy));
}
public void testFuelLevel_State() {
ComponentVolumeStatus copy = ( (OnVehicleData) msg).getFuelLevel_State();
assertEquals("Fuel level does not match input fuel level", VehicleDataHelper.FUEL_LEVEL_STATE, copy);
}
public void testInstantFuelConsumption() {
Double copy = ( (OnVehicleData) msg).getInstantFuelConsumption();
assertEquals("Instant fuel consumption does not match input instant fuel consumption", VehicleDataHelper.INSTANT_FUEL_CONSUMPTION, copy);
}
public void testBeltStatus() {
BeltStatus copy = ( (OnVehicleData) msg).getBeltStatus();
assertNotSame("Belt status was not defensive copied", VehicleDataHelper.BELT_STATUS, copy);
assertTrue("Belt status does not match input belt status", Validator.validateBeltStatus(VehicleDataHelper.BELT_STATUS, copy));
}
public void testBodyInformation() {
BodyInformation copy = ( (OnVehicleData) msg).getBodyInformation();
assertNotSame("Body information was not defensive copied", VehicleDataHelper.BODY_INFORMATION, copy);
assertTrue("Body information does not match input body information", Validator.validateBodyInformation(VehicleDataHelper.BODY_INFORMATION, copy));
}
public void testDeviceStatus() {
DeviceStatus copy = ( (OnVehicleData) msg).getDeviceStatus();
assertNotSame("Device status was not defensive copied", VehicleDataHelper.DEVICE_STATUS, copy);
assertTrue("Device status does not match input device status", Validator.validateDeviceStatus(VehicleDataHelper.DEVICE_STATUS, copy));
}
public void testDriverBraking() {
VehicleDataEventStatus copy = ( (OnVehicleData) msg).getDriverBraking();
assertEquals("Driver braking does not match input driver braking", VehicleDataHelper.DRIVER_BRAKING, copy);
}
public void testWiperStatus() {
WiperStatus copy = ( (OnVehicleData) msg).getWiperStatus();
assertEquals("Wiper status does not match input wiper status", VehicleDataHelper.WIPER_STATUS, copy);
}
public void testHeadLampStatus() {
HeadLampStatus copy = ( (OnVehicleData) msg).getHeadLampStatus();
assertNotSame("Head lamp status was not defensive copied", VehicleDataHelper.HEAD_LAMP_STATUS, copy);
assertTrue("Head lamp status does not match input head lamp status", Validator.validateHeadLampStatus(VehicleDataHelper.HEAD_LAMP_STATUS, copy));
}
public void testAccPedalPosition() {
Double copy = ( (OnVehicleData) msg).getAccPedalPosition();
assertEquals("Acc pedal position does not match input acc pedal position", VehicleDataHelper.ACC_PEDAL_POSITION, copy);
}
public void testSteeringWheelAngle() {
Double copy = ( (OnVehicleData) msg).getSteeringWheelAngle();
assertEquals("Steering wheel angle does not match input steering wheel angle", VehicleDataHelper.STEERING_WHEEL_ANGLE, copy);
}
public void testECallInfo() {
ECallInfo copy = ( (OnVehicleData) msg).getECallInfo();
assertNotSame("Emergency call info was not defensive copied", VehicleDataHelper.E_CALL_INFO, copy);
assertTrue("Emergency call info does not match input emergency call info", Validator.validateECallInfo(VehicleDataHelper.E_CALL_INFO, copy));
}
public void testAirbagStatus() {
AirbagStatus copy = ( (OnVehicleData) msg).getAirbagStatus();
assertNotSame("Airbag status was not defensive copied", VehicleDataHelper.AIRBAG_STATUS, copy);
assertTrue("Airbag status does not match input airbag status", Validator.validateAirbagStatus(VehicleDataHelper.AIRBAG_STATUS, copy));
}
public void testEmergencyEvent() {
EmergencyEvent copy = ( (OnVehicleData) msg).getEmergencyEvent();
assertNotSame("Emergency event was not defensive copied", VehicleDataHelper.EMERGENCY_EVENT, copy);
assertTrue("Emergency event does not match input emergency event", Validator.validateEmergencyEvent(VehicleDataHelper.EMERGENCY_EVENT, copy));
}
public void testClusterModeStatus() {
ClusterModeStatus copy = ( (OnVehicleData) msg).getClusterModeStatus();
assertNotSame("Cluster mode status was not defensive copied", VehicleDataHelper.CLUSTER_MODE_STATUS, copy);
assertTrue("Cluster mode status does not match cluster mode status", Validator.validateClusterModeStatus(VehicleDataHelper.CLUSTER_MODE_STATUS, copy));
}
public void testMyKey() {
MyKey copy = ( (OnVehicleData) msg).getMyKey();
assertNotSame("My key was not defensive copied", VehicleDataHelper.MY_KEY, copy);
assertTrue("My key does not match my key", Validator.validateMyKey(VehicleDataHelper.MY_KEY, copy));
}
public void testJson() {
JSONObject reference = new JSONObject();
//objects needed on the first level
JSONObject tireStatusObj = new JSONObject();
JSONObject GPSDataObj = new JSONObject();
JSONObject beltStatusObj = new JSONObject();
JSONObject bodyInformationObj = new JSONObject();
JSONObject deviceStatusObj = new JSONObject();
JSONObject headLampStatusObj = new JSONObject();
JSONObject ECallInfoObj = new JSONObject();
JSONObject airbagStatusObj = new JSONObject();
JSONObject emergencyEventObj = new JSONObject();
JSONObject clusterModeStatusObj = new JSONObject();
JSONObject myKeyObj = new JSONObject();
try {
//set up the JSONObject to represent OnVehicleData
//TIRE_PRESSURE
tireStatusObj.put(TireStatus.KEY_PRESSURE_TELL_TALE, VehicleDataHelper.TIRE_PRESSURE_TELL_TALE);
JSONObject tireLeftFront = new JSONObject();
tireLeftFront.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_LEFT_FRONT);
tireStatusObj.put(TireStatus.KEY_LEFT_FRONT, tireLeftFront);
JSONObject tireRightFront = new JSONObject();
tireRightFront.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_RIGHT_FRONT);
tireStatusObj.put(TireStatus.KEY_RIGHT_FRONT, tireRightFront);
JSONObject tireLeftRear = new JSONObject();
tireLeftRear.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_LEFT_REAR);
tireStatusObj.put(TireStatus.KEY_LEFT_REAR, tireLeftRear);
JSONObject tireRightRear = new JSONObject();
tireRightRear.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_RIGHT_REAR);
tireStatusObj.put(TireStatus.KEY_RIGHT_REAR, tireRightRear);
JSONObject tireInnerLeftRear = new JSONObject();
tireInnerLeftRear.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_INNER_LEFT_REAR);
tireStatusObj.put(TireStatus.KEY_INNER_LEFT_REAR, tireInnerLeftRear);
JSONObject tireInnerRightRear = new JSONObject();
tireInnerRightRear.put(SingleTireStatus.KEY_STATUS, VehicleDataHelper.TIRE_PRESSURE_INNER_RIGHT_REAR);
tireStatusObj.put(TireStatus.KEY_INNER_RIGHT_REAR, tireInnerRightRear);
//GPS
GPSDataObj.put(GPSData.KEY_LONGITUDE_DEGREES, VehicleDataHelper.GPS_LONGITUDE);
GPSDataObj.put(GPSData.KEY_LATITUDE_DEGREES, VehicleDataHelper.GPS_LATITUDE);
GPSDataObj.put(GPSData.KEY_UTC_YEAR, VehicleDataHelper.GPS_YEAR);
GPSDataObj.put(GPSData.KEY_UTC_MONTH, VehicleDataHelper.GPS_MONTH);
GPSDataObj.put(GPSData.KEY_UTC_DAY, VehicleDataHelper.GPS_DAY);
GPSDataObj.put(GPSData.KEY_UTC_HOURS, VehicleDataHelper.GPS_HOURS);
GPSDataObj.put(GPSData.KEY_UTC_MINUTES, VehicleDataHelper.GPS_MINUTES);
GPSDataObj.put(GPSData.KEY_UTC_SECONDS, VehicleDataHelper.GPS_SECONDS);
GPSDataObj.put(GPSData.KEY_COMPASS_DIRECTION, VehicleDataHelper.GPS_DIRECTION);
GPSDataObj.put(GPSData.KEY_PDOP, VehicleDataHelper.GPS_PDOP);
GPSDataObj.put(GPSData.KEY_VDOP, VehicleDataHelper.GPS_VDOP);
GPSDataObj.put(GPSData.KEY_HDOP, VehicleDataHelper.GPS_HDOP);
GPSDataObj.put(GPSData.KEY_ACTUAL, VehicleDataHelper.GPS_ACTUAL);
GPSDataObj.put(GPSData.KEY_SATELLITES, VehicleDataHelper.GPS_SATELLITES);
GPSDataObj.put(GPSData.KEY_DIMENSION, VehicleDataHelper.GPS_DIMENSION);
GPSDataObj.put(GPSData.KEY_ALTITUDE, VehicleDataHelper.GPS_ALTITUDE);
GPSDataObj.put(GPSData.KEY_HEADING, VehicleDataHelper.GPS_HEADING);
GPSDataObj.put(GPSData.KEY_SPEED, VehicleDataHelper.GPS_SPEED);
//BELT_STATUS
beltStatusObj.put(BeltStatus.KEY_DRIVER_BELT_DEPLOYED, VehicleDataHelper.BELT_STATUS_DRIVER_DEPLOYED);
beltStatusObj.put(BeltStatus.KEY_PASSENGER_BELT_DEPLOYED, VehicleDataHelper.BELT_STATUS_PASSENGER_DEPLOYED);
beltStatusObj.put(BeltStatus.KEY_PASSENGER_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_PASSENGER_BELTED);
beltStatusObj.put(BeltStatus.KEY_DRIVER_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_DRIVER_BELTED);
beltStatusObj.put(BeltStatus.KEY_LEFT_ROW_2_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_LEFT_ROW_2_BELTED);
beltStatusObj.put(BeltStatus.KEY_PASSENGER_CHILD_DETECTED, VehicleDataHelper.BELT_STATUS_PASSENGER_CHILD);
beltStatusObj.put(BeltStatus.KEY_RIGHT_ROW_2_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_RIGHT_ROW_2_BELTED);
beltStatusObj.put(BeltStatus.KEY_MIDDLE_ROW_2_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_MIDDLE_ROW_2_BELTED);
beltStatusObj.put(BeltStatus.KEY_MIDDLE_ROW_3_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_MIDDLE_ROW_3_BELTED);
beltStatusObj.put(BeltStatus.KEY_LEFT_ROW_3_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_LEFT_ROW_3_BELTED);
beltStatusObj.put(BeltStatus.KEY_RIGHT_ROW_3_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_RIGHT_ROW_3_BELTED);
beltStatusObj.put(BeltStatus.KEY_REAR_INFLATABLE_BELTED, VehicleDataHelper.BELT_STATUS_LEFT_REAR_INFLATABLE_BELTED);
beltStatusObj.put(BeltStatus.KEY_RIGHT_REAR_INFLATABLE_BELTED, VehicleDataHelper.BELT_STATUS_RIGHT_REAR_INFLATABLE_BELTED);
beltStatusObj.put(BeltStatus.KEY_MIDDLE_ROW_1_BELT_DEPLOYED, VehicleDataHelper.BELT_STATUS_MIDDLE_ROW_1_DEPLOYED);
beltStatusObj.put(BeltStatus.KEY_MIDDLE_ROW_1_BUCKLE_BELTED, VehicleDataHelper.BELT_STATUS_MIDDLE_ROW_1_BELTED);
//BODY_INFORMATION
bodyInformationObj.put(BodyInformation.KEY_PARK_BRAKE_ACTIVE, VehicleDataHelper.BODY_INFORMATION_PARK_BRAKE);
bodyInformationObj.put(BodyInformation.KEY_IGNITION_STABLE_STATUS, VehicleDataHelper.BODY_INFORMATION_IGNITION_STATUS);
bodyInformationObj.put(BodyInformation.KEY_IGNITION_STATUS, VehicleDataHelper.BODY_INFORMATION_IGNITION_STABLE_STATUS);
bodyInformationObj.put(BodyInformation.KEY_DRIVER_DOOR_AJAR, VehicleDataHelper.BODY_INFORMATION_DRIVER_AJAR);
bodyInformationObj.put(BodyInformation.KEY_PASSENGER_DOOR_AJAR, VehicleDataHelper.BODY_INFORMATION_PASSENGER_AJAR);
bodyInformationObj.put(BodyInformation.KEY_REAR_LEFT_DOOR_AJAR, VehicleDataHelper.BODY_INFORMATION_REAR_LEFT_AJAR);
bodyInformationObj.put(BodyInformation.KEY_REAR_RIGHT_DOOR_AJAR, VehicleDataHelper.BODY_INFORMATION_REAR_RIGHT_AJAR);
//DEVICE_STATUS
deviceStatusObj.put(DeviceStatus.KEY_VOICE_REC_ON, VehicleDataHelper.DEVICE_STATUS_VOICE_REC);
deviceStatusObj.put(DeviceStatus.KEY_BT_ICON_ON, VehicleDataHelper.DEVICE_STATUS_BT_ICON);
deviceStatusObj.put(DeviceStatus.KEY_CALL_ACTIVE, VehicleDataHelper.DEVICE_STATUS_CALL_ACTIVE);
deviceStatusObj.put(DeviceStatus.KEY_PHONE_ROAMING, VehicleDataHelper.DEVICE_STATUS_PHONE_ROAMING);
deviceStatusObj.put(DeviceStatus.KEY_TEXT_MSG_AVAILABLE, VehicleDataHelper.DEVICE_STATUS_TEXT_MSG_AVAILABLE);
deviceStatusObj.put(DeviceStatus.KEY_BATT_LEVEL_STATUS, VehicleDataHelper.DEVICE_STATUS_BATT_LEVEL_STATUS);
deviceStatusObj.put(DeviceStatus.KEY_STEREO_AUDIO_OUTPUT_MUTED, VehicleDataHelper.DEVICE_STATUS_STEREO_MUTED);
deviceStatusObj.put(DeviceStatus.KEY_MONO_AUDIO_OUTPUT_MUTED, VehicleDataHelper.DEVICE_STATUS_MONO_MUTED);
deviceStatusObj.put(DeviceStatus.KEY_SIGNAL_LEVEL_STATUS, VehicleDataHelper.DEVICE_STATUS_SIGNAL_LEVEL_STATUS);
deviceStatusObj.put(DeviceStatus.KEY_PRIMARY_AUDIO_SOURCE, VehicleDataHelper.DEVICE_STATUS_PRIMARY_AUDIO);
deviceStatusObj.put(DeviceStatus.KEY_E_CALL_EVENT_ACTIVE, VehicleDataHelper.DEVICE_STATUS_E_CALL_ACTIVE);
//HEAD_LAMP_STATUS
headLampStatusObj.put(HeadLampStatus.KEY_AMBIENT_LIGHT_SENSOR_STATUS, VehicleDataHelper.HEAD_LAMP_STATUS_AMBIENT_STATUS);
headLampStatusObj.put(HeadLampStatus.KEY_HIGH_BEAMS_ON, VehicleDataHelper.HEAD_LAMP_HIGH_BEAMS);
headLampStatusObj.put(HeadLampStatus.KEY_LOW_BEAMS_ON, VehicleDataHelper.HEAD_LAMP_LOW_BEAMS);
//E_CALL_INFO
ECallInfoObj.put(ECallInfo.KEY_E_CALL_NOTIFICATION_STATUS, VehicleDataHelper.E_CALL_INFO_E_CALL_NOTIFICATION_STATUS);
ECallInfoObj.put(ECallInfo.KEY_AUX_E_CALL_NOTIFICATION_STATUS, VehicleDataHelper.E_CALL_INFO_AUX_E_CALL_NOTIFICATION_STATUS);
ECallInfoObj.put(ECallInfo.KEY_E_CALL_CONFIRMATION_STATUS, VehicleDataHelper.E_CALL_INFO_CONFIRMATION_STATUS);
//AIRBAG_STATUS
airbagStatusObj.put(AirbagStatus.KEY_DRIVER_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_DRIVER_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_DRIVER_SIDE_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_DRIVER_SIDE_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_DRIVER_CURTAIN_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_DRIVER_CURTAIN_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_DRIVER_KNEE_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_DRIVER_KNEE_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_PASSENGER_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_PASSENGER_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_PASSENGER_SIDE_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_PASSENGER_SIDE_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_PASSENGER_CURTAIN_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_PASSENGER_CURTAIN_DEPLOYED);
airbagStatusObj.put(AirbagStatus.KEY_PASSENGER_KNEE_AIRBAG_DEPLOYED, VehicleDataHelper.AIRBAG_STATUS_PASSENGER_KNEE_DEPLOYED);
//EMERGENCY_EVENT
emergencyEventObj.put(EmergencyEvent.KEY_EMERGENCY_EVENT_TYPE, VehicleDataHelper.EMERGENCY_EVENT_TYPE);
emergencyEventObj.put(EmergencyEvent.KEY_FUEL_CUTOFF_STATUS, VehicleDataHelper.EMERGENCY_EVENT_FUEL_CUTOFF_STATUS);
emergencyEventObj.put(EmergencyEvent.KEY_ROLLOVER_EVENT, VehicleDataHelper.EMERGENCY_EVENT_ROLLOVER_EVENT);
emergencyEventObj.put(EmergencyEvent.KEY_MAXIMUM_CHANGE_VELOCITY, VehicleDataHelper.EMERGENCY_EVENT_MAX_CHANGE_VELOCITY);
emergencyEventObj.put(EmergencyEvent.KEY_MULTIPLE_EVENTS, VehicleDataHelper.EMERGENCY_EVENT_MULTIPLE_EVENTS);
//CLUSTER_MODE_STATUS
clusterModeStatusObj.put(ClusterModeStatus.KEY_POWER_MODE_ACTIVE, VehicleDataHelper.CLUSTER_MODE_STATUS_POWER_MODE_ACTIVE);
clusterModeStatusObj.put(ClusterModeStatus.KEY_POWER_MODE_QUALIFICATION_STATUS, VehicleDataHelper.CLUSTER_MODE_STATUS_POWER_MODE_QUALIFICATION_STATUS);
clusterModeStatusObj.put(ClusterModeStatus.KEY_CAR_MODE_STATUS, VehicleDataHelper.CLUSTER_MODE_STATUS_CAR_MODE_STATUS);
clusterModeStatusObj.put(ClusterModeStatus.KEY_POWER_MODE_STATUS, VehicleDataHelper.CLUSTER_MODE_STATUS_POWER_MODE_STATUS);
//MY_KEY
myKeyObj.put(MyKey.KEY_E_911_OVERRIDE, VehicleDataHelper.MY_KEY_E_911_OVERRIDE);
reference.put(OnVehicleData.KEY_SPEED, VehicleDataHelper.SPEED);
reference.put(OnVehicleData.KEY_RPM, VehicleDataHelper.RPM);
reference.put(OnVehicleData.KEY_EXTERNAL_TEMPERATURE, VehicleDataHelper.EXTERNAL_TEMPERATURE);
reference.put(OnVehicleData.KEY_FUEL_LEVEL, VehicleDataHelper.FUEL_LEVEL);
reference.put(OnVehicleData.KEY_VIN, VehicleDataHelper.VIN);
reference.put(OnVehicleData.KEY_PRNDL, VehicleDataHelper.PRNDL_FINAL);
reference.put(OnVehicleData.KEY_TIRE_PRESSURE, tireStatusObj);
reference.put(OnVehicleData.KEY_ENGINE_TORQUE, VehicleDataHelper.ENGINE_TORQUE);
reference.put(OnVehicleData.KEY_ODOMETER, VehicleDataHelper.ODOMETER);
reference.put(OnVehicleData.KEY_GPS, GPSDataObj);
reference.put(OnVehicleData.KEY_FUEL_LEVEL_STATE, VehicleDataHelper.FUEL_LEVEL_STATE);
reference.put(OnVehicleData.KEY_INSTANT_FUEL_CONSUMPTION, VehicleDataHelper.INSTANT_FUEL_CONSUMPTION);
reference.put(OnVehicleData.KEY_BELT_STATUS, beltStatusObj);
reference.put(OnVehicleData.KEY_BODY_INFORMATION, bodyInformationObj);
reference.put(OnVehicleData.KEY_DEVICE_STATUS, deviceStatusObj);
reference.put(OnVehicleData.KEY_DRIVER_BRAKING, VehicleDataHelper.DRIVER_BRAKING);
reference.put(OnVehicleData.KEY_WIPER_STATUS, VehicleDataHelper.WIPER_STATUS);
reference.put(OnVehicleData.KEY_HEAD_LAMP_STATUS, headLampStatusObj);
reference.put(OnVehicleData.KEY_ACC_PEDAL_POSITION, VehicleDataHelper.ACC_PEDAL_POSITION);
reference.put(OnVehicleData.KEY_STEERING_WHEEL_ANGLE, VehicleDataHelper.STEERING_WHEEL_ANGLE);
reference.put(OnVehicleData.KEY_E_CALL_INFO, ECallInfoObj);
reference.put(OnVehicleData.KEY_AIRBAG_STATUS, airbagStatusObj);
reference.put(OnVehicleData.KEY_EMERGENCY_EVENT, emergencyEventObj);
reference.put(OnVehicleData.KEY_CLUSTER_MODE_STATUS, clusterModeStatusObj);
reference.put(OnVehicleData.KEY_MY_KEY, myKeyObj);
System.out.println(reference);
JSONObject underTest = msg.serializeJSON();
//go inside underTest and only return the JSONObject inside the parameters key inside the notification key
underTest = underTest.getJSONObject("notification").getJSONObject("parameters");
assertEquals("JSON size didn't match expected size.", reference.length(), underTest.length());
Iterator<?> iterator = reference.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if (key.equals(OnVehicleData.KEY_TIRE_PRESSURE)) {
JSONObject tirePressureReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject tirePressureTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateTireStatus(
new TireStatus(JsonRPCMarshaller.deserializeJSONObject(tirePressureReference)),
new TireStatus(JsonRPCMarshaller.deserializeJSONObject(tirePressureTest))));
}
else if (key.equals(OnVehicleData.KEY_GPS)) {
JSONObject GPSObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject GPSObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateGpsData(
new GPSData(JsonRPCMarshaller.deserializeJSONObject(GPSObjReference)),
new GPSData(JsonRPCMarshaller.deserializeJSONObject(GPSObjTest))));
}
else if (key.equals(OnVehicleData.KEY_BELT_STATUS)) {
JSONObject beltObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject beltObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateBeltStatus(
new BeltStatus(JsonRPCMarshaller.deserializeJSONObject(beltObjReference)),
new BeltStatus(JsonRPCMarshaller.deserializeJSONObject(beltObjTest))));
}
else if (key.equals(OnVehicleData.KEY_BODY_INFORMATION)) {
JSONObject bodyInfoObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject bodyInfoObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateBodyInformation(
new BodyInformation(JsonRPCMarshaller.deserializeJSONObject(bodyInfoObjReference)),
new BodyInformation(JsonRPCMarshaller.deserializeJSONObject(bodyInfoObjTest))));
}
else if (key.equals(OnVehicleData.KEY_DEVICE_STATUS)) {
JSONObject deviceObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject deviceObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateDeviceStatus(
new DeviceStatus(JsonRPCMarshaller.deserializeJSONObject(deviceObjReference)),
new DeviceStatus(JsonRPCMarshaller.deserializeJSONObject(deviceObjTest))));
}
else if (key.equals(OnVehicleData.KEY_HEAD_LAMP_STATUS)) {
JSONObject headLampObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject headLampObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateHeadLampStatus(
new HeadLampStatus(JsonRPCMarshaller.deserializeJSONObject(headLampObjReference)),
new HeadLampStatus(JsonRPCMarshaller.deserializeJSONObject(headLampObjTest))));
}
else if (key.equals(OnVehicleData.KEY_E_CALL_INFO)) {
JSONObject callInfoObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject callInfoObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateECallInfo(
new ECallInfo(JsonRPCMarshaller.deserializeJSONObject(callInfoObjReference)),
new ECallInfo(JsonRPCMarshaller.deserializeJSONObject(callInfoObjTest))));
}
else if (key.equals(OnVehicleData.KEY_AIRBAG_STATUS)) {
JSONObject airbagObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject airbagObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateAirbagStatus(
new AirbagStatus(JsonRPCMarshaller.deserializeJSONObject(airbagObjReference)),
new AirbagStatus(JsonRPCMarshaller.deserializeJSONObject(airbagObjTest))));
}
else if (key.equals(OnVehicleData.KEY_EMERGENCY_EVENT)) {
JSONObject emergencyObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject emergencyObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateEmergencyEvent(
new EmergencyEvent(JsonRPCMarshaller.deserializeJSONObject(emergencyObjReference)),
new EmergencyEvent(JsonRPCMarshaller.deserializeJSONObject(emergencyObjTest))));
}
else if (key.equals(OnVehicleData.KEY_CLUSTER_MODE_STATUS)) {
JSONObject clusterModeObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject clusterModeObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateClusterModeStatus(
new ClusterModeStatus(JsonRPCMarshaller.deserializeJSONObject(clusterModeObjReference)),
new ClusterModeStatus(JsonRPCMarshaller.deserializeJSONObject(clusterModeObjTest))));
}
else if (key.equals(OnVehicleData.KEY_MY_KEY)) {
JSONObject myKeyObjReference = JsonUtils.readJsonObjectFromJsonObject(reference, key);
JSONObject myKeyObjTest = JsonUtils.readJsonObjectFromJsonObject(underTest, key);
assertTrue("JSON value didn't match expected value for key \"" + key + "\".",
Validator.validateMyKey(
new MyKey(JsonRPCMarshaller.deserializeJSONObject(myKeyObjReference)),
new MyKey(JsonRPCMarshaller.deserializeJSONObject(myKeyObjTest))));
}
else {
assertEquals("JSON value didn't match expected value for key \"" + key + "\".",
JsonUtils.readObjectFromJsonObject(reference, key),
JsonUtils.readObjectFromJsonObject(underTest, key));
}
}
} catch (JSONException e) {
/* do nothing */
}
}
public void testNull(){
OnVehicleData msg = new OnVehicleData();
assertNotNull("Null object creation failed.", msg);
testNullBase(msg);
assertNull("Speed wasn't set, but getter method returned an object.", msg.getSpeed());
assertNull("RPM wasn't set, but getter method returned an object.", msg.getRpm());
assertNull("External temperature wasn't set, but getter method returned an object.", msg.getExternalTemperature());
assertNull("Fuel level wasn't set, but getter method returned an object.", msg.getFuelLevel());
assertNull("VIN wasn't set, but getter method returned an object.", msg.getVin());
assertNull("PRNDL wasn't set, but getter method returned an object.", msg.getPrndl());
assertNull("Tire pressure wasn't set, but getter method returned an object.", msg.getTirePressure());
assertNull("Engine torque wasn't set, but getter method returned an object.", msg.getEngineTorque());
assertNull("Odometer wasn't set, but getter method returned an object.", msg.getOdometer());
assertNull("GPS wasn't set, but getter method returned an object.", msg.getGps());
assertNull("Fuel level state wasn't set, but getter method returned an object.", msg.getFuelLevel_State());
assertNull("Instant fuel consumption wasn't set, but getter method returned an object.", msg.getInstantFuelConsumption());
assertNull("Belt status wasn't set, but getter method returned an object.", msg.getBeltStatus());
assertNull("Body information wasn't set, but getter method returned an object.", msg.getBodyInformation());
assertNull("Device status wasn't set, but getter method returned an object.", msg.getDeviceStatus());
assertNull("Driver braking wasn't set, but getter method returned an object.", msg.getDriverBraking());
assertNull("Wiper status wasn't set, but getter method returned an object.", msg.getWiperStatus());
assertNull("Head lamp status wasn't set, but getter method returned an object.", msg.getHeadLampStatus());
assertNull("Acceleration pedal position wasn't set, but getter method returned an object.", msg.getAccPedalPosition());
assertNull("Steering wheel angle wasn't set, but getter method returned an object.", msg.getSteeringWheelAngle());
assertNull("Emergency call info wasn't set, but getter method returned an object.", msg.getECallInfo());
assertNull("Airbag status wasn't set, but getter method returned an object.", msg.getAirbagStatus());
assertNull("Emergency event wasn't set, but getter method returned an object.", msg.getEmergencyEvent());
assertNull("Cluster mode status wasn't set, but getter method returned an object.", msg.getClusterModeStatus());
assertNull("My key wasn't set, but getter method returned an object.", msg.getMyKey());
}
}
| removed system print statement
| sdl_android_tests/src/com/smartdevicelink/test/rpc/notifications/OnVehicleDataTests.java | removed system print statement | <ide><path>dl_android_tests/src/com/smartdevicelink/test/rpc/notifications/OnVehicleDataTests.java
<ide> reference.put(OnVehicleData.KEY_CLUSTER_MODE_STATUS, clusterModeStatusObj);
<ide> reference.put(OnVehicleData.KEY_MY_KEY, myKeyObj);
<ide>
<del> System.out.println(reference);
<del>
<ide> JSONObject underTest = msg.serializeJSON();
<ide> //go inside underTest and only return the JSONObject inside the parameters key inside the notification key
<ide> underTest = underTest.getJSONObject("notification").getJSONObject("parameters"); |
|
JavaScript | mit | 5bab3c21c9f69254093ea8d9d29edb3f4a18776c | 0 | rwjblue/ember-cli-inject-live-reload | 'use strict';
const buildLiveReloadPath = require('clean-base-url');
const VersionChecker = require('ember-cli-version-checker');
module.exports = {
name: 'live-reload-middleware',
contentFor: function(type) {
let liveReloadPort = process.env.EMBER_CLI_INJECT_LIVE_RELOAD_PORT;
let baseURL = process.env.EMBER_CLI_INJECT_LIVE_RELOAD_BASEURL;
if (liveReloadPort && type === 'head') {
return '<script src="' + baseURL + 'ember-cli-live-reload.js" type="text/javascript"></script>';
}
},
dynamicScript: function(options) {
let liveReloadOptions = options.liveReloadOptions;
if (liveReloadOptions && liveReloadOptions.snipver === undefined) {
liveReloadOptions.snipver = 1;
}
let liveReloadPath = buildLiveReloadPath(options.liveReloadPrefix) || '/';
let liveReloadPort;
let path = '';
if (options.liveReloadPort !== options.port) {
liveReloadPort = options.liveReloadPort
}
if (options.isLatestEmber && options.liveReloadPrefix) {
path = `&path=${options.liveReloadPrefix}/livereload`;
}
return `(function() {${liveReloadOptions ? "\n window.LiveReloadOptions = " + JSON.stringify(liveReloadOptions) + ";" : ''}
var srcUrl = ${options.liveReloadJsUrl ? "'" + options.liveReloadJsUrl + "'" : null};
var host= location.hostname || 'localhost';
var liveReloadPort = ${liveReloadPort};
var defaultPort = location.protocol === 'https:' ? 443 : 80;
var port = liveReloadPort || location.port || defaultPort;
var path = '${path}';
var prefixURL = ${liveReloadPort ? "(location.protocol || 'http:') + '//' + host + ':' + " + liveReloadPort : "''"};
var src = srcUrl || prefixURL + '${liveReloadPath + 'livereload.js?port='}' + port + '&host=' + host + path;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}());`;
},
serverMiddleware: function(config) {
let options = config.options;
let app = config.app;
let self = this;
// maintaining `baseURL` for backwards compatibility. See: http://emberjs.com/blog/2016/04/28/baseURL.html
let baseURL = options.liveReloadBaseUrl || options.rootURL || options.baseURL;
if (this.parent) {
let checker = new VersionChecker(this.parent);
let depedency = checker.for('ember-cli');
options.isLatestEmber = depedency.gt('3.5.0-beta.2');
}
if (options.liveReload !== true) { return; }
process.env.EMBER_CLI_INJECT_LIVE_RELOAD_PORT = options.liveReloadPort;
process.env.EMBER_CLI_INJECT_LIVE_RELOAD_BASEURL = baseURL;
let baseURLWithoutHost = baseURL.replace(/^https?:\/\/[^/]+/, '');
app.use(baseURLWithoutHost + 'ember-cli-live-reload.js', function(request, response) {
response.contentType('text/javascript');
response.send(self.dynamicScript(options));
});
}
};
| index.js | 'use strict';
const buildLiveReloadPath = require('clean-base-url');
const VersionChecker = require('ember-cli-version-checker');
module.exports = {
name: 'live-reload-middleware',
contentFor: function(type) {
let liveReloadPort = process.env.EMBER_CLI_INJECT_LIVE_RELOAD_PORT;
let baseURL = process.env.EMBER_CLI_INJECT_LIVE_RELOAD_BASEURL;
if (liveReloadPort && type === 'head') {
return '<script src="' + baseURL + 'ember-cli-live-reload.js" type="text/javascript"></script>';
}
},
dynamicScript: function(options) {
let liveReloadOptions = options.liveReloadOptions;
if (liveReloadOptions && liveReloadOptions.snipver === undefined) {
liveReloadOptions.snipver = 1;
}
let liveReloadPath = buildLiveReloadPath(options.liveReloadPrefix) || '/';
let liveReloadPort;
let path = '';
if (options.liveReloadPort !== options.port) {
liveReloadPort = options.liveReloadPort
}
if (options.isLatestEmber && options.liveReloadPrefix) {
path = `&path=${options.liveReloadPrefix}/livereload`;
}
return `(function() {${liveReloadOptions ? "\n window.LiveReloadOptions = " + JSON.stringify(liveReloadOptions) + ";" : ''}
var srcUrl = ${options.liveReloadJsUrl ? "'" + options.liveReloadJsUrl + "'" : null};
var host= location.hostname || 'localhost';
var liveReloadPort = ${liveReloadPort};
var defaultPort = location.protocol === 'https:' ? 443 : 80;
var port = liveReloadPort || location.port || defaultPort;
var path = '${path}';
var prefixURL = ${liveReloadPort ? "(location.protocol || 'http:') + '//' + host + ':' + " + liveReloadPort : ''};
var src = srcUrl || prefixURL + '${liveReloadPath + 'livereload.js?port='}' + port + '&host=' + host + path;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}());`;
},
serverMiddleware: function(config) {
let options = config.options;
let app = config.app;
let self = this;
// maintaining `baseURL` for backwards compatibility. See: http://emberjs.com/blog/2016/04/28/baseURL.html
let baseURL = options.liveReloadBaseUrl || options.rootURL || options.baseURL;
if (this.parent) {
let checker = new VersionChecker(this.parent);
let depedency = checker.for('ember-cli');
options.isLatestEmber = depedency.gt('3.5.0-beta.2');
}
if (options.liveReload !== true) { return; }
process.env.EMBER_CLI_INJECT_LIVE_RELOAD_PORT = options.liveReloadPort;
process.env.EMBER_CLI_INJECT_LIVE_RELOAD_BASEURL = baseURL;
let baseURLWithoutHost = baseURL.replace(/^https?:\/\/[^/]+/, '');
app.use(baseURLWithoutHost + 'ember-cli-live-reload.js', function(request, response) {
response.contentType('text/javascript');
response.send(self.dynamicScript(options));
});
}
};
| fix: add empty string in `dynamicScript` | index.js | fix: add empty string in `dynamicScript` | <ide><path>ndex.js
<ide> var defaultPort = location.protocol === 'https:' ? 443 : 80;
<ide> var port = liveReloadPort || location.port || defaultPort;
<ide> var path = '${path}';
<del> var prefixURL = ${liveReloadPort ? "(location.protocol || 'http:') + '//' + host + ':' + " + liveReloadPort : ''};
<add> var prefixURL = ${liveReloadPort ? "(location.protocol || 'http:') + '//' + host + ':' + " + liveReloadPort : "''"};
<ide> var src = srcUrl || prefixURL + '${liveReloadPath + 'livereload.js?port='}' + port + '&host=' + host + path;
<ide> var script = document.createElement('script');
<ide> script.type = 'text/javascript'; |
|
Java | apache-2.0 | 1aa27ea5954e3ed87276f9c00974c893ee207a44 | 0 | openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb,openengsb/openengsb | /**
// * Copyright 2010 OpenEngSB Division, Vienna University of Technology
*
* 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.
*/
package org.openengsb.tooling.pluginsuite.openengsbplugin;
import java.util.Arrays;
import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* equivalent to <code>mvn clean validate -Plicense-check</code>
*
* @goal licenseCheck
*
* @inheritedByDefault false
*
* @requiresProject true
*
*/
public class LicenseCheck extends AbstractOpenengsbMojo {
private List<String> goals;
private List<String> activatedProfiles;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
validateIfExecutionIsAllowed();
initializeMavenExecutionProperties();
executeMaven();
}
private void validateIfExecutionIsAllowed() throws MojoExecutionException {
throwErrorIfWrapperRequestIsRecursive();
throwErrorIfProjectIsNotExecutedInRootDirectory();
}
private void initializeMavenExecutionProperties() {
goals = Arrays
.asList(new String[]{ "clean", "validate" });
activatedProfiles = Arrays
.asList(new String[]{ "license-check" });
}
private void executeMaven() throws MojoExecutionException {
getNewMavenExecutor().setRecursive(true).execute(this, goals, activatedProfiles, null, null,
getProject(), getSession(), getMaven());
}
}
| tooling/maven-openengsb-plugin/src/main/java/org/openengsb/tooling/pluginsuite/openengsbplugin/LicenseCheck.java | /**
// * Copyright 2010 OpenEngSB Division, Vienna University of Technology
*
* 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.
*/
package org.openengsb.tooling.pluginsuite.openengsbplugin;
import java.util.Arrays;
import java.util.List;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
/**
* equivalent to <code>mvn clean validate -Plicense-check</code>
*
* @goal licenseCheck
*
* @inheritedByDefault false
*
* @requiresProject true
*
*/
public class LicenseCheck extends AbstractOpenengsbMojo {
private List<String> goals;
private List<String> activatedProfiles;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (!getProject().isExecutionRoot()) {
return;
}
validateIfExecutionIsAllowed();
initializeMavenExecutionProperties();
executeMaven();
}
private void validateIfExecutionIsAllowed() throws MojoExecutionException {
throwErrorIfWrapperRequestIsRecursive();
throwErrorIfProjectIsNotExecutedInRootDirectory();
}
private void initializeMavenExecutionProperties() {
goals = Arrays
.asList(new String[]{ "clean", "validate" });
activatedProfiles = Arrays
.asList(new String[]{ "license-check" });
}
private void executeMaven() throws MojoExecutionException {
getNewMavenExecutor().setRecursive(true).execute(this, goals, activatedProfiles, null, null,
getProject(), getSession(), getMaven());
}
}
| removed minor duplication of code
Signed-off-by: Andreas Pieber <[email protected]>
| tooling/maven-openengsb-plugin/src/main/java/org/openengsb/tooling/pluginsuite/openengsbplugin/LicenseCheck.java | removed minor duplication of code | <ide><path>ooling/maven-openengsb-plugin/src/main/java/org/openengsb/tooling/pluginsuite/openengsbplugin/LicenseCheck.java
<ide>
<ide> @Override
<ide> public void execute() throws MojoExecutionException, MojoFailureException {
<del> if (!getProject().isExecutionRoot()) {
<del> return;
<del> }
<ide> validateIfExecutionIsAllowed();
<ide> initializeMavenExecutionProperties();
<ide> executeMaven(); |
|
Java | bsd-3-clause | e90a5668ef2bdf748fc5bb330f6c7df5960ee224 | 0 | harnesscloud/xtreemfs,kleingeist/xtreemfs,harnesscloud/xtreemfs,kleingeist/xtreemfs,kleingeist/xtreemfs,rbaerzib/xtreemfs,rbaerzib/xtreemfs,harnesscloud/xtreemfs,jswrenn/xtreemfs,rbaerzib/xtreemfs,rbaerzib/xtreemfs,jswrenn/xtreemfs,jswrenn/xtreemfs,rbaerzib/xtreemfs,jswrenn/xtreemfs,jswrenn/xtreemfs,kleingeist/xtreemfs,harnesscloud/xtreemfs,kleingeist/xtreemfs,rbaerzib/xtreemfs,harnesscloud/xtreemfs,kleingeist/xtreemfs,rbaerzib/xtreemfs,kleingeist/xtreemfs,harnesscloud/xtreemfs,jswrenn/xtreemfs,jswrenn/xtreemfs,harnesscloud/xtreemfs,harnesscloud/xtreemfs,kleingeist/xtreemfs,jswrenn/xtreemfs,rbaerzib/xtreemfs | /*
* Copyright (c) 2008-2011 by Bjoern Kolbeck, Jan Stender,
* Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.osd.stages;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.xtreemfs.common.Capability;
import org.xtreemfs.common.ReplicaUpdatePolicies;
import org.xtreemfs.common.xloc.XLocations;
import org.xtreemfs.foundation.LRUCache;
import org.xtreemfs.foundation.TimeSync;
import org.xtreemfs.foundation.buffer.ASCIIString;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.MessageType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse;
import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils;
import org.xtreemfs.foundation.pbrpc.utils.ReusableBufferInputStream;
import org.xtreemfs.foundation.util.OutputUtils;
import org.xtreemfs.osd.AdvisoryLock;
import org.xtreemfs.osd.OSDRequest;
import org.xtreemfs.osd.OSDRequestDispatcher;
import org.xtreemfs.osd.OpenFileTable;
import org.xtreemfs.osd.OpenFileTable.OpenFileTableEntry;
import org.xtreemfs.osd.operations.DeleteOperation;
import org.xtreemfs.osd.operations.EventCloseFile;
import org.xtreemfs.osd.operations.EventCreateFileVersion;
import org.xtreemfs.osd.operations.OSDOperation;
import org.xtreemfs.osd.rwre.ReplicaUpdatePolicy;
import org.xtreemfs.osd.storage.CowPolicy;
import org.xtreemfs.osd.storage.CowPolicy.cowMode;
import org.xtreemfs.osd.storage.MetadataCache;
import org.xtreemfs.osd.storage.StorageLayout;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SnapConfig;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.Lock;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.XLocSetVersionState;
import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceConstants;
import com.google.protobuf.Message;
public class PreprocStage extends Stage {
public final static int STAGEOP_PARSE_AUTH_OFTOPEN = 1;
public final static int STAGEOP_OFT_DELETE = 2;
public final static int STAGEOP_ACQUIRE_LEASE = 3;
public final static int STAGEOP_RETURN_LEASE = 4;
public final static int STAGEOP_VERIFIY_CLEANUP = 5;
public final static int STAGEOP_ACQUIRE_LOCK = 10;
public final static int STAGEOP_CHECK_LOCK = 11;
public final static int STAGEOP_UNLOCK = 12;
public final static int STAGEOP_PING_FILE = 14;
public final static int STAGEOP_INSTALL_XLOC = 15;
public final static int STAGEOP_INVALIDATE_XLOC = 16;
public final static int STAGEOP_UPDATE_XLOC = 17;
private final static long OFT_CLEAN_INTERVAL = 1000 * 60;
private final static long OFT_OPEN_EXTENSION = 1000 * 30;
private final Map<String, LRUCache<String, Capability>> capCache;
private final OpenFileTable oft;
// time left to next clean op
private long timeToNextOFTclean;
// last check of the OFT
private long lastOFTcheck;
private volatile long numRequests;
/**
* X-Location cache
*/
private final LRUCache<String, XLocations> xLocCache;
private final MetadataCache metadataCache;
private final StorageLayout layout;
private final OSDRequestDispatcher master;
private final boolean ignoreCaps;
private static final int MAX_CAP_CACHE = 20;
/** Creates a new instance of AuthenticationStage */
public PreprocStage(OSDRequestDispatcher master, MetadataCache metadataCache, StorageLayout layout,
int maxRequestsQueueLength) {
super("OSD PreProcSt", maxRequestsQueueLength);
capCache = new HashMap();
oft = new OpenFileTable();
xLocCache = new LRUCache<String, XLocations>(10000);
this.master = master;
this.metadataCache = metadataCache;
this.layout = layout;
this.ignoreCaps = master.getConfig().isIgnoreCaps();
}
public void prepareRequest(OSDRequest request, ParseCompleteCallback listener) {
this.enqueueOperation(STAGEOP_PARSE_AUTH_OFTOPEN, new Object[] { request }, null, listener);
}
public static interface ParseCompleteCallback {
public void parseComplete(OSDRequest result, ErrorResponse error);
}
private void doPrepareRequest(StageRequest rq) {
final OSDRequest request = (OSDRequest) rq.getArgs()[0];
final ParseCompleteCallback callback = (ParseCompleteCallback) rq.getCallback();
numRequests++;
if (parseRequest(request) == false)
return;
if (request.getOperation().requiresCapability()) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "STAGEOP AUTH");
ErrorResponse err = processAuthenticate(request);
if (err != null) {
callback.parseComplete(request, err);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"authentication of request failed: %s", ErrorUtils.formatError(err));
}
return;
}
}
// check if the request is from the same view (same XLocationSet version)
if (request.getOperation().requiresValidView()) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "STAGEOP VIEW");
ErrorResponse error = processValidateView(request);
if (error != null) {
callback.parseComplete(request, error);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.misc, this,
"request failed with an invalid view: %s", ErrorUtils.formatError(error));
}
return;
}
}
String fileId = request.getFileId();
if (fileId != null) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "STAGEOP OPEN");
CowPolicy cowPolicy = CowPolicy.PolicyNoCow;
// Open file unless it is a DeleteOperation.
if (!(request.getOperation() instanceof DeleteOperation)) {
// check if snasphots are enabled and a write operation is executed;
// this is required to create new snapshots when files open for
// writing are closed, even if the same files are still open for
// reading
boolean write = request.getCapability() != null
&& request.getCapability().getSnapConfig() != SnapConfig.SNAP_CONFIG_SNAPS_DISABLED
&& ((SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()
| SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY
.getNumber()) & request.getCapability().getAccessMode()) > 0;
if (oft.contains(fileId)) {
cowPolicy = oft.refresh(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, write);
} else {
// find out which COW mode to use, depending on the capability
if (request.getCapability() == null
|| request.getCapability().getSnapConfig() == SnapConfig.SNAP_CONFIG_SNAPS_DISABLED)
cowPolicy = CowPolicy.PolicyNoCow;
else
cowPolicy = new CowPolicy(cowMode.COW_ONCE);
oft.openFile(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, cowPolicy, write);
request.setFileOpen(true);
}
} else {
// It's a DeleteOperation. Close the file first.
if (oft.close(fileId)) {
checkOpenFileTable(true);
}
}
request.setCowPolicy(cowPolicy);
}
callback.parseComplete(request, null);
}
public void pingFile(String fileId) {
this.enqueueOperation(STAGEOP_PING_FILE, new Object[] { fileId }, null, null);
}
private void doPingFile(StageRequest m) {
final String fileId = (String) m.getArgs()[0];
// TODO: check if the file was opened for writing
oft.refresh(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, false);
}
public void checkDeleteOnClose(String fileId, DeleteOnCloseCallback listener) {
this.enqueueOperation(STAGEOP_OFT_DELETE, new Object[] { fileId }, null, listener);
}
public static interface DeleteOnCloseCallback {
public void deleteOnCloseResult(boolean isDeleteOnClose, ErrorResponse error);
}
private void doCheckDeleteOnClose(StageRequest m) {
final String fileId = (String) m.getArgs()[0];
final DeleteOnCloseCallback callback = (DeleteOnCloseCallback) m.getCallback();
final boolean deleteOnClose = oft.contains(fileId);
if (deleteOnClose)
oft.setDeleteOnClose(fileId);
callback.deleteOnCloseResult(deleteOnClose, null);
}
public static interface LockOperationCompleteCallback {
public void parseComplete(Lock result, ErrorResponse error);
}
public void acquireLock(String clientUuid, int pid, String fileId, long offset, long length,
boolean exclusive, OSDRequest request, LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_ACQUIRE_LOCK, new Object[] { clientUuid, pid, fileId, offset, length,
exclusive }, request, listener);
}
public void doAcquireLock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
final Long offset = (Long) m.getArgs()[3];
final Long length = (Long) m.getArgs()[4];
final Boolean exclusive = (Boolean) m.getArgs()[5];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
AdvisoryLock l = e.acquireLock(clientUuid, pid, offset, length, exclusive);
if (l != null) {
Lock lock = Lock.newBuilder().setClientPid(l.getClientPid()).setClientUuid(l.getClientUuid()).setLength(l.getLength()).setOffset(l.getOffset()).setExclusive(l.isExclusive()).build();
callback.parseComplete(lock, null);
}
else
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EAGAIN, "conflicting lock"));
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
public void checkLock(String clientUuid, int pid, String fileId, long offset, long length,
boolean exclusive, OSDRequest request, LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_CHECK_LOCK, new Object[] { clientUuid, pid, fileId, offset, length,
exclusive }, request, listener);
}
public void doCheckLock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
final Long offset = (Long) m.getArgs()[3];
final Long length = (Long) m.getArgs()[4];
final Boolean exclusive = (Boolean) m.getArgs()[5];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
AdvisoryLock l = e.checkLock(clientUuid, pid, offset, length, exclusive);
Lock lock = Lock.newBuilder().setClientPid(l.getClientPid()).setClientUuid(l.getClientUuid()).setLength(l.getLength()).setOffset(l.getOffset()).setExclusive(l.isExclusive()).build();
callback.parseComplete(lock, null);
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
public void unlock(String clientUuid, int pid, String fileId, OSDRequest request,
LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_UNLOCK, new Object[] { clientUuid, pid, fileId }, request, listener);
}
public void doUnlock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
e.unlock(clientUuid, pid);
callback.parseComplete(null, null);
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
@Override
public void run() {
notifyStarted();
// interval to check the OFT
timeToNextOFTclean = OFT_CLEAN_INTERVAL;
lastOFTcheck = TimeSync.getLocalSystemTime();
while (!quit) {
try {
final StageRequest op = q.poll(timeToNextOFTclean, TimeUnit.MILLISECONDS);
checkOpenFileTable(false);
if (op == null) {
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"no request
// -- timer only");
continue;
}
processMethod(op);
} catch (InterruptedException ex) {
break;
} catch (Throwable ex) {
notifyCrashed(ex);
break;
}
}
notifyStopped();
}
/**
* Removes all open files from the {@link OpenFileTable} whose time has expired and triggers for each file
* the internal event {@link EventCloseFile} or {@link EventCreateFileVersion}.
*
* @param force
* If true, force the cleaning and do not respect the cleaning interval.
*/
private void checkOpenFileTable(boolean force) {
final long tPassed = TimeSync.getLocalSystemTime() - lastOFTcheck;
timeToNextOFTclean = timeToNextOFTclean - tPassed;
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"time to next OFT:
// "+timeToNextOFTclean);
if (force || timeToNextOFTclean <= 0) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.proc, this, "OpenFileTable clean");
long currentTime = TimeSync.getLocalSystemTime();
// do OFT clean
List<OpenFileTable.OpenFileTableEntry> closedFiles = oft.clean(currentTime);
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"closing
// "+closedFiles.size()+" files");
for (OpenFileTable.OpenFileTableEntry entry : closedFiles) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this,
"send internal close event for %s, deleteOnClose=%b", entry.getFileId(), entry
.isDeleteOnClose());
LRUCache<String, Capability> cachedCaps = capCache.remove(entry.getFileId());
// send close event
OSDOperation closeEvent = master.getInternalEvent(EventCloseFile.class);
closeEvent.startInternalEvent(new Object[] { entry.getFileId(), entry.isDeleteOnClose(),
metadataCache.getFileInfo(entry.getFileId()), entry.getCowPolicy(), cachedCaps });
}
// check if written files need to be closed; if no files were closed
// completely, generate close events w/o discarding the open state
List<OpenFileTable.OpenFileTableEntry> closedWrittenFiles = oft.cleanWritten(currentTime);
if (closedFiles.size() == 0) {
for (OpenFileTable.OpenFileTableEntry entry : closedWrittenFiles) {
OSDOperation createVersionEvent = master.getInternalEvent(EventCreateFileVersion.class);
createVersionEvent.startInternalEvent(new Object[] { entry.getFileId(),
metadataCache.getFileInfo(entry.getFileId()) });
}
}
timeToNextOFTclean = OFT_CLEAN_INTERVAL;
}
lastOFTcheck = TimeSync.getLocalSystemTime();
}
@Override
protected void processMethod(StageRequest m) {
final int requestedMethod = m.getStageMethod();
switch (requestedMethod) {
case STAGEOP_PARSE_AUTH_OFTOPEN:
doPrepareRequest(m);
break;
case STAGEOP_OFT_DELETE:
doCheckDeleteOnClose(m);
break;
case STAGEOP_ACQUIRE_LOCK:
doAcquireLock(m);
break;
case STAGEOP_CHECK_LOCK:
doCheckLock(m);
break;
case STAGEOP_UNLOCK:
doUnlock(m);
break;
case STAGEOP_PING_FILE:
doPingFile(m);
break;
case STAGEOP_INSTALL_XLOC:
doInstallXLocSet(m);
break;
case STAGEOP_INVALIDATE_XLOC:
doInvalidateXLocSet(m);
break;
case STAGEOP_UPDATE_XLOC:
doUpdateXLocSetFromFlease(m);
break;
default:
Logging.logMessage(Logging.LEVEL_ERROR, this, "unknown stageop called: %d", requestedMethod);
break;
}
}
private boolean parseRequest(OSDRequest rq) {
RPCHeader hdr = rq.getRpcRequest().getHeader();
if (hdr.getMessageType() != MessageType.RPC_REQUEST) {
rq.sendError(ErrorType.GARBAGE_ARGS, POSIXErrno.POSIX_ERROR_EIO, "expected RPC request message type but got "+hdr.getMessageType());
return false;
}
RPCHeader.RequestHeader rqHdr = hdr.getRequestHeader();
if (rqHdr.getInterfaceId() != OSDServiceConstants.INTERFACE_ID) {
rq.sendError(ErrorType.INVALID_INTERFACE_ID, POSIXErrno.POSIX_ERROR_EIO, "invalid interface id. Maybe wrong service address/port configured?");
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"invalid version requested (requested=%d avail=%d)", rqHdr.getInterfaceId(),
OSDServiceConstants.INTERFACE_ID);
}
return false;
}
// everything ok, find the right operation
OSDOperation op = master.getOperation(rqHdr.getProcId());
if (op == null) {
rq.sendError(ErrorType.INVALID_PROC_ID, POSIXErrno.POSIX_ERROR_EINVAL, "requested operation is not available on this OSD (proc # "
+ rqHdr.getProcId() + ")");
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"requested operation is not available on this OSD (proc #%d)", rqHdr.getProcId());
}
return false;
}
rq.setOperation(op);
try {
final Message rqPrototype = OSDServiceConstants.getRequestMessage(rqHdr.getProcId());
if (rqPrototype == null) {
rq.setRequestArgs(null);
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request with empty message");
} else {
if (rq.getRPCRequest().getMessage() != null) {
rq.setRequestArgs(rqPrototype.newBuilderForType().mergeFrom(new ReusableBufferInputStream(rq.getRPCRequest().getMessage())).build());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request of type %s",
rq.getRequestArgs().getClass().getName());
}
} else {
rq.setRequestArgs(rqPrototype.getDefaultInstanceForType());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request of type %s (empty message)",
rq.getRequestArgs().getClass().getName());
}
}
}
ErrorResponse err = op.parseRPCMessage(rq);
if (err != null) {
rq.getRpcRequest().sendError(err);
return false;
}
} catch (Throwable ex) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.proc, this, OutputUtils
.stackTraceToString(ex));
rq.getRpcRequest().sendError(ErrorUtils.getInternalServerError(ex));
return false;
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "request parsed: %d", rq
.getRequestId());
}
return true;
}
private ErrorResponse processAuthenticate(OSDRequest rq) {
final Capability rqCap = rq.getCapability();
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this, "capability: %s", rqCap.getXCap().toString().replace('\n', '/'));
}
// check if the capability has valid arguments
if (rqCap.getFileId().length() == 0) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL, "invalid capability. file_id must not be empty");
}
if (rqCap.getEpochNo() < 0) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL, "invalid capability. epoch must not be < 0");
}
if (ignoreCaps)
return null;
// check if the capability is valid
boolean isValid = false;
// look in capCache
LRUCache<String, Capability> cachedCaps = capCache.get(rqCap.getFileId());
if (cachedCaps != null) {
final Capability cap = cachedCaps.get(rqCap.getSignature());
if (cap != null) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this, "using cached cap: %s %s", cap.getFileId(),
cap.getSignature());
}
isValid = !cap.hasExpired();
}
}
if (!isValid) {
isValid = rqCap.isValid();
if (isValid) {
// add to cache
if (cachedCaps == null) {
cachedCaps = new LRUCache<String, Capability>(MAX_CAP_CACHE);
capCache.put(rqCap.getFileId(), cachedCaps);
}
cachedCaps.put(rqCap.getSignature(), rqCap);
}
}
// depending on the result the event listener is sent
if (!isValid) {
if (rqCap.hasExpired())
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (timed out)");
if (!rqCap.hasValidSignature())
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (invalid signature)");
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (unknown cause)");
}
// check if the capability was issued for the requested file
if (!rqCap.getFileId().equals(rq.getFileId())) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability was issued for another file than the one requested");
}
// check if the capability provides sufficient access rights for
// requested operation
if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_READ) {
if ((rqCap.getAccessMode() & (SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY.getNumber())) != 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow read access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_WRITE) {
if ((rqCap.getAccessMode() & (SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber()
| SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR
.getNumber())) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow write access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_TRUNCATE) {
if ((rqCap.getAccessMode() & SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber()) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow truncate access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_UNLINK) {
// TODO: replace numeric flag with constant
if ((rqCap.getAccessMode() & 010000000) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow delete access to file " + rqCap.getFileId());
}
// TODO(jdillmann): check rights for invalidate, install, and internal fetch invalidated
return null;
}
private ErrorResponse processValidateView(OSDRequest request) {
String fileId = request.getFileId();
if (fileId == null || fileId.length() == 0) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL,
"invalid view. file_id must not be empty");
}
XLocations xloc = request.getLocationList();
if (xloc == null) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL,
"invalid view. xlocset must not be empty");
}
XLocSetVersionState state;
try {
// TODO(jdillmann): Cache the VersionState
state = layout.getXLocSetVersionState(fileId);
} catch (IOException e) {
// TODO(jdillmann): do something with the error
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO,
"invalid view. local version could not be read");
}
XLocations locset = request.getLocationList();
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,
"operation: %s, local version: %s, request version: %s, destination: %s", request.getOperation()
.getClass().getSimpleName(), state.getVersion(), locset.getVersion(), master.getConfig()
.getPort());
}
if (state.getVersion() == locset.getVersion() && !state.getInvalidated()) {
return null;
} else if (locset.getVersion() > state.getVersion()) {
XLocSetVersionState newstate = state.toBuilder()
.setInvalidated(false)
.setVersion(locset.getVersion())
.build();
try {
// persist the view
layout.setXLocSetVersionState(fileId, newstate);
// inform flease about the new view
if (!locset.getReplicaUpdatePolicy().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY)) {
ASCIIString cellId = ReplicaUpdatePolicy.fileToCellId(fileId);
// TODO(jdillmann): think about using a callback which will be called when flease got the message
master.getRWReplicationStage().setFleaseView(fileId, cellId, newstate);
}
} catch (IOException e) {
// TODO(jdillmann): do something with the error
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO,
"invalid view. local version could not be written");
}
return null;
}
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EAGAIN, "view is not valid");
}
/**
* Process a viewIdChangeEvent from flease and update the persistent version/state
*/
public void updateXLocSetFromFlease(ASCIIString cellId, int version) {
enqueueOperation(STAGEOP_UPDATE_XLOC, new Object[] { cellId, version }, null, null);
}
private void doUpdateXLocSetFromFlease(StageRequest m) {
final ASCIIString cellId = (ASCIIString) m.getArgs()[0];
final int version = (Integer) m.getArgs()[1];
final String fileId = ReplicaUpdatePolicy.cellToFileId(cellId);
XLocSetVersionState state;
try {
// TODO(jdillmann): Cache the VersionState
state = layout.getXLocSetVersionState(fileId);
} catch (IOException e) {
// TODO(jdillmann): do something with the error or at least log it
Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,
"VersionState could not be read for fileId: %s", fileId);
return;
}
// If a response from a newer View is encountered, we have to install it and leave the invalidated state.
if (state.getVersion() < version) {
state = state.toBuilder().setInvalidated(false).setVersion(version).build();
try {
// persist the version
layout.setXLocSetVersionState(fileId, state);
// and pass it back to flease
master.getRWReplicationStage().setFleaseView(fileId, cellId, state);
} catch (IOException e) {
// TODO(jdillmann): do something with the error or at least log it
Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,
"VersionState could not be written for fileId: %s", fileId);
return;
}
}
// If the local version is greater then the one flease got from it responses, the other replicas have
// to update their version. There exists no path to decrement the version if it has been seen once.
return;
}
/**
* Invalidate the current XLocSet. The replica will not respond to read/write/truncate or flease
* operations until a new XLocSet is installed.
*/
public void invalidateXLocSet(OSDRequest request, final InvalidateXLocSetCallback listener) {
enqueueOperation(STAGEOP_INVALIDATE_XLOC, new Object[] {}, request, listener);
}
private void doInvalidateXLocSet(StageRequest m) {
final OSDRequest request = m.getRequest();
final String fileId = request.getFileId();
final InvalidateXLocSetCallback callback = (InvalidateXLocSetCallback) m.getCallback();
XLocSetVersionState state;
try {
state = layout.getXLocSetVersionState(fileId).toBuilder().setInvalidated(true).build();
layout.setXLocSetVersionState(fileId, state);
if (request.getLocationList().getReplicaUpdatePolicy().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY)) {
callback.invalidateComplete(true, null);
} else {
ASCIIString cellId = ReplicaUpdatePolicy.fileToCellId(fileId);
master.getRWReplicationStage().invalidateFleaseView(fileId, cellId, callback);
}
} catch (IOException e) {
// TODO(jdillmann): do something with the exception
ErrorResponse error = ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO,
"invalid view. local version could not be written");
callback.invalidateComplete(false, error);
}
}
public static interface InvalidateXLocSetCallback {
public void invalidateComplete(boolean isPrimary, ErrorResponse error);
}
/**
* Install a new XLocSet and release the replica from the invalidated state.
*/
public void installXLocSet(OSDRequest request, InstallXLocSetCallback listener) {
enqueueOperation(STAGEOP_INSTALL_XLOC, new Object[] {}, request, listener);
}
private void doInstallXLocSet(StageRequest m) {
final OSDRequest request = m.getRequest();
final String fileId = request.getFileId();
final InstallXLocSetCallback callback = (InstallXLocSetCallback) m.getCallback();
XLocSetVersionState state = XLocSetVersionState.newBuilder()
.setInvalidated(false)
.setVersion(request.getLocationList().getVersion())
.build();
try {
layout.setXLocSetVersionState(fileId, state);
if (request.getLocationList().getReplicaUpdatePolicy().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY)) {
callback.installComplete(fileId, state.getVersion(), null);
} else {
ASCIIString cellId = ReplicaUpdatePolicy.fileToCellId(fileId);
master.getRWReplicationStage().setFleaseView(fileId, cellId, state, callback);
}
} catch (IOException e) {
// TODO(jdillmann): do something with the exception
ErrorResponse error = ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO,
"invalid view. local version could not be written");
callback.installComplete(fileId, -1, error);
}
}
public static interface InstallXLocSetCallback {
public void installComplete(String fileId, int version, ErrorResponse error);
}
public int getNumOpenFiles() {
return oft.getNumOpenFiles();
}
public long getNumRequests() {
return numRequests;
}
}
| java/servers/src/org/xtreemfs/osd/stages/PreprocStage.java | /*
* Copyright (c) 2008-2011 by Bjoern Kolbeck, Jan Stender,
* Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.osd.stages;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.xtreemfs.common.Capability;
import org.xtreemfs.common.ReplicaUpdatePolicies;
import org.xtreemfs.common.xloc.XLocations;
import org.xtreemfs.foundation.LRUCache;
import org.xtreemfs.foundation.TimeSync;
import org.xtreemfs.foundation.buffer.ASCIIString;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.MessageType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.RPCHeader.ErrorResponse;
import org.xtreemfs.foundation.pbrpc.utils.ErrorUtils;
import org.xtreemfs.foundation.pbrpc.utils.ReusableBufferInputStream;
import org.xtreemfs.foundation.util.OutputUtils;
import org.xtreemfs.osd.AdvisoryLock;
import org.xtreemfs.osd.OSDRequest;
import org.xtreemfs.osd.OSDRequestDispatcher;
import org.xtreemfs.osd.OpenFileTable;
import org.xtreemfs.osd.OpenFileTable.OpenFileTableEntry;
import org.xtreemfs.osd.operations.DeleteOperation;
import org.xtreemfs.osd.operations.EventCloseFile;
import org.xtreemfs.osd.operations.EventCreateFileVersion;
import org.xtreemfs.osd.operations.OSDOperation;
import org.xtreemfs.osd.rwre.ReplicaUpdatePolicy;
import org.xtreemfs.osd.storage.CowPolicy;
import org.xtreemfs.osd.storage.CowPolicy.cowMode;
import org.xtreemfs.osd.storage.MetadataCache;
import org.xtreemfs.osd.storage.StorageLayout;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SYSTEM_V_FCNTL;
import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.SnapConfig;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.Lock;
import org.xtreemfs.pbrpc.generatedinterfaces.OSD.XLocSetVersionState;
import org.xtreemfs.pbrpc.generatedinterfaces.OSDServiceConstants;
import com.google.protobuf.Message;
public class PreprocStage extends Stage {
public final static int STAGEOP_PARSE_AUTH_OFTOPEN = 1;
public final static int STAGEOP_OFT_DELETE = 2;
public final static int STAGEOP_ACQUIRE_LEASE = 3;
public final static int STAGEOP_RETURN_LEASE = 4;
public final static int STAGEOP_VERIFIY_CLEANUP = 5;
public final static int STAGEOP_ACQUIRE_LOCK = 10;
public final static int STAGEOP_CHECK_LOCK = 11;
public final static int STAGEOP_UNLOCK = 12;
public final static int STAGEOP_PING_FILE = 14;
public final static int STAGEOP_INSTALL_XLOC = 15;
public final static int STAGEOP_INVALIDATE_XLOC = 16;
public final static int STAGEOP_UPDATE_XLOC = 17;
private final static long OFT_CLEAN_INTERVAL = 1000 * 60;
private final static long OFT_OPEN_EXTENSION = 1000 * 30;
private final Map<String, LRUCache<String, Capability>> capCache;
private final OpenFileTable oft;
// time left to next clean op
private long timeToNextOFTclean;
// last check of the OFT
private long lastOFTcheck;
private volatile long numRequests;
/**
* X-Location cache
*/
private final LRUCache<String, XLocations> xLocCache;
private final MetadataCache metadataCache;
private final StorageLayout layout;
private final OSDRequestDispatcher master;
private final boolean ignoreCaps;
private static final int MAX_CAP_CACHE = 20;
/** Creates a new instance of AuthenticationStage */
public PreprocStage(OSDRequestDispatcher master, MetadataCache metadataCache, StorageLayout layout,
int maxRequestsQueueLength) {
super("OSD PreProcSt", maxRequestsQueueLength);
capCache = new HashMap();
oft = new OpenFileTable();
xLocCache = new LRUCache<String, XLocations>(10000);
this.master = master;
this.metadataCache = metadataCache;
this.layout = layout;
this.ignoreCaps = master.getConfig().isIgnoreCaps();
}
public void prepareRequest(OSDRequest request, ParseCompleteCallback listener) {
this.enqueueOperation(STAGEOP_PARSE_AUTH_OFTOPEN, new Object[] { request }, null, listener);
}
public static interface ParseCompleteCallback {
public void parseComplete(OSDRequest result, ErrorResponse error);
}
private void doPrepareRequest(StageRequest rq) {
final OSDRequest request = (OSDRequest) rq.getArgs()[0];
final ParseCompleteCallback callback = (ParseCompleteCallback) rq.getCallback();
numRequests++;
if (parseRequest(request) == false)
return;
if (request.getOperation().requiresCapability()) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "STAGEOP AUTH");
ErrorResponse err = processAuthenticate(request);
if (err != null) {
callback.parseComplete(request, err);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"authentication of request failed: %s", ErrorUtils.formatError(err));
}
return;
}
}
// check if the request is from the same view (same XLocationSet version)
if (request.getOperation().requiresValidView()) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "STAGEOP VIEW");
ErrorResponse error = processValidateView(request);
if (error != null) {
callback.parseComplete(request, error);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.misc, this,
"request failed with an invalid view: %s", ErrorUtils.formatError(error));
}
return;
}
}
String fileId = request.getFileId();
if (fileId != null) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "STAGEOP OPEN");
CowPolicy cowPolicy = CowPolicy.PolicyNoCow;
// Open file unless it is a DeleteOperation.
if (!(request.getOperation() instanceof DeleteOperation)) {
// check if snasphots are enabled and a write operation is executed;
// this is required to create new snapshots when files open for
// writing are closed, even if the same files are still open for
// reading
boolean write = request.getCapability() != null
&& request.getCapability().getSnapConfig() != SnapConfig.SNAP_CONFIG_SNAPS_DISABLED
&& ((SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR.getNumber()
| SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY
.getNumber()) & request.getCapability().getAccessMode()) > 0;
if (oft.contains(fileId)) {
cowPolicy = oft.refresh(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, write);
} else {
// find out which COW mode to use, depending on the capability
if (request.getCapability() == null
|| request.getCapability().getSnapConfig() == SnapConfig.SNAP_CONFIG_SNAPS_DISABLED)
cowPolicy = CowPolicy.PolicyNoCow;
else
cowPolicy = new CowPolicy(cowMode.COW_ONCE);
oft.openFile(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, cowPolicy, write);
request.setFileOpen(true);
}
} else {
// It's a DeleteOperation. Close the file first.
if (oft.close(fileId)) {
checkOpenFileTable(true);
}
}
request.setCowPolicy(cowPolicy);
}
callback.parseComplete(request, null);
}
public void pingFile(String fileId) {
this.enqueueOperation(STAGEOP_PING_FILE, new Object[] { fileId }, null, null);
}
private void doPingFile(StageRequest m) {
final String fileId = (String) m.getArgs()[0];
// TODO: check if the file was opened for writing
oft.refresh(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, false);
}
public void checkDeleteOnClose(String fileId, DeleteOnCloseCallback listener) {
this.enqueueOperation(STAGEOP_OFT_DELETE, new Object[] { fileId }, null, listener);
}
public static interface DeleteOnCloseCallback {
public void deleteOnCloseResult(boolean isDeleteOnClose, ErrorResponse error);
}
private void doCheckDeleteOnClose(StageRequest m) {
final String fileId = (String) m.getArgs()[0];
final DeleteOnCloseCallback callback = (DeleteOnCloseCallback) m.getCallback();
final boolean deleteOnClose = oft.contains(fileId);
if (deleteOnClose)
oft.setDeleteOnClose(fileId);
callback.deleteOnCloseResult(deleteOnClose, null);
}
public static interface LockOperationCompleteCallback {
public void parseComplete(Lock result, ErrorResponse error);
}
public void acquireLock(String clientUuid, int pid, String fileId, long offset, long length,
boolean exclusive, OSDRequest request, LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_ACQUIRE_LOCK, new Object[] { clientUuid, pid, fileId, offset, length,
exclusive }, request, listener);
}
public void doAcquireLock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
final Long offset = (Long) m.getArgs()[3];
final Long length = (Long) m.getArgs()[4];
final Boolean exclusive = (Boolean) m.getArgs()[5];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
AdvisoryLock l = e.acquireLock(clientUuid, pid, offset, length, exclusive);
if (l != null) {
Lock lock = Lock.newBuilder().setClientPid(l.getClientPid()).setClientUuid(l.getClientUuid()).setLength(l.getLength()).setOffset(l.getOffset()).setExclusive(l.isExclusive()).build();
callback.parseComplete(lock, null);
}
else
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EAGAIN, "conflicting lock"));
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
public void checkLock(String clientUuid, int pid, String fileId, long offset, long length,
boolean exclusive, OSDRequest request, LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_CHECK_LOCK, new Object[] { clientUuid, pid, fileId, offset, length,
exclusive }, request, listener);
}
public void doCheckLock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
final Long offset = (Long) m.getArgs()[3];
final Long length = (Long) m.getArgs()[4];
final Boolean exclusive = (Boolean) m.getArgs()[5];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
AdvisoryLock l = e.checkLock(clientUuid, pid, offset, length, exclusive);
Lock lock = Lock.newBuilder().setClientPid(l.getClientPid()).setClientUuid(l.getClientUuid()).setLength(l.getLength()).setOffset(l.getOffset()).setExclusive(l.isExclusive()).build();
callback.parseComplete(lock, null);
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
public void unlock(String clientUuid, int pid, String fileId, OSDRequest request,
LockOperationCompleteCallback listener) {
this.enqueueOperation(STAGEOP_UNLOCK, new Object[] { clientUuid, pid, fileId }, request, listener);
}
public void doUnlock(StageRequest m) {
final LockOperationCompleteCallback callback = (LockOperationCompleteCallback) m.getCallback();
try {
final String clientUuid = (String) m.getArgs()[0];
final Integer pid = (Integer) m.getArgs()[1];
final String fileId = (String) m.getArgs()[2];
OpenFileTableEntry e = oft.getEntry(fileId);
if (e == null) {
callback.parseComplete(null, ErrorUtils.getErrorResponse(ErrorType.INTERNAL_SERVER_ERROR, POSIXErrno.POSIX_ERROR_EIO, "no entry in OFT, programmatic error"));
return;
}
e.unlock(clientUuid, pid);
callback.parseComplete(null, null);
} catch (Exception ex) {
callback.parseComplete(null, ErrorUtils.getInternalServerError(ex));
}
}
@Override
public void run() {
notifyStarted();
// interval to check the OFT
timeToNextOFTclean = OFT_CLEAN_INTERVAL;
lastOFTcheck = TimeSync.getLocalSystemTime();
while (!quit) {
try {
final StageRequest op = q.poll(timeToNextOFTclean, TimeUnit.MILLISECONDS);
checkOpenFileTable(false);
if (op == null) {
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"no request
// -- timer only");
continue;
}
processMethod(op);
} catch (InterruptedException ex) {
break;
} catch (Throwable ex) {
notifyCrashed(ex);
break;
}
}
notifyStopped();
}
/**
* Removes all open files from the {@link OpenFileTable} whose time has expired and triggers for each file
* the internal event {@link EventCloseFile} or {@link EventCreateFileVersion}.
*
* @param force
* If true, force the cleaning and do not respect the cleaning interval.
*/
private void checkOpenFileTable(boolean force) {
final long tPassed = TimeSync.getLocalSystemTime() - lastOFTcheck;
timeToNextOFTclean = timeToNextOFTclean - tPassed;
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"time to next OFT:
// "+timeToNextOFTclean);
if (force || timeToNextOFTclean <= 0) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.proc, this, "OpenFileTable clean");
long currentTime = TimeSync.getLocalSystemTime();
// do OFT clean
List<OpenFileTable.OpenFileTableEntry> closedFiles = oft.clean(currentTime);
// Logging.logMessage(Logging.LEVEL_DEBUG,this,"closing
// "+closedFiles.size()+" files");
for (OpenFileTable.OpenFileTableEntry entry : closedFiles) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this,
"send internal close event for %s, deleteOnClose=%b", entry.getFileId(), entry
.isDeleteOnClose());
LRUCache<String, Capability> cachedCaps = capCache.remove(entry.getFileId());
// send close event
OSDOperation closeEvent = master.getInternalEvent(EventCloseFile.class);
closeEvent.startInternalEvent(new Object[] { entry.getFileId(), entry.isDeleteOnClose(),
metadataCache.getFileInfo(entry.getFileId()), entry.getCowPolicy(), cachedCaps });
}
// check if written files need to be closed; if no files were closed
// completely, generate close events w/o discarding the open state
List<OpenFileTable.OpenFileTableEntry> closedWrittenFiles = oft.cleanWritten(currentTime);
if (closedFiles.size() == 0) {
for (OpenFileTable.OpenFileTableEntry entry : closedWrittenFiles) {
OSDOperation createVersionEvent = master.getInternalEvent(EventCreateFileVersion.class);
createVersionEvent.startInternalEvent(new Object[] { entry.getFileId(),
metadataCache.getFileInfo(entry.getFileId()) });
}
}
timeToNextOFTclean = OFT_CLEAN_INTERVAL;
}
lastOFTcheck = TimeSync.getLocalSystemTime();
}
@Override
protected void processMethod(StageRequest m) {
final int requestedMethod = m.getStageMethod();
switch (requestedMethod) {
case STAGEOP_PARSE_AUTH_OFTOPEN:
doPrepareRequest(m);
break;
case STAGEOP_OFT_DELETE:
doCheckDeleteOnClose(m);
break;
case STAGEOP_ACQUIRE_LOCK:
doAcquireLock(m);
break;
case STAGEOP_CHECK_LOCK:
doCheckLock(m);
break;
case STAGEOP_UNLOCK:
doUnlock(m);
break;
case STAGEOP_PING_FILE:
doPingFile(m);
break;
case STAGEOP_INSTALL_XLOC:
doInstallXLocSet(m);
break;
case STAGEOP_INVALIDATE_XLOC:
doInvalidateXLocSet(m);
break;
case STAGEOP_UPDATE_XLOC:
doUpdateXLocSetFromFlease(m);
break;
default:
Logging.logMessage(Logging.LEVEL_ERROR, this, "unknown stageop called: %d", requestedMethod);
break;
}
}
private boolean parseRequest(OSDRequest rq) {
RPCHeader hdr = rq.getRpcRequest().getHeader();
if (hdr.getMessageType() != MessageType.RPC_REQUEST) {
rq.sendError(ErrorType.GARBAGE_ARGS, POSIXErrno.POSIX_ERROR_EIO, "expected RPC request message type but got "+hdr.getMessageType());
return false;
}
RPCHeader.RequestHeader rqHdr = hdr.getRequestHeader();
if (rqHdr.getInterfaceId() != OSDServiceConstants.INTERFACE_ID) {
rq.sendError(ErrorType.INVALID_INTERFACE_ID, POSIXErrno.POSIX_ERROR_EIO, "invalid interface id. Maybe wrong service address/port configured?");
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"invalid version requested (requested=%d avail=%d)", rqHdr.getInterfaceId(),
OSDServiceConstants.INTERFACE_ID);
}
return false;
}
// everything ok, find the right operation
OSDOperation op = master.getOperation(rqHdr.getProcId());
if (op == null) {
rq.sendError(ErrorType.INVALID_PROC_ID, POSIXErrno.POSIX_ERROR_EINVAL, "requested operation is not available on this OSD (proc # "
+ rqHdr.getProcId() + ")");
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"requested operation is not available on this OSD (proc #%d)", rqHdr.getProcId());
}
return false;
}
rq.setOperation(op);
try {
final Message rqPrototype = OSDServiceConstants.getRequestMessage(rqHdr.getProcId());
if (rqPrototype == null) {
rq.setRequestArgs(null);
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request with empty message");
} else {
if (rq.getRPCRequest().getMessage() != null) {
rq.setRequestArgs(rqPrototype.newBuilderForType().mergeFrom(new ReusableBufferInputStream(rq.getRPCRequest().getMessage())).build());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request of type %s",
rq.getRequestArgs().getClass().getName());
}
} else {
rq.setRequestArgs(rqPrototype.getDefaultInstanceForType());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "received request of type %s (empty message)",
rq.getRequestArgs().getClass().getName());
}
}
}
ErrorResponse err = op.parseRPCMessage(rq);
if (err != null) {
rq.getRpcRequest().sendError(err);
return false;
}
} catch (Throwable ex) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.proc, this, OutputUtils
.stackTraceToString(ex));
rq.getRpcRequest().sendError(ErrorUtils.getInternalServerError(ex));
return false;
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "request parsed: %d", rq
.getRequestId());
}
return true;
}
private ErrorResponse processAuthenticate(OSDRequest rq) {
final Capability rqCap = rq.getCapability();
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this, "capability: %s", rqCap.getXCap().toString().replace('\n', '/'));
}
// check if the capability has valid arguments
if (rqCap.getFileId().length() == 0) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL, "invalid capability. file_id must not be empty");
}
if (rqCap.getEpochNo() < 0) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL, "invalid capability. epoch must not be < 0");
}
if (ignoreCaps)
return null;
// check if the capability is valid
boolean isValid = false;
// look in capCache
LRUCache<String, Capability> cachedCaps = capCache.get(rqCap.getFileId());
if (cachedCaps != null) {
final Capability cap = cachedCaps.get(rqCap.getSignature());
if (cap != null) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this, "using cached cap: %s %s", cap.getFileId(),
cap.getSignature());
}
isValid = !cap.hasExpired();
}
}
if (!isValid) {
isValid = rqCap.isValid();
if (isValid) {
// add to cache
if (cachedCaps == null) {
cachedCaps = new LRUCache<String, Capability>(MAX_CAP_CACHE);
capCache.put(rqCap.getFileId(), cachedCaps);
}
cachedCaps.put(rqCap.getSignature(), rqCap);
}
}
// depending on the result the event listener is sent
if (!isValid) {
if (rqCap.hasExpired())
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (timed out)");
if (!rqCap.hasValidSignature())
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (invalid signature)");
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability is not valid (unknown cause)");
}
// check if the capability was issued for the requested file
if (!rqCap.getFileId().equals(rq.getFileId())) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES, "capability was issued for another file than the one requested");
}
// check if the capability provides sufficient access rights for
// requested operation
if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_READ) {
if ((rqCap.getAccessMode() & (SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY.getNumber())) != 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow read access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_WRITE) {
if ((rqCap.getAccessMode() & (SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_CREAT.getNumber()
| SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_WRONLY.getNumber() | SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_RDWR
.getNumber())) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow write access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_TRUNCATE) {
if ((rqCap.getAccessMode() & SYSTEM_V_FCNTL.SYSTEM_V_FCNTL_H_O_TRUNC.getNumber()) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow truncate access to file " + rqCap.getFileId());
} else if (rq.getOperation().getProcedureId() == OSDServiceConstants.PROC_ID_UNLINK) {
// TODO: replace numeric flag with constant
if ((rqCap.getAccessMode() & 010000000) == 0)
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EACCES,
"capability does not allow delete access to file " + rqCap.getFileId());
}
// TODO(jdillmann): check rights for invalidate, install, and internal fetch invalidated
return null;
}
private ErrorResponse processValidateView(OSDRequest request) {
String fileId = request.getFileId();
if (fileId == null || fileId.length() == 0) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL,
"invalid view. file_id must not be empty");
}
XLocations xloc = request.getLocationList();
if (xloc == null) {
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EINVAL,
"invalid view. xlocset must not be empty");
}
XLocSetVersionState state;
try {
// TODO(jdillmann): Cache the VersionState
state = layout.getXLocSetVersionState(fileId);
} catch (IOException e) {
// TODO(jdillmann): do something with the error
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO,
"invalid view. local version could not be read");
}
XLocations locset = request.getLocationList();
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,
"operation: %s, local version: %s, request version: %s, destination: %s", request.getOperation()
.getClass().getSimpleName(), state.getVersion(), locset.getVersion(), master.getConfig()
.getPort());
}
if (state.getVersion() == locset.getVersion() && !state.getInvalidated()) {
return null;
} else if (locset.getVersion() > state.getVersion()) {
XLocSetVersionState newstate = state.toBuilder()
.setInvalidated(false)
.setVersion(locset.getVersion())
.build();
try {
// persist the view
layout.setXLocSetVersionState(fileId, newstate);
// inform flease about the new view
if (!locset.getReplicaUpdatePolicy().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY)) {
ASCIIString cellId = ReplicaUpdatePolicy.fileToCellId(fileId);
// TODO(jdillmann): think about using a callback which will be called when flease got the message
master.getRWReplicationStage().setFleaseView(fileId, cellId, newstate);
}
} catch (IOException e) {
// TODO(jdillmann): do something with the error
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO,
"invalid view. local version could not be written");
}
return null;
}
return ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EAGAIN, "view is not valid");
}
/**
* Process a viewIdChangeEvent from flease and update the persistent version/state
*/
public void updateXLocSetFromFlease(ASCIIString cellId, int version) {
enqueueOperation(STAGEOP_UPDATE_XLOC, new Object[] { cellId, version }, null, null);
}
private void doUpdateXLocSetFromFlease(StageRequest m) {
final ASCIIString cellId = (ASCIIString) m.getArgs()[0];
final int version = (Integer) m.getArgs()[1];
final String fileId = ReplicaUpdatePolicy.cellToFileId(cellId);
XLocSetVersionState state;
try {
// TODO(jdillmann): Cache the VersionState
state = layout.getXLocSetVersionState(fileId);
} catch (IOException e) {
// TODO(jdillmann): do something with the error or at least log it
Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,
"VersionState could not be read for fileId: %s", fileId);
return;
}
if (state.getVersion() < version || (state.getVersion() == version && state.getInvalidated())) {
state = state.toBuilder().setInvalidated(false).setVersion(version).build();
try {
// persist the version
layout.setXLocSetVersionState(fileId, state);
// and pass it back to flease
master.getRWReplicationStage().setFleaseView(fileId, cellId, state);
} catch (IOException e) {
// TODO(jdillmann): do something with the error or at least log it
Logging.logMessage(Logging.LEVEL_ERROR, Category.replication, this,
"VersionState could not be written for fileId: %s", fileId);
return;
}
}
// If the local version is greater then the one flease got from it responses, the other replicas have
// to update their version. There exists no path to decrement the version if it has been seen once.
return;
}
/**
* Invalidate the current XLocSet. The replica will not respond to read/write/truncate or flease
* operations until a new XLocSet is installed.
*/
public void invalidateXLocSet(OSDRequest request, final InvalidateXLocSetCallback listener) {
enqueueOperation(STAGEOP_INVALIDATE_XLOC, new Object[] {}, request, listener);
}
private void doInvalidateXLocSet(StageRequest m) {
final OSDRequest request = m.getRequest();
final String fileId = request.getFileId();
final InvalidateXLocSetCallback callback = (InvalidateXLocSetCallback) m.getCallback();
XLocSetVersionState state;
try {
state = layout.getXLocSetVersionState(fileId).toBuilder().setInvalidated(true).build();
layout.setXLocSetVersionState(fileId, state);
if (request.getLocationList().getReplicaUpdatePolicy().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY)) {
callback.invalidateComplete(true, null);
} else {
ASCIIString cellId = ReplicaUpdatePolicy.fileToCellId(fileId);
master.getRWReplicationStage().invalidateFleaseView(fileId, cellId, callback);
}
} catch (IOException e) {
// TODO(jdillmann): do something with the exception
ErrorResponse error = ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO,
"invalid view. local version could not be written");
callback.invalidateComplete(false, error);
}
}
public static interface InvalidateXLocSetCallback {
public void invalidateComplete(boolean isPrimary, ErrorResponse error);
}
/**
* Install a new XLocSet and release the replica from the invalidated state.
*/
public void installXLocSet(OSDRequest request, InstallXLocSetCallback listener) {
enqueueOperation(STAGEOP_INSTALL_XLOC, new Object[] {}, request, listener);
}
private void doInstallXLocSet(StageRequest m) {
final OSDRequest request = m.getRequest();
final String fileId = request.getFileId();
final InstallXLocSetCallback callback = (InstallXLocSetCallback) m.getCallback();
XLocSetVersionState state = XLocSetVersionState.newBuilder()
.setInvalidated(false)
.setVersion(request.getLocationList().getVersion())
.build();
try {
layout.setXLocSetVersionState(fileId, state);
if (request.getLocationList().getReplicaUpdatePolicy().equals(ReplicaUpdatePolicies.REPL_UPDATE_PC_RONLY)) {
callback.installComplete(fileId, state.getVersion(), null);
} else {
ASCIIString cellId = ReplicaUpdatePolicy.fileToCellId(fileId);
master.getRWReplicationStage().setFleaseView(fileId, cellId, state, callback);
}
} catch (IOException e) {
// TODO(jdillmann): do something with the exception
ErrorResponse error = ErrorUtils.getErrorResponse(ErrorType.ERRNO, POSIXErrno.POSIX_ERROR_EIO,
"invalid view. local version could not be written");
callback.installComplete(fileId, -1, error);
}
}
public static interface InstallXLocSetCallback {
public void installComplete(String fileId, int version, ErrorResponse error);
}
public int getNumOpenFiles() {
return oft.getNumOpenFiles();
}
public long getNumRequests() {
return numRequests;
}
}
| servers: views: Fix small bug in the handling of ViewUpdates from flease.
| java/servers/src/org/xtreemfs/osd/stages/PreprocStage.java | servers: views: Fix small bug in the handling of ViewUpdates from flease. | <ide><path>ava/servers/src/org/xtreemfs/osd/stages/PreprocStage.java
<ide> return;
<ide> }
<ide>
<del>
<del> if (state.getVersion() < version || (state.getVersion() == version && state.getInvalidated())) {
<add> // If a response from a newer View is encountered, we have to install it and leave the invalidated state.
<add> if (state.getVersion() < version) {
<ide> state = state.toBuilder().setInvalidated(false).setVersion(version).build();
<ide> try {
<ide> // persist the version |
|
Java | lgpl-2.1 | 3a94c3c2f38b8495d31d4bde60fd83593a5144ca | 0 | mediaworx/opencms-core,serrapos/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,victos/opencms-core,MenZil/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,gallardo/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,victos/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,victos/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,MenZil/opencms-core,MenZil/opencms-core,victos/opencms-core,serrapos/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,serrapos/opencms-core,gallardo/opencms-core,serrapos/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/jsp/CmsJspTagContainer.java,v $
* Date : $Date: 2010/01/11 08:03:03 $
* Version: $Revision: 1.11 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2009 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.jsp;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.history.CmsHistoryResourceHandler;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.flex.CmsFlexController;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalStateException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.xml.containerpage.CmsADEManager;
import org.opencms.xml.containerpage.CmsContainerBean;
import org.opencms.xml.containerpage.CmsContainerElementBean;
import org.opencms.xml.containerpage.CmsContainerPageBean;
import org.opencms.xml.containerpage.CmsSubContainerBean;
import org.opencms.xml.containerpage.CmsXmlContainerPage;
import org.opencms.xml.containerpage.CmsXmlContainerPageFactory;
import org.opencms.xml.containerpage.CmsXmlSubContainer;
import org.opencms.xml.containerpage.CmsXmlSubContainerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.Locale;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.logging.Log;
/**
* Provides access to the page container elements.<p>
*
* @author Michael Moossen
*
* @version $Revision: 1.11 $
*
* @since 7.6
*/
public class CmsJspTagContainer extends TagSupport {
/** The create no tag attribute value constant. */
private static final String CREATE_NO_TAG = "none";
/** The default tag name constant. */
private static final String DEFAULT_TAG_NAME = "div";
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = -1228397990961282556L;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsJspTagContainer.class);
/** The maxElements attribute value. */
private String m_maxElements;
/** The name attribute value. */
private String m_name;
/** The type attribute value. */
private String m_type;
/** The tag attribute value. */
private String m_tag;
/** The class attribute value. */
private String m_tagClass;
/**
* Returns the tag attribute.<p>
*
* @return the tag attribute
*/
public String getTag() {
return m_tag;
}
/**
* Sets the tag attribute.<p>
*
* @param tag the createTag to set
*/
public void setTag(String tag) {
m_tag = tag;
}
/**
* Returns the tag class attribute.<p>
*
* @return the tag class attribute
*/
public String getTagClass() {
return m_tagClass;
}
/**
* Sets the tag class attribute.<p>
*
* @param tagClass the tag class attribute to set
*/
public void setTagClass(String tagClass) {
m_tagClass = tagClass;
}
/**
* Internal action method.<p>
*
* @param pageContext the current JSP page context
* @param containerName the name of the container
* @param containerType the type of the container
* @param containerMaxElements the maximal number of elements in the container
* @param tag the tag to create
* @param tagClass the tag class attribute
* @param req the current request
* @param res the current response
*
* @throws CmsException if something goes wrong
* @throws JspException if there is some problem calling the jsp formatter
*/
public static void containerTagAction(
PageContext pageContext,
String containerName,
String containerType,
String containerMaxElements,
String tag,
String tagClass,
ServletRequest req,
ServletResponse res) throws CmsException, JspException {
CmsFlexController controller = CmsFlexController.getController(req);
CmsObject cms = controller.getCmsObject();
boolean actAsTemplate = false;
// get the container page itself, checking the history first
CmsResource containerPage = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req);
if (containerPage == null) {
containerPage = cms.readResource(cms.getRequestContext().getUri());
}
if (!CmsResourceTypeXmlContainerPage.isContainerPage(containerPage)) {
// container page is used as template
String cntPagePath = cms.readPropertyObject(
containerPage,
CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS,
true).getValue("");
try {
containerPage = cms.readResource(cntPagePath);
} catch (CmsException e) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_CONTAINER_PAGE_NOT_FOUND_3,
cms.getRequestContext().getUri(),
CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS,
cntPagePath), e);
}
if (!CmsResourceTypeXmlContainerPage.isContainerPage(containerPage)) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_CONTAINER_PAGE_NOT_FOUND_3,
cms.getRequestContext().getUri(),
CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS,
cntPagePath));
}
actAsTemplate = true;
} else if (req.getParameter(CmsContainerPageBean.TEMPLATE_ELEMENT_PARAMETER) != null) {
actAsTemplate = true;
}
CmsXmlContainerPage xmlCntPage = CmsXmlContainerPageFactory.unmarshal(cms, containerPage, req);
CmsContainerPageBean cntPage = xmlCntPage.getCntPage(cms, cms.getRequestContext().getLocale());
Locale locale = cntPage.getLocale();
// get the container
CmsContainerBean container = cntPage.getContainers().get(containerName);
if (container == null) {
// container not found
LOG.error(Messages.get().container(
Messages.LOG_CONTAINER_NOT_FOUND_3,
cms.getSitePath(containerPage),
locale,
containerName).key());
return;
}
// validate the type
if (!containerType.equals(container.getType())) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.LOG_WRONG_CONTAINER_TYPE_4,
new Object[] {cms.getSitePath(containerPage), locale, containerName, containerType}));
}
// get the maximal number of elements
int maxElements = -1;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(containerMaxElements)) {
try {
maxElements = Integer.parseInt(containerMaxElements);
} catch (NumberFormatException e) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.LOG_WRONG_CONTAINER_MAXELEMENTS_4,
new Object[] {cms.getSitePath(containerPage), locale, containerName, containerMaxElements}), e);
}
// actualize the cache
container.setMaxElements(maxElements);
} else {
if (LOG.isWarnEnabled()) {
LOG.warn(Messages.get().container(
Messages.LOG_MAXELEMENTS_NOT_SET_3,
new Object[] {containerName, locale, cms.getSitePath(containerPage)}));
}
}
// get the actual number of elements to render
int renderElems = container.getElements().size();
if ((maxElements > 0) && (renderElems > maxElements)) {
renderElems = maxElements;
}
// create tag for container if necessary
boolean createTag = false;
String tagName = CmsStringUtil.isEmptyOrWhitespaceOnly(tag) ? DEFAULT_TAG_NAME : tag;
if (!CREATE_NO_TAG.equals(tag)) {
createTag = true;
try {
pageContext.getOut().print(getTagOpen(tagName, containerName, tagClass));
} catch (IOException t) {
throw new JspException(t);
}
}
if (actAsTemplate) {
if (!cntPage.getTypes().contains(CmsContainerPageBean.TYPE_TEMPLATE)) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_CONTAINER_PAGE_NO_TYPE_3,
cms.getRequestContext().getUri(),
cms.getSitePath(containerPage),
CmsContainerPageBean.TYPE_TEMPLATE));
}
if (containerType.equals(CmsContainerPageBean.TYPE_TEMPLATE)) {
// render template element
renderElems--;
CmsResource resUri;
if (req.getParameter(CmsContainerPageBean.TEMPLATE_ELEMENT_PARAMETER) != null) {
CmsUUID id = new CmsUUID(req.getParameter(CmsContainerPageBean.TEMPLATE_ELEMENT_PARAMETER));
resUri = cms.readResource(id);
} else {
// check the history first
resUri = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req);
if (resUri == null) {
resUri = cms.readResource(cms.getRequestContext().getUri());
}
}
String elementFormatter = OpenCms.getADEManager().getXmlContentFormatters(cms, resUri).get(
containerType);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(elementFormatter)) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_XSD_NO_TEMPLATE_FORMATTER_3,
cms.getRequestContext().getUri(),
OpenCms.getResourceManager().getResourceType(resUri).getTypeName(),
CmsContainerPageBean.TYPE_TEMPLATE));
}
// execute the formatter jsp for the given element uri
CmsContainerElementBean element = new CmsContainerElementBean(
resUri.getStructureId(),
cms.readResource(elementFormatter).getStructureId(),
null); // when used as template element there are no properties
CmsJspTagInclude.includeTagAction(
pageContext,
elementFormatter,
null,
false,
null,
Collections.singletonMap(CmsADEManager.ATTR_CURRENT_ELEMENT, (Object)element),
req,
res);
}
}
// iterate the elements
for (CmsContainerElementBean element : container.getElements()) {
if (renderElems < 1) {
break;
}
renderElems--;
CmsResource resUri = cms.readResource(element.getElementId());
if (resUri.getTypeId() == CmsResourceTypeXmlContainerPage.SUB_CONTAINER_TYPE_ID) {
CmsXmlSubContainer xmlSubContainer = CmsXmlSubContainerFactory.unmarshal(cms, resUri, req);
CmsSubContainerBean subContainer = xmlSubContainer.getSubContainer(
cms,
cms.getRequestContext().getLocale());
if (!subContainer.getTypes().contains(containerType)) {
//TODO: change message
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_XSD_NO_TEMPLATE_FORMATTER_3,
resUri.getRootPath(),
OpenCms.getResourceManager().getResourceType(resUri).getTypeName(),
containerType));
}
for (CmsContainerElementBean subelement : subContainer.getElements()) {
CmsResource subelementRes = cms.readResource(subelement.getElementId());
String subelementUri = cms.getSitePath(subelementRes);
//String subelementFormatter = cms.getSitePath(subelement.getFormatter());
String subelementFormatter = OpenCms.getADEManager().getXmlContentFormatters(cms, subelementRes).get(
containerType);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(subelementFormatter) && LOG.isErrorEnabled()) {
// skip this element, it has no formatter for this container type defined
LOG.error(new CmsIllegalStateException(Messages.get().container(
Messages.ERR_XSD_NO_TEMPLATE_FORMATTER_3,
subelementUri,
OpenCms.getResourceManager().getResourceType(subelementRes).getTypeName(),
containerType)));
continue;
}
// execute the formatter jsp for the given element uri
CmsJspTagInclude.includeTagAction(
pageContext,
subelementFormatter,
null,
false,
null,
Collections.singletonMap(CmsADEManager.ATTR_CURRENT_ELEMENT, (Object)subelement),
req,
res);
}
} else {
String elementFormatter = cms.getSitePath(cms.readResource(element.getFormatterId()));
// execute the formatter jsp for the given element uri
CmsJspTagInclude.includeTagAction(
pageContext,
elementFormatter,
null,
false,
null,
Collections.singletonMap(CmsADEManager.ATTR_CURRENT_ELEMENT, (Object)element),
req,
res);
}
}
// close tag for container
if (createTag) {
try {
pageContext.getOut().print(getTagClose(tagName));
} catch (IOException t) {
throw new JspException(t);
}
}
}
/**
* @return SKIP_BODY
* @throws JspException in case something goes wrong
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
@Override
public int doStartTag() throws JspException {
ServletRequest req = pageContext.getRequest();
ServletResponse res = pageContext.getResponse();
// This will always be true if the page is called through OpenCms
if (CmsFlexController.isCmsRequest(req)) {
try {
containerTagAction(
pageContext,
getName(),
getType(),
getMaxElements(),
getTag(),
getTagClass(),
req,
res);
} catch (Exception ex) {
if (LOG.isErrorEnabled()) {
LOG.error(Messages.get().getBundle().key(Messages.ERR_PROCESS_TAG_1, "container"), ex);
}
throw new javax.servlet.jsp.JspException(ex);
}
}
return SKIP_BODY;
}
/**
* Returns the maxElements attribute value.<p>
*
* @return the maxElements attribute value
*/
public String getMaxElements() {
return m_maxElements;
}
/**
* Returns the name attribute value.<p>
*
* @return String the name attribute value
*/
public String getName() {
return m_name;
}
/**
* Returns the type attribute value.<p>
*
* @return the type attribute value
*/
public String getType() {
return m_type;
}
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
@Override
public void release() {
super.release();
m_type = null;
m_name = null;
m_maxElements = null;
}
/**
* Sets the maxElements attribute value.<p>
*
* @param maxElements the maxElements value to set
*/
public void setMaxElements(String maxElements) {
m_maxElements = maxElements;
}
/**
* Sets the name attribute value.<p>
*
* @param name the name value to set
*/
public void setName(String name) {
m_name = name;
}
/**
* Sets the type attribute value.<p>
*
* @param type the type value to set
*/
public void setType(String type) {
m_type = type;
}
/**
* Creates the opening tag for the container assigning the appropriate id and class attributes.<p>
*
* @param tagName the tag name
* @param containerName the container name used as id attribute value
* @param tagClass the tag class attribute value
* @return the opening tag
*/
private static String getTagOpen(String tagName, String containerName, String tagClass) {
String classAttr = CmsStringUtil.isEmptyOrWhitespaceOnly(tagClass) ? "" : "class=\"" + tagClass + "\" ";
return "<" + tagName + " id=\"" + containerName + "\" " + classAttr + ">";
}
/**
* Creates the closing tag for the container.<p>
*
* @param tagName the tag name
* @return the closing tag
*/
private static String getTagClose(String tagName) {
return "</" + tagName + ">";
}
}
| src/org/opencms/jsp/CmsJspTagContainer.java | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/jsp/CmsJspTagContainer.java,v $
* Date : $Date: 2009/12/17 07:59:30 $
* Version: $Revision: 1.10 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2009 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.jsp;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.history.CmsHistoryResourceHandler;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.flex.CmsFlexController;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalStateException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import org.opencms.xml.containerpage.CmsADEManager;
import org.opencms.xml.containerpage.CmsContainerBean;
import org.opencms.xml.containerpage.CmsContainerElementBean;
import org.opencms.xml.containerpage.CmsContainerPageBean;
import org.opencms.xml.containerpage.CmsSubContainerBean;
import org.opencms.xml.containerpage.CmsXmlContainerPage;
import org.opencms.xml.containerpage.CmsXmlContainerPageFactory;
import org.opencms.xml.containerpage.CmsXmlSubContainer;
import org.opencms.xml.containerpage.CmsXmlSubContainerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.Locale;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.logging.Log;
/**
* Provides access to the page container elements.<p>
*
* @author Michael Moossen
*
* @version $Revision: 1.10 $
*
* @since 7.6
*/
public class CmsJspTagContainer extends TagSupport {
/** The create no tag attribute value constant. */
private static final String CREATE_NO_TAG = "none";
/** The default tag name constant. */
private static final String DEFAULT_TAG_NAME = "div";
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = -1228397990961282556L;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsJspTagContainer.class);
/** The maxElements attribute value. */
private String m_maxElements;
/** The name attribute value. */
private String m_name;
/** The type attribute value. */
private String m_type;
/** The tag attribute value. */
private String m_tag;
/** The class attribute value. */
private String m_tagClass;
/**
* Returns the tag attribute.<p>
*
* @return the tag attribute
*/
public String getTag() {
return m_tag;
}
/**
* Sets the tag attribute.<p>
*
* @param tag the createTag to set
*/
public void setTag(String tag) {
m_tag = tag;
}
/**
* Returns the tag class attribute.<p>
*
* @return the tag class attribute
*/
public String getTagClass() {
return m_tagClass;
}
/**
* Sets the tag class attribute.<p>
*
* @param tagClass the tag class attribute to set
*/
public void setTagClass(String tagClass) {
m_tagClass = tagClass;
}
/**
* Internal action method.<p>
*
* @param pageContext the current JSP page context
* @param containerName the name of the container
* @param containerType the type of the container
* @param containerMaxElements the maximal number of elements in the container
* @param tag the tag to create
* @param tagClass the tag class attribute
* @param req the current request
* @param res the current response
*
* @throws CmsException if something goes wrong
* @throws JspException if there is some problem calling the jsp formatter
*/
public static void containerTagAction(
PageContext pageContext,
String containerName,
String containerType,
String containerMaxElements,
String tag,
String tagClass,
ServletRequest req,
ServletResponse res) throws CmsException, JspException {
CmsFlexController controller = CmsFlexController.getController(req);
CmsObject cms = controller.getCmsObject();
boolean actAsTemplate = false;
// get the container page itself, checking the history first
CmsResource containerPage = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req);
if (containerPage == null) {
containerPage = cms.readResource(cms.getRequestContext().getUri());
}
if (!CmsResourceTypeXmlContainerPage.isContainerPage(containerPage)) {
// container page is used as template
String cntPagePath = cms.readPropertyObject(
containerPage,
CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS,
true).getValue("");
try {
containerPage = cms.readResource(cntPagePath);
} catch (CmsException e) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_CONTAINER_PAGE_NOT_FOUND_3,
cms.getRequestContext().getUri(),
CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS,
cntPagePath), e);
}
if (!CmsResourceTypeXmlContainerPage.isContainerPage(containerPage)) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_CONTAINER_PAGE_NOT_FOUND_3,
cms.getRequestContext().getUri(),
CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS,
cntPagePath));
}
actAsTemplate = true;
} else if (req.getParameter(CmsContainerPageBean.TEMPLATE_ELEMENT_PARAMETER) != null) {
actAsTemplate = true;
}
CmsXmlContainerPage xmlCntPage = CmsXmlContainerPageFactory.unmarshal(cms, containerPage, req);
CmsContainerPageBean cntPage = xmlCntPage.getCntPage(cms, cms.getRequestContext().getLocale());
Locale locale = cntPage.getLocale();
// get the container
if (!cntPage.getContainers().containsKey(containerName)) {
if (!cms.getRequestContext().currentProject().isOnlineProject()) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.LOG_CONTAINER_NOT_FOUND_3,
cms.getSitePath(containerPage),
locale,
containerName));
} else {
// be silent online
LOG.error(Messages.get().container(
Messages.LOG_CONTAINER_NOT_FOUND_3,
cms.getSitePath(containerPage),
locale,
containerName).key());
return;
}
}
CmsContainerBean container = cntPage.getContainers().get(containerName);
// validate the type
if (!containerType.equals(container.getType())) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.LOG_WRONG_CONTAINER_TYPE_4,
new Object[] {cms.getSitePath(containerPage), locale, containerName, containerType}));
}
// get the maximal number of elements
int maxElements = -1;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(containerMaxElements)) {
try {
maxElements = Integer.parseInt(containerMaxElements);
} catch (NumberFormatException e) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.LOG_WRONG_CONTAINER_MAXELEMENTS_4,
new Object[] {cms.getSitePath(containerPage), locale, containerName, containerMaxElements}), e);
}
// actualize the cache
container.setMaxElements(maxElements);
} else {
if (LOG.isWarnEnabled()) {
LOG.warn(Messages.get().container(
Messages.LOG_MAXELEMENTS_NOT_SET_3,
new Object[] {containerName, locale, cms.getSitePath(containerPage)}));
}
}
// get the actual number of elements to render
int renderElems = container.getElements().size();
if ((maxElements > 0) && (renderElems > maxElements)) {
renderElems = maxElements;
}
// create tag for container if necessary
boolean createTag = false;
String tagName = CmsStringUtil.isEmptyOrWhitespaceOnly(tag) ? DEFAULT_TAG_NAME : tag;
if (!CREATE_NO_TAG.equals(tag)) {
createTag = true;
try {
pageContext.getOut().print(getTagOpen(tagName, containerName, tagClass));
} catch (IOException t) {
throw new JspException(t);
}
}
if (actAsTemplate) {
if (!cntPage.getTypes().contains(CmsContainerPageBean.TYPE_TEMPLATE)) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_CONTAINER_PAGE_NO_TYPE_3,
cms.getRequestContext().getUri(),
cms.getSitePath(containerPage),
CmsContainerPageBean.TYPE_TEMPLATE));
}
if (containerType.equals(CmsContainerPageBean.TYPE_TEMPLATE)) {
// render template element
renderElems--;
CmsResource resUri;
if (req.getParameter(CmsContainerPageBean.TEMPLATE_ELEMENT_PARAMETER) != null) {
CmsUUID id = new CmsUUID(req.getParameter(CmsContainerPageBean.TEMPLATE_ELEMENT_PARAMETER));
resUri = cms.readResource(id);
} else {
// check the history first
resUri = (CmsResource)CmsHistoryResourceHandler.getHistoryResource(req);
if (resUri == null) {
resUri = cms.readResource(cms.getRequestContext().getUri());
}
}
String elementFormatter = OpenCms.getADEManager().getXmlContentFormatters(cms, resUri).get(
containerType);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(elementFormatter)) {
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_XSD_NO_TEMPLATE_FORMATTER_3,
cms.getRequestContext().getUri(),
OpenCms.getResourceManager().getResourceType(resUri).getTypeName(),
CmsContainerPageBean.TYPE_TEMPLATE));
}
// execute the formatter jsp for the given element uri
CmsContainerElementBean element = new CmsContainerElementBean(
resUri.getStructureId(),
cms.readResource(elementFormatter).getStructureId(),
null); // when used as template element there are no properties
CmsJspTagInclude.includeTagAction(
pageContext,
elementFormatter,
null,
false,
null,
Collections.singletonMap(CmsADEManager.ATTR_CURRENT_ELEMENT, (Object)element),
req,
res);
}
}
// iterate the elements
for (CmsContainerElementBean element : container.getElements()) {
if (renderElems < 1) {
break;
}
renderElems--;
CmsResource resUri = cms.readResource(element.getElementId());
if (resUri.getTypeId() == CmsResourceTypeXmlContainerPage.SUB_CONTAINER_TYPE_ID) {
CmsXmlSubContainer xmlSubContainer = CmsXmlSubContainerFactory.unmarshal(cms, resUri, req);
CmsSubContainerBean subContainer = xmlSubContainer.getSubContainer(
cms,
cms.getRequestContext().getLocale());
if (!subContainer.getTypes().contains(containerType)) {
//TODO: change message
throw new CmsIllegalStateException(Messages.get().container(
Messages.ERR_XSD_NO_TEMPLATE_FORMATTER_3,
resUri.getRootPath(),
OpenCms.getResourceManager().getResourceType(resUri).getTypeName(),
containerType));
}
for (CmsContainerElementBean subelement : subContainer.getElements()) {
CmsResource subelementRes = cms.readResource(subelement.getElementId());
String subelementUri = cms.getSitePath(subelementRes);
//String subelementFormatter = cms.getSitePath(subelement.getFormatter());
String subelementFormatter = OpenCms.getADEManager().getXmlContentFormatters(cms, subelementRes).get(
containerType);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(subelementFormatter) && LOG.isErrorEnabled()) {
// skip this element, it has no formatter for this container type defined
LOG.error(new CmsIllegalStateException(Messages.get().container(
Messages.ERR_XSD_NO_TEMPLATE_FORMATTER_3,
subelementUri,
OpenCms.getResourceManager().getResourceType(subelementRes).getTypeName(),
containerType)));
continue;
}
// execute the formatter jsp for the given element uri
CmsJspTagInclude.includeTagAction(
pageContext,
subelementFormatter,
null,
false,
null,
Collections.singletonMap(CmsADEManager.ATTR_CURRENT_ELEMENT, (Object)subelement),
req,
res);
}
} else {
String elementFormatter = cms.getSitePath(cms.readResource(element.getFormatterId()));
// execute the formatter jsp for the given element uri
CmsJspTagInclude.includeTagAction(
pageContext,
elementFormatter,
null,
false,
null,
Collections.singletonMap(CmsADEManager.ATTR_CURRENT_ELEMENT, (Object)element),
req,
res);
}
}
// close tag for container
if (createTag) {
try {
pageContext.getOut().print(getTagClose(tagName));
} catch (IOException t) {
throw new JspException(t);
}
}
}
/**
* @return SKIP_BODY
* @throws JspException in case something goes wrong
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
@Override
public int doStartTag() throws JspException {
ServletRequest req = pageContext.getRequest();
ServletResponse res = pageContext.getResponse();
// This will always be true if the page is called through OpenCms
if (CmsFlexController.isCmsRequest(req)) {
try {
containerTagAction(
pageContext,
getName(),
getType(),
getMaxElements(),
getTag(),
getTagClass(),
req,
res);
} catch (Exception ex) {
if (LOG.isErrorEnabled()) {
LOG.error(Messages.get().getBundle().key(Messages.ERR_PROCESS_TAG_1, "container"), ex);
}
throw new javax.servlet.jsp.JspException(ex);
}
}
return SKIP_BODY;
}
/**
* Returns the maxElements attribute value.<p>
*
* @return the maxElements attribute value
*/
public String getMaxElements() {
return m_maxElements;
}
/**
* Returns the name attribute value.<p>
*
* @return String the name attribute value
*/
public String getName() {
return m_name;
}
/**
* Returns the type attribute value.<p>
*
* @return the type attribute value
*/
public String getType() {
return m_type;
}
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
@Override
public void release() {
super.release();
m_type = null;
m_name = null;
m_maxElements = null;
}
/**
* Sets the maxElements attribute value.<p>
*
* @param maxElements the maxElements value to set
*/
public void setMaxElements(String maxElements) {
m_maxElements = maxElements;
}
/**
* Sets the name attribute value.<p>
*
* @param name the name value to set
*/
public void setName(String name) {
m_name = name;
}
/**
* Sets the type attribute value.<p>
*
* @param type the type value to set
*/
public void setType(String type) {
m_type = type;
}
/**
* Creates the opening tag for the container assigning the appropriate id and class attributes.<p>
*
* @param tagName the tag name
* @param containerName the container name used as id attribute value
* @param tagClass the tag class attribute value
* @return the opening tag
*/
private static String getTagOpen(String tagName, String containerName, String tagClass) {
String classAttr = CmsStringUtil.isEmptyOrWhitespaceOnly(tagClass) ? "" : "class=\"" + tagClass + "\" ";
return "<" + tagName + " id=\"" + containerName + "\" " + classAttr + ">";
}
/**
* Creates the closing tag for the container.<p>
*
* @param tagName the tag name
* @return the closing tag
*/
private static String getTagClose(String tagName) {
return "</" + tagName + ">";
}
}
| when a container page does not have a container used by the template, just skip it, do not throw an exception
| src/org/opencms/jsp/CmsJspTagContainer.java | when a container page does not have a container used by the template, just skip it, do not throw an exception | <ide><path>rc/org/opencms/jsp/CmsJspTagContainer.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/jsp/CmsJspTagContainer.java,v $
<del> * Date : $Date: 2009/12/17 07:59:30 $
<del> * Version: $Revision: 1.10 $
<add> * Date : $Date: 2010/01/11 08:03:03 $
<add> * Version: $Revision: 1.11 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Management System
<ide> *
<ide> * @author Michael Moossen
<ide> *
<del> * @version $Revision: 1.10 $
<add> * @version $Revision: 1.11 $
<ide> *
<ide> * @since 7.6
<ide> */
<ide> Locale locale = cntPage.getLocale();
<ide>
<ide> // get the container
<del> if (!cntPage.getContainers().containsKey(containerName)) {
<del> if (!cms.getRequestContext().currentProject().isOnlineProject()) {
<del> throw new CmsIllegalStateException(Messages.get().container(
<del> Messages.LOG_CONTAINER_NOT_FOUND_3,
<del> cms.getSitePath(containerPage),
<del> locale,
<del> containerName));
<del> } else {
<del> // be silent online
<del> LOG.error(Messages.get().container(
<del> Messages.LOG_CONTAINER_NOT_FOUND_3,
<del> cms.getSitePath(containerPage),
<del> locale,
<del> containerName).key());
<del> return;
<del> }
<del> }
<ide> CmsContainerBean container = cntPage.getContainers().get(containerName);
<add> if (container == null) {
<add> // container not found
<add> LOG.error(Messages.get().container(
<add> Messages.LOG_CONTAINER_NOT_FOUND_3,
<add> cms.getSitePath(containerPage),
<add> locale,
<add> containerName).key());
<add> return;
<add> }
<ide>
<ide> // validate the type
<ide> if (!containerType.equals(container.getType())) { |
|
JavaScript | mit | 6e0f6a9bda9d9ab6123cf2af1e461f4bdcd202bb | 0 | Vaeb/VaeBot,einsteinK/VaeBot | console.log('\n-STARTING-\n');
// //////////////////////////////////////////////////////////////////////////////////////////////
const Auth = require('./Auth.js');
exports.FileSys = require('fs');
exports.DateFormat = require('dateformat');
exports.Request = require('request');
exports.Urban = require('urban');
const TrelloObj = require('node-trello');
exports.Ytdl = require('ytdl-core');
exports.Path = require('path');
exports.NodeOpus = require('node-opus');
exports.Exec = require('child_process').exec;
const YtInfoObj = require('youtube-node');
exports.Translate = require('google-translate-api');
exports.MySQL = require('mysql');
exports.YtInfo = new YtInfoObj();
exports.TrelloHandler = new TrelloObj(Auth.trelloKey, Auth.trelloToken);
exports.linkGuilds = [
['284746138995785729', '309785618932563968'],
];
exports.dbPass = Auth.dbPass;
// //////////////////////////////////////////////////////////////////////////////////////////////
global.index = module.exports;
global.has = Object.prototype.hasOwnProperty;
global.selfId = '224529399003742210';
global.vaebId = '107593015014486016';
global.Util = require('./Util.js');
global.Data = require('./data/ManageData.js');
global.Trello = require('./core/ManageTrello.js');
global.Mutes = require('./core/ManageMutesNew.js');
global.MutesOld = require('./core/ManageMutes.js'); // Will be replaced with MutesNew upon completion
global.Music = require('./core/ManageMusic.js');
global.Cmds = require('./core/ManageCommands.js');
global.Events = require('./core/ManageEvents.js');
global.Discord = require('discord.js');
exports.YtInfo.setKey(Auth.youtube);
Discord.GuildMember.prototype.getProp = function (p) {
if (this[p] != null) return this[p];
return this.user[p];
};
Discord.User.prototype.getProp = function (p) {
return this[p];
};
global.client = new Discord.Client({
disabledEvents: ['TYPING_START'],
fetchAllMembers: true,
disableEveryone: true,
});
// //////////////////////////////////////////////////////////////////////////////////////////////
exports.dailyMutes = [];
exports.dailyKicks = [];
exports.dailyBans = [];
exports.commandTypes = {
locked: 'vaeb',
staff: 'staff',
public: 'null',
};
const briefHour = 2;
const msToHours = 1 / (1000 * 60 * 60);
const dayMS = 24 / msToHours;
let madeBriefing = false;
global.colAction = 0xF44336; // Log of action, e.g. action from within command
global.colUser = 0x4CAF50; // Log of member change
global.colMessage = 0xFFEB3B; // Log of message change
global.colCommand = 0x2196F3; // Log of command being executed
exports.blockedUsers = {};
exports.blockedWords = [];
exports.runFuncs = [];
exports.warnedImage = {};
// //////////////////////////////////////////////////////////////////////////////////////////////
function setBriefing() {
setTimeout(() => {
const time1 = new Date();
const time2 = new Date();
time2.setHours(briefHour);
time2.setMinutes(0);
time2.setSeconds(0);
time2.setMilliseconds(0);
const t1 = +time1;
const t2 = +time2;
let t3 = t2 - t1;
if (t3 < 0) t3 += dayMS;
const channel = client.channels.get('168744024931434498');
// const guild = channel.guild;
Util.log(`Set daily briefing for ${t3 * msToHours} hours`);
setTimeout(() => {
// const upField = { name: '', value: '', inline: false };
const muteField = { name: 'Mutes', value: 'No mutes today', inline: false };
// var rightField = {name: "", value: ""}
const kickField = { name: 'Kicks', value: 'No kicks today', inline: false };
const banField = { name: 'Bans', value: 'No bans today', inline: false };
const embFields = [muteField, kickField, banField];
const embObj = {
title: 'Daily Briefing',
description: '',
fields: embFields,
footer: { text: '>> More info in #vaebot-log <<' },
thumbnail: { url: './resources/avatar.png' },
color: 0x00E676,
};
if (exports.dailyMutes.length > 0) {
const dataValues = [];
for (let i = 0; i < exports.dailyMutes.length; i++) {
const nowData = exports.dailyMutes[i];
const userId = nowData[0];
// const userName = nowData[1];
const userReason = nowData[2];
// const userTime = nowData[3];
const targMention = `<@${userId}>`;
let reasonStr = '';
if (userReason != null && userReason.trim().length > 0) {
reasonStr = ` : ${userReason}`;
}
dataValues.push(targMention + reasonStr);
}
muteField.value = dataValues.join('\n\n');
}
muteField.value = `\n${muteField.value}\n`;
if (exports.dailyKicks.length > 0) {
const dataValues = [];
for (let i = 0; i < exports.dailyKicks.length; i++) {
const nowData = exports.dailyKicks[i];
const userId = nowData[0];
// const userName = nowData[1];
const userReason = nowData[2];
const targMention = `<@${userId}>`;
let reasonStr = '';
if (userReason != null && userReason.trim().length > 0) {
reasonStr = ` : ${userReason}`;
}
dataValues.push(targMention + reasonStr);
}
kickField.value = dataValues.join('\n\n');
}
kickField.value = `\n${kickField.value}\n`;
if (exports.dailyBans.length > 0) {
const dataValues = [];
for (let i = 0; i < exports.dailyBans.length; i++) {
const nowData = exports.dailyBans[i];
const userId = nowData[0];
// const userName = nowData[1];
const userReason = nowData[2];
const targMention = `<@${userId}>`;
let reasonStr = '';
if (userReason != null && userReason.trim().length > 0) {
reasonStr = ` : ${userReason}`;
}
dataValues.push(targMention + reasonStr);
}
banField.value = dataValues.join('\n\n');
}
banField.value = `\n${banField.value}\n`;
if (exports.dailyMutes.length > 0
|| exports.dailyKicks.length > 0
|| exports.dailyBans.length > 0) {
channel.send(undefined, { embed: embObj })
.catch(error => Util.log(`[E_SendBriefing] ${error}`));
}
exports.dailyMutes = []; // Reset
exports.dailyKicks = [];
exports.dailyBans = [];
setBriefing();
}, t3);
}, 2000); // Let's wait 2 seconds before starting countdown, just in case of floating point errors triggering multiple countdowns
}
exports.globalBan = {
'201740276472086528': true,
'75736018761818112': true,
'123146298504380416': true,
'263372398059847681': true,
'238981466606927873': true, // Lindah
'189687397951209472': true, // xCraySECx / Nico Nico
'154255141317378050': true, // HighDefinition
'157749388964265985': true, // Zetroxer
'280419231181307906': true, // Solarical
'169261309353918464': true, // Slappy826
};
function securityFunc(guild, member, sendRoleParam) {
const guildName = guild.name;
// const guildId = guild.id;
const memberId = member.id;
const memberName = Util.getFullName(member);
let sendRole = sendRoleParam;
if (sendRole == null) sendRole = Util.getRole('SendMessages', guild);
if (has.call(exports.globalBan, memberId)) {
member.kick()
.catch(console.error);
Util.log(`Globally banned user ${memberName} had already joined ${guildName}`);
return;
}
if (sendRole != null) {
const isMuted = Mutes.checkMuted(guild, memberId);
if (isMuted) {
if (Util.hasRole(member, sendRole)) {
member.removeRole(sendRole)
.catch(console.error);
Util.log(`Muted user ${memberName} had already joined ${guildName}`);
}
} else if (!Util.hasRole(member, sendRole)) {
member.addRole(sendRole)
.catch(console.error);
Util.log(`Assigned SendMessages to old member ${memberName}`);
}
}
}
function setupSecurity(guild) {
const sendRole = Util.getRole('SendMessages', guild);
Util.logc('Security1', `Setting up security for ${guild.name} (${guild.members.size} members)`);
guild.members.forEach((member) => {
securityFunc(guild, member, sendRole);
});
}
function setupSecurityVeil() {
const veilGuild = client.guilds.get('284746138995785729');
if (!veilGuild) return Util.log('[ERROR_VP] Veil guild not found!');
const guild = client.guilds.get('309785618932563968');
if (!guild) return Util.log('[ERROR_VP] New Veil guild not found!');
const veilBuyer = veilGuild.roles.find('name', 'Buyer');
if (!veilBuyer) return Util.log('[ERROR_VP] Veil Buyer role not found!');
const newBuyer = guild.roles.find('name', 'Buyer');
if (!newBuyer) return Util.log('[ERROR_VP] New Buyer role not found!');
// const guildId = guild.id;
// const guildName = guild.name;
Util.logc('AutoKick1', `Setting up auto-kick for ${guild.name} (${guild.members.size} members)`);
guild.members.forEach((member) => {
const memberId = member.id;
if (memberId === vaebId || memberId === selfId) return;
const memberName = Util.getFullName(member);
const veilMember = Util.getMemberById(memberId, veilGuild);
if (!veilMember) {
Util.log(`[Auto-Old-Kick 1] User not in Veil: ${memberName}`);
member.kick()
.catch(error => Util.log(`[E_AutoOldKick1] ${memberName} | ${error}`));
return;
}
if (!veilMember.roles.has(veilBuyer.id)) {
Util.log(`[Auto-Old-Kick 2] User does not have Buyer role: ${memberName}`);
member.kick()
.catch(error => Util.log(`[E_AutoOldKick2] ${memberName} | ${error}`));
return;
}
if (!member.roles.has(newBuyer.id)) {
member.addRole(newBuyer)
.catch(error => Util.log(`[E_AutoOldAddRole1] ${memberName} | ${error}`));
Util.log(`Updated old member with Buyer role: ${memberName}`);
}
});
return undefined;
}
const veilGuilds = {
'284746138995785729': true,
'309785618932563968': true,
};
exports.secure = async function () {
Util.log('> Securing guilds...');
let securityNum = 0;
const veilGuildsNum = Object.keys(veilGuilds).length;
await Promise.all(client.guilds.map(async (guild) => {
const newGuild = await guild.fetchMembers();
if (newGuild == null) {
Util.log(newGuild);
Util.log('Found null guild');
return;
}
if (has.call(veilGuilds, newGuild.id)) {
securityNum++;
if (securityNum === veilGuildsNum) setupSecurityVeil();
}
setupSecurity(newGuild);
Trello.setupCache(newGuild);
}));
Util.log('> Security setup complete');
};
// //////////////////////////////////////////////////////////////////////////////////////////////
Cmds.initCommands();
// Index_Ready -> Data_SQL -> Mutes_Initialize -> Index_Secure
client.on('ready', async () => {
Util.log(`> Connected as ${client.user.username}!`);
if (madeBriefing === false) {
madeBriefing = true;
setBriefing();
}
const dbGuilds = [];
await Promise.all(client.guilds.map(async (guild) => {
const newGuild = await guild.fetchMembers();
dbGuilds.push(newGuild);
}));
Util.log('> Cached all guild members!');
Data.connectInitial(dbGuilds)
.catch(err => Util.log(`[E_DataConnect] ${err}`));
});
client.on('disconnect', (closeEvent) => {
Util.log('DISCONNECTED');
Util.log(closeEvent);
Util.log(`Code: ${closeEvent.code}`);
Util.log(`Reason: ${closeEvent.reason}`);
Util.log(`Clean: ${closeEvent.wasClean}`);
});
client.on('guildMemberRemove', (member) => {
const guild = member.guild;
Events.emit(guild, 'UserLeave', member);
const sendLogData = [
'User Left',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Highest Role', value: member.highestRole.name },
];
Util.sendLog(sendLogData, colUser);
});
client.on('guildMemberAdd', (member) => {
const guild = member.guild;
const guildId = guild.id;
const guildName = guild.name;
const memberId = member.id;
const memberName = Util.getFullName(member);
Util.log(`User joined: ${memberName} (${memberId}) @ ${guildName}`);
// test
if (guildId === '309785618932563968') {
const veilGuild = client.guilds.get('284746138995785729');
const veilBuyer = veilGuild.roles.find('name', 'Buyer');
const newBuyer = guild.roles.find('name', 'Buyer');
if (!veilGuild) {
Util.log('[ERROR_VP] Veil guild not found!');
} else if (!veilBuyer) {
Util.log('[ERROR_VP] Veil Buyer role not found!');
} else if (!newBuyer) {
Util.log('[ERROR_VP] New Buyer role not found!');
} else {
const veilMember = Util.getMemberById(memberId, veilGuild);
if (!veilMember) {
Util.log(`[Auto-Kick 1] User not in Veil: ${memberName}`);
member.kick()
.catch(error => Util.log(`[E_AutoKick1] ${error}`));
return;
}
if (!veilMember.roles.has(veilBuyer.id)) {
Util.log(`[Auto-Kick 2] User does not have Buyer role: ${memberName}`);
member.kick()
.catch(error => Util.log(`[E_AutoKick2] ${error}`));
return;
}
member.addRole(newBuyer)
.catch(error => Util.log(`[E_AutoAddRole1] ${error}`));
Util.log('Awarded new member with Buyer role');
}
}
if (has.call(exports.globalBan, memberId)) {
member.kick()
.catch(console.error);
Util.log(`Globally banned user ${memberName} joined ${guildName}`);
return;
}
const isMuted = Mutes.checkMuted(guild, memberId);
if (isMuted) {
Util.log(`Muted user ${memberName} joined ${guildName}`);
} else {
const sendRole = Util.getRole('SendMessages', guild);
if (sendRole) {
member.addRole(sendRole)
.catch(console.error);
Util.log(`Assigned SendMessages to new member ${memberName}`);
}
}
if (memberId === '280579952263430145') member.setNickname('<- mentally challenged');
Events.emit(guild, 'UserJoin', member);
const sendLogData = [
'User Joined',
guild,
member,
{ name: 'Username', value: member.toString() },
];
Util.sendLog(sendLogData, colUser);
});
client.on('guildMemberUpdate', (oldMember, member) => {
const guild = member.guild;
const previousNick = oldMember.nickname;
const nowNick = member.nickname;
const oldRoles = oldMember.roles;
const nowRoles = member.roles;
const rolesAdded = nowRoles.filter(role => (!oldRoles.has(role.id)));
const rolesRemoved = oldRoles.filter(role => (!nowRoles.has(role.id)));
if (rolesAdded.size > 0) {
rolesAdded.forEach((nowRole) => {
if ((member.id === '214047714059616257' || member.id === '148931616452902912') && (nowRole.id === '293458258042159104' || nowRole.id === '284761589155102720')) {
member.removeRole(nowRole);
}
if (nowRole.name === 'Buyer' && guild.id === '284746138995785729') {
const message = 'Please join the Veil Buyers Discord:\n\nhttps://discord.gg/PRq6fcg\n\nThis is very important, thank you.';
const title = 'Congratulations on your purchase of Veil';
const footer = Util.makeEmbedFooter('AutoMessage');
Util.sendDescEmbed(member, title, message, footer, null, 0x00BCD4);
}
const isMuted = Mutes.checkMuted(guild, member.id);
if (nowRole.name === 'SendMessages' && isMuted) {
member.removeRole(nowRole);
Util.log(`Force re-muted ${Util.getName(member)} (${member.id})`);
} else {
const sendLogData = [
'Role Added',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Role Name', value: nowRole.name },
];
Util.sendLog(sendLogData, colUser);
}
Events.emit(guild, 'UserRoleAdd', member, nowRole);
});
}
if (rolesRemoved.size > 0) {
rolesRemoved.forEach((nowRole) => {
const isMuted = Mutes.checkMuted(guild, member.id);
if (nowRole.name === 'SendMessages' && !isMuted) {
member.addRole(nowRole)
.catch(console.error);
Util.log(`Force re-unmuted ${Util.getName(member)} (${member.id})`);
} else {
const sendLogData = [
'Role Removed',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Role Name', value: nowRole.name },
];
Util.sendLog(sendLogData, colUser);
}
Events.emit(guild, 'UserRoleRemove', member, nowRole);
});
}
if (previousNick !== nowNick) {
if (member.id === '280579952263430145' && nowNick !== '<- mentally challenged') member.setNickname('<- mentally challenged');
Events.emit(guild, 'UserNicknameUpdate', member, previousNick, nowNick);
const sendLogData = [
'Nickname Updated',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Old Nickname', value: previousNick },
{ name: 'New Nickname', value: nowNick },
];
Util.sendLog(sendLogData, colUser);
}
});
/* client.on('userUpdate', (oldUser, user) => {
const oldUsername = oldUser.username;
const newUsername = user.username;
if (oldUsername !== newUsername) {
Events.emit(guild, 'UserNicknameUpdate', member, previousNick, nowNick);
const sendLogData = [
'Username Updated',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Old Nickname', value: previousNick },
{ name: 'New Nickname', value: nowNick },
];
Util.sendLog(sendLogData, colUser);
}
});*/
client.on('messageUpdate', (oldMsgObj, newMsgObj) => {
if (newMsgObj == null) return;
const channel = newMsgObj.channel;
if (channel.name === 'vaebot-log') return;
const guild = newMsgObj.guild;
const member = newMsgObj.member;
const author = newMsgObj.author;
const content = newMsgObj.content;
const contentLower = content.toLowerCase();
// const isStaff = author.id == vaebId;
// const msgId = newMsgObj.id;
const oldContent = oldMsgObj.content;
for (let i = 0; i < exports.blockedWords.length; i++) {
if (contentLower.includes(exports.blockedWords[i].toLowerCase())) {
newMsgObj.delete();
return;
}
}
if (exports.runFuncs.length > 0) {
for (let i = 0; i < exports.runFuncs.length; i++) {
exports.runFuncs[i](newMsgObj, member, channel, guild, true);
}
}
Events.emit(guild, 'MessageUpdate', member, channel, oldContent, content);
if (oldContent !== content) {
const sendLogData = [
'Message Updated',
guild,
author,
{ name: 'Username', value: author.toString() },
{ name: 'Channel Name', value: channel.toString() },
{ name: 'Old Message', value: oldContent },
{ name: 'New Message', value: content },
];
Util.sendLog(sendLogData, colMessage);
}
});
exports.lockChannel = null;
exports.calmSpeed = 7000;
exports.slowChat = {};
exports.slowInterval = {};
exports.chatQueue = {};
exports.chatNext = {};
client.on('voiceStateUpdate', (oldMember, member) => {
const oldChannel = oldMember.voiceChannel; // May be null
const newChannel = member.voiceChannel; // May be null
const oldChannelId = oldChannel ? oldChannel.id : null;
const newChannelId = newChannel ? newChannel.id : null;
// const guild = member.guild;
if (member.id === selfId) {
if (member.serverMute) {
member.setMute(false);
Util.log('Force removed server-mute from bot');
}
if (exports.lockChannel != null && oldChannelId === exports.lockChannel && newChannelId !== exports.lockChannel) {
Util.log('Force re-joined locked channel');
oldChannel.join();
}
}
});
/*
Audit log types
const Actions = {
GUILD_UPDATE: 1,
CHANNEL_CREATE: 10,
CHANNEL_UPDATE: 11,
CHANNEL_DELETE: 12,
CHANNEL_OVERWRITE_CREATE: 13,
CHANNEL_OVERWRITE_UPDATE: 14,
CHANNEL_OVERWRITE_DELETE: 15,
MEMBER_KICK: 20,
MEMBER_PRUNE: 21,
MEMBER_BAN_ADD: 22,
MEMBER_BAN_REMOVE: 23,
MEMBER_UPDATE: 24,
MEMBER_ROLE_UPDATE: 25,
ROLE_CREATE: 30,
ROLE_UPDATE: 31,
ROLE_DELETE: 32,
INVITE_CREATE: 40,
INVITE_UPDATE: 41,
INVITE_DELETE: 42,
WEBHOOK_CREATE: 50,
WEBHOOK_UPDATE: 51,
WEBHOOK_DELETE: 52,
EMOJI_CREATE: 60,
EMOJI_UPDATE: 61,
EMOJI_DELETE: 62,
MESSAGE_DELETE: 72,
};
*/
/* function chooseRelevantEntry(entries, options) {
if (options.action == null || options.time == null) {
Util.log(options);
Util.log('Options did not contain necessary properties');
return undefined;
}
const strongest = [null, null];
entries.forEach((entry) => {
if (entry.action !== options.action || (options.target != null && entry.target.id !== options.target.id)) return;
const timeScore = -Math.abs(options.time - entry.createdTimestamp);
if (strongest[0] == null || timeScore > strongest[0]) {
strongest[0] = timeScore;
strongest[1] = entry;
}
});
return strongest[1];
} */
client.on('messageDelete', (msgObj) => {
if (msgObj == null) return;
const channel = msgObj.channel;
const guild = msgObj.guild;
const member = msgObj.member;
const author = msgObj.author;
const content = msgObj.content;
// const evTime = +new Date();
// const contentLower = content.toLowerCase();
// const isStaff = author.id == vaebId;
// const msgId = msgObj.id;
// if (author.id === vaebId) return;
Events.emit(guild, 'MessageDelete', member, channel, content);
if (guild != null) {
const attachmentLinks = [];
msgObj.attachments.forEach(obj => attachmentLinks.push(obj.url));
const sendLogData = [
'Message Deleted',
guild,
author,
{ name: 'Username', value: author.toString() },
// { name: 'Moderator', value: entry.executor.toString() },
{ name: 'Channel Name', value: channel.toString() },
{ name: 'Message', value: content },
{ name: 'Attachments', value: attachmentLinks.join('\n') },
];
Util.sendLog(sendLogData, colMessage);
/* setTimeout(() => {
guild.fetchAuditLogs({
// user: member,
type: 72,
})
.then((logs) => {
Util.log('[MD] Got audit log data');
const entries = logs.entries;
const entry = chooseRelevantEntry(entries, {
time: evTime,
target: author,
action: 'MESSAGE_DELETE',
});
Util.log(entry);
Util.log(entry.executor.toString());
Util.log(entry.target.toString());
const sendLogData = [
'Message Deleted',
guild,
author,
{ name: 'Username', value: author.toString() },
{ name: 'Moderator', value: entry.executor.toString() },
{ name: 'Channel Name', value: channel.toString() },
{ name: 'Message', value: content },
];
Util.sendLog(sendLogData, colMessage);
})
.catch((error) => {
Util.log(error);
Util.log('[MD] Failed to get audit log data');
});
}, 5000); */
}
});
const messageStamps = {};
const userStatus = {};
const lastWarn = {};
const checkMessages = 5; // (n)
const warnGrad = 13.5; // Higher = More Spam (Messages per Second) | 10 = 1 message per second
const sameGrad = 4;
const muteGrad = 8; // 9
const waitTime = 5.5;
const endAlert = 40;
/* const replaceAll = function (str, search, replacement) {
return str.split(search).join(replacement);
};
let contentLower = 'lol <qe23> tege <> <e321z> dz';
contentLower = contentLower.replace(/<[^ ]*?[:#@][^ ]*?>/gm, '');
// contentLower = replaceAll(contentLower, ' ', '');
Util.log(contentLower); */
/* exports.runFuncs.push((msgObj, speaker, channel, guild) => { // More sensitive
if (guild == null || msgObj == null || speaker == null || speaker.user.bot === true || speaker.id === vaebId) return;
let contentLower = msgObj.content.toLowerCase();
contentLower = contentLower.replace(/<[^ ]*?[:#@][^ ]*?>/gm, '');
contentLower = Util.replaceAll(contentLower, ' ', '');
contentLower = Util.replaceAll(contentLower, 'one', '1');
contentLower = Util.replaceAll(contentLower, 'won', '1');
contentLower = Util.replaceAll(contentLower, 'uno', '1');
contentLower = Util.replaceAll(contentLower, 'una', '1');
contentLower = Util.replaceAll(contentLower, 'two', '2');
contentLower = Util.replaceAll(contentLower, 'dose', '2');
contentLower = Util.replaceAll(contentLower, 'dos', '2');
contentLower = Util.replaceAll(contentLower, 'too', '2');
contentLower = Util.replaceAll(contentLower, 'to', '2');
contentLower = Util.replaceAll(contentLower, 'three', '3');
contentLower = Util.replaceAll(contentLower, 'tres', '3');
contentLower = Util.replaceAll(contentLower, 'free', '3');
let triggered = false;
if (contentLower === '3') {
triggered = true;
} else {
// const trigger = [/11./g, /12[^8]/g, /13./g, /21./g, /22./g, /23./g, /31./g, /32[^h]/g, /33./g, /muteme/g, /onet.?o/g, /threet.?o/g];
// const trigger = [/[123][123][123]/g, /muteme/g];
const trigger = [/[123][^\d]?[^\d]?[123][^\d]?[^\d]?[123]/g, /[123][123]\d/g, /muteme/g];
for (let i = 0; i < trigger.length; i++) {
if (trigger[i].test(contentLower)) {
triggered = true;
break;
}
}
}
if (triggered) {
Mutes.addMute(guild, channel, speaker, 'System', { 'reason': 'Muted Themself' });
}
}); */
exports.runFuncs.push((msgObj, speaker, channel, guild) => {
if (guild == null || msgObj == null || speaker == null || speaker.user.bot === true) return;
let contentLower = msgObj.content.toLowerCase();
contentLower = contentLower.replace(/\s/g, '');
contentLower = contentLower.replace(/which/g, 'what');
contentLower = contentLower.replace(/great/g, 'best');
contentLower = contentLower.replace(/finest/g, 'best');
contentLower = contentLower.replace(/perfect/g, 'best');
contentLower = contentLower.replace(/top/g, 'best');
contentLower = contentLower.replace(/hack/g, 'exploit');
contentLower = contentLower.replace(/h\Sx/g, 'exploit');
contentLower = contentLower.replace(/le?v\S?l(?:\d|s|f)/g, 'exploit');
let triggered = 0;
const trigger = [/wh?[au]t/g, /b\S?st/g, /explo\S?t/g];
for (let i = 0; i < trigger.length; i++) {
if (trigger[i].test(contentLower)) triggered++;
}
if (triggered == trigger.length) {
Mutes.addMute(guild, channel, speaker, 'System', { 'time': 1800000, 'reason': '[Auto-Mute] Asking stupid questions' });
}
});
exports.runFuncs.push((msgObj, speaker, channel, guild, isEdit) => {
if (isEdit || guild == null || guild.id != '284746138995785729' || msgObj == null || speaker == null || speaker.user.bot === true) return;
let contentLower = msgObj.content.toLowerCase().trim();
if (contentLower == '!buy') return;
// contentLower = contentLower.replace(/\s/g, '');
contentLower = contentLower.replace(/\bthe /g, '');
contentLower = contentLower.replace(/\bit\b/g, 'veil');
contentLower = contentLower.replace(/\bthis\b/g, 'veil');
contentLower = contentLower.replace(/\bvel\b/g, 'veil');
contentLower = contentLower.replace(/\bveli/g, 'veil');
contentLower = contentLower.replace(/\bv[ie][ie]l/g, 'veil');
contentLower = contentLower.replace(/hack\b/g, 'veil');
contentLower = contentLower.replace(/\bh\Sx\b/g, 'veil');
contentLower = contentLower.replace(/le?v\S?l.?(?:\d|s|f)/g, 'veil');
contentLower = contentLower.replace(/explo\S?t\b/g, 'veil');
contentLower = contentLower.replace(/\bpay\b/g, 'buy');
// contentLower = contentLower.replace(/get/g, 'buy');
contentLower = contentLower.replace(/get veil/g, 'buy');
contentLower = contentLower.replace(/purchas.?/g, 'buy');
let triggered = false;
if ((/\s/g).test(contentLower) && contentLower.substr(contentLower.length - 3, 3) == 'buy') {
triggered = true;
}
if (!triggered) {
let triggeredNum = 0;
const trigger = [/buy\b/g, /veil/g];
for (let i = 0; i < trigger.length; i++) {
if (trigger[i].test(contentLower)) triggeredNum++;
}
if (triggeredNum == trigger.length) triggered = true;
}
if (triggered) {
Util.sendDescEmbed(channel, 'How To Buy', 'To buy veil send a message saying !buy', null, null, 0x00E676);
}
});
function antiScam(msgObj, contentLower, speaker, channel, guild, isEdit, original) {
if (speaker == null || msgObj == null || speaker.user.bot === true) return false;
if (original) {
contentLower = contentLower.replace(/[\n\r]/g, ' ');
contentLower = contentLower.replace(/0/g, 'o');
contentLower = contentLower.replace(/1/g, 'i');
contentLower = contentLower.replace(/3/g, 'e');
contentLower = contentLower.replace(/4/g, 'a');
contentLower = contentLower.replace(/5/g, 's');
contentLower = contentLower.replace(/8/g, 'b');
contentLower = contentLower.replace(/@/g, 'a');
if (antiScam(msgObj, Util.reverse(contentLower), speaker, channel, guild, isEdit, false)) return true;
}
contentLower = contentLower.replace(/https?/g, '');
contentLower = contentLower.replace(/[^a-z .]+/g, '');
contentLower = contentLower.replace(/dot/g, '.');
contentLower = contentLower.replace(/(.)\1+/g, '$1');
if (original) {
if (antiScam(msgObj, Util.reverse(contentLower), speaker, channel, guild, isEdit, false)) return true;
}
if (guild.id == '166601083584643072') console.log(contentLower);
let triggered = false;
const trigger = [ // Change: consecutive characters, non letter/dot characters
{
regex: /[^\s.]*steam([^\s.]+)\.com/g,
allow: [/^powered$/g],
}, {
regex: /[^\s.]+steam[^\s.]*\.com/g,
allow: [],
},
];
for (let i = 0; i < trigger.length; i++) {
let matches = trigger[i].regex.exec(contentLower);
if (guild.id == '166601083584643072') console.log(matches);
if (!matches) continue;
const triggerAllow = trigger[i].allow;
for (let j = 0; j < triggerAllow.length; j++) {
if (original && triggerAllow[j].test(matches[j + 1])) {
matches = null;
break;
}
}
if (!matches) continue;
triggered = true;
break;
}
if (triggered) {
Mutes.addMute(guild, channel, speaker, 'System', { 'time': 1800000, 'reason': '[Anti-Scam] Posting a suspicious link' });
return true;
}
return false;
}
exports.runFuncs.push((msgObj, speaker, channel, guild, isEdit) => {
antiScam(msgObj, msgObj.content.toLowerCase().trim(), speaker, channel, guild, isEdit, true);
});
client.on('message', (msgObj) => {
const channel = msgObj.channel;
if (channel.name === 'vaebot-log') return;
const guild = msgObj.guild;
let speaker = msgObj.member;
let author = msgObj.author;
let content = msgObj.content;
const authorId = author.id;
// if (guild.id !== '166601083584643072') return;
if (content.substring(content.length - 5) === ' -del' && authorId === vaebId) {
msgObj.delete();
content = content.substring(0, content.length - 5);
}
let contentLower = content.toLowerCase();
const isStaff = (guild && speaker) ? Util.checkStaff(guild, speaker) : authorId === vaebId;
if (exports.blockedUsers[authorId]) {
msgObj.delete();
return;
}
if (!isStaff) {
for (let i = 0; i < exports.blockedWords.length; i++) {
if (contentLower.includes(exports.blockedWords[i].toLowerCase())) {
msgObj.delete();
return;
}
}
}
if (guild != null && contentLower.substr(0, 5) === 'sudo ' && authorId === vaebId) {
author = Util.getUserById(selfId);
speaker = Util.getMemberById(selfId, guild);
content = content.substring(5);
contentLower = content.toLowerCase();
}
if (exports.runFuncs.length > 0) {
for (let i = 0; i < exports.runFuncs.length; i++) {
exports.runFuncs[i](msgObj, speaker, channel, guild, false);
}
}
if (guild != null && author.bot === false && content.length > 0 && author.id !== guild.owner.id && !Mutes.checkMuted(guild, author.id)) {
if (!has.call(userStatus, authorId)) userStatus[authorId] = 0;
if (!has.call(messageStamps, authorId)) messageStamps[authorId] = [];
const nowStamps = messageStamps[authorId];
const stamp = (+new Date());
nowStamps.unshift({ stamp, message: contentLower });
if (Util.isSpam(content)) {
if (userStatus[authorId] == 0) {
Util.logc('AntiSpam1', `[4] ${Util.getName(speaker)} warned`);
Util.print(channel, speaker.toString(), 'Warning: If you continue to spam you will be auto-muted');
lastWarn[authorId] = stamp;
userStatus[authorId] = 2;
} else {
Util.logc('AntiSpam1', `[4] ${Util.getName(speaker)} muted`);
Mutes.addMute(guild, channel, speaker, 'System', { 'reason': '[Auto-Mute] Spamming' });
userStatus[authorId] = 0;
}
}
if (!Mutes.checkMuted(guild, author.id) && userStatus[authorId] !== 1) {
if (nowStamps.length > checkMessages) {
nowStamps.splice(checkMessages, nowStamps.length - checkMessages);
}
if (nowStamps.length >= checkMessages) {
const oldStamp = nowStamps[checkMessages - 1].stamp;
const elapsed = (stamp - oldStamp) / 1000;
const grad1 = (checkMessages / elapsed) * 10;
let checkGrad1 = sameGrad;
const latestMsg = nowStamps[0].message;
for (let i = 0; i < checkMessages; i++) {
if (nowStamps[i].message !== latestMsg) {
checkGrad1 = warnGrad;
break;
}
}
// Util.log("User: " + Util.getName(speaker) + " | Elapsed Since " + checkMessages + " Messages: " + elapsed + " | Gradient1: " + grad1);
if (grad1 >= checkGrad1) { // Is spamming
if (userStatus[authorId] === 0) {
Util.logc('AntiSpam1', `[1] ${Util.getName(speaker)} warned, gradient ${grad1} larger than ${checkGrad1}`);
userStatus[authorId] = 1;
Util.print(channel, speaker.toString(), 'Warning: If you continue to spam you will be auto-muted');
setTimeout(() => {
const lastStamp = nowStamps[0].stamp;
setTimeout(() => {
if (Mutes.checkMuted(guild, author.id)) {
Util.logc('AntiSpam1', `[2] ${Util.getName(speaker)} is already muted`);
userStatus[authorId] = 0;
return;
}
let numNew = 0;
let checkGrad2 = sameGrad;
const newStamp = (+new Date());
const latestMsg2 = nowStamps[0].message;
// var origStamp2;
for (let i = 0; i < nowStamps.length; i++) {
const curStamp = nowStamps[i];
const isFinal = curStamp.stamp === lastStamp;
if (isFinal && stamp === lastStamp) break;
numNew++;
// origStamp2 = curStamp.stamp;
if (curStamp.message !== latestMsg2) checkGrad2 = muteGrad;
if (isFinal) break;
}
if (numNew <= 1) {
Util.logc('AntiSpam1', `[2_] ${Util.getName(speaker)} stopped spamming and was put on alert`);
lastWarn[authorId] = newStamp;
userStatus[authorId] = 2;
return;
}
let numNew2 = 0;
let elapsed2 = 0;
let grad2 = 0;
// var elapsed2 = (newStamp-origStamp2)/1000;
// var grad2 = (numNew/elapsed2)*10;
for (let i = 2; i < numNew; i++) {
const curStamp = nowStamps[i].stamp;
const nowElapsed = (newStamp - curStamp) / 1000;
const nowGradient = ((i + 1) / nowElapsed) * 10;
if (nowGradient > grad2) {
grad2 = nowGradient;
elapsed2 = nowElapsed;
numNew2 = i + 1;
}
}
Util.logc('AntiSpam1', `[2] User: ${Util.getName(speaker)} | Messages Since ${elapsed2} Seconds: ${numNew2} | Gradient2: ${grad2}`);
if (grad2 >= checkGrad2) {
Util.logc('AntiSpam1', `[2] ${Util.getName(speaker)} muted, gradient ${grad2} larger than ${checkGrad2}`);
Mutes.addMute(guild, channel, speaker, 'System', { 'reason': '[Auto-Mute] Spamming' });
userStatus[authorId] = 0;
} else {
Util.logc('AntiSpam1', `[2] ${Util.getName(speaker)} was put on alert`);
lastWarn[authorId] = newStamp;
userStatus[authorId] = 2;
}
}, waitTime * 1000);
}, 350);
} else if (userStatus[authorId] === 2) {
Util.logc('AntiSpam1', `[3] ${Util.getName(speaker)} muted, repeated warns`);
Mutes.addMute(guild, channel, speaker, 'System', { 'reason': '[Auto-Mute] Spamming' });
userStatus[authorId] = 0;
}
} else if (userStatus[authorId] === 2 && (stamp - lastWarn[authorId]) > (endAlert * 1000)) {
Util.logc('AntiSpam1', `[3] ${Util.getName(speaker)} ended their alert`);
userStatus[authorId] = 0;
}
}
}
}
if (guild != null) {
if (Music.guildQueue[guild.id] == null) Music.guildQueue[guild.id] = [];
if (Music.guildMusicInfo[guild.id] == null) {
Music.guildMusicInfo[guild.id] = {
activeSong: null,
activeAuthor: null,
voteSkips: [],
isAuto: false,
};
}
}
if (guild && exports.slowChat[guild.id] && author.bot === false && !isStaff) {
const nowTime = +new Date();
if (nowTime > exports.chatNext[guild.id]) {
exports.chatNext[guild.id] = nowTime + exports.calmSpeed;
} else {
msgObj.delete()
.catch(console.error);
const intervalNum = exports.calmSpeed / 1000;
// var timeUntilSend = (exports.chatNext[guild.id] - nowTime) / 1000;
author.send(`Your message has been deleted. ${guild.name} is temporarily in slow mode, meaning everyone must wait ${intervalNum} seconds
after the previous message before they can send one.`)
.catch(console.error);
}
// exports.chatQueue[guild.id].push(msgObj);
}
Cmds.checkMessage(msgObj, speaker || author, channel, guild, content, contentLower, authorId, isStaff);
if (author.bot === true) { // RETURN IF BOT
return;
}
Events.emit(guild, 'MessageCreate', speaker, channel, msgObj, content);
if (contentLower.includes(('��').toLowerCase())) Util.print(channel, '��');
});
// //////////////////////////////////////////////////////////////////////////////////////////////
Util.log('-CONNECTING-');
client.login(Auth.discordToken);
process.on('unhandledRejection', (err) => {
console.error(`Uncaught Promise Error: \n${err.stack}`);
});
| index.js | console.log('\n-STARTING-\n');
// //////////////////////////////////////////////////////////////////////////////////////////////
const Auth = require('./Auth.js');
exports.FileSys = require('fs');
exports.DateFormat = require('dateformat');
exports.Request = require('request');
exports.Urban = require('urban');
const TrelloObj = require('node-trello');
exports.Ytdl = require('ytdl-core');
exports.Path = require('path');
exports.NodeOpus = require('node-opus');
exports.Exec = require('child_process').exec;
const YtInfoObj = require('youtube-node');
exports.Translate = require('google-translate-api');
exports.MySQL = require('mysql');
exports.YtInfo = new YtInfoObj();
exports.TrelloHandler = new TrelloObj(Auth.trelloKey, Auth.trelloToken);
exports.linkGuilds = [
['284746138995785729', '309785618932563968'],
];
exports.dbPass = Auth.dbPass;
// //////////////////////////////////////////////////////////////////////////////////////////////
global.index = module.exports;
global.has = Object.prototype.hasOwnProperty;
global.selfId = '224529399003742210';
global.vaebId = '107593015014486016';
global.Util = require('./Util.js');
global.Data = require('./data/ManageData.js');
global.Trello = require('./core/ManageTrello.js');
global.Mutes = require('./core/ManageMutesNew.js');
global.MutesOld = require('./core/ManageMutes.js'); // Will be replaced with MutesNew upon completion
global.Music = require('./core/ManageMusic.js');
global.Cmds = require('./core/ManageCommands.js');
global.Events = require('./core/ManageEvents.js');
global.Discord = require('discord.js');
exports.YtInfo.setKey(Auth.youtube);
Discord.GuildMember.prototype.getProp = function (p) {
if (this[p] != null) return this[p];
return this.user[p];
};
Discord.User.prototype.getProp = function (p) {
return this[p];
};
global.client = new Discord.Client({
disabledEvents: ['TYPING_START'],
fetchAllMembers: true,
disableEveryone: true,
});
// //////////////////////////////////////////////////////////////////////////////////////////////
exports.dailyMutes = [];
exports.dailyKicks = [];
exports.dailyBans = [];
exports.commandTypes = {
locked: 'vaeb',
staff: 'staff',
public: 'null',
};
const briefHour = 2;
const msToHours = 1 / (1000 * 60 * 60);
const dayMS = 24 / msToHours;
let madeBriefing = false;
global.colAction = 0xF44336; // Log of action, e.g. action from within command
global.colUser = 0x4CAF50; // Log of member change
global.colMessage = 0xFFEB3B; // Log of message change
global.colCommand = 0x2196F3; // Log of command being executed
exports.blockedUsers = {};
exports.blockedWords = [];
exports.runFuncs = [];
exports.warnedImage = {};
// //////////////////////////////////////////////////////////////////////////////////////////////
function setBriefing() {
setTimeout(() => {
const time1 = new Date();
const time2 = new Date();
time2.setHours(briefHour);
time2.setMinutes(0);
time2.setSeconds(0);
time2.setMilliseconds(0);
const t1 = +time1;
const t2 = +time2;
let t3 = t2 - t1;
if (t3 < 0) t3 += dayMS;
const channel = client.channels.get('168744024931434498');
// const guild = channel.guild;
Util.log(`Set daily briefing for ${t3 * msToHours} hours`);
setTimeout(() => {
// const upField = { name: '', value: '', inline: false };
const muteField = { name: 'Mutes', value: 'No mutes today', inline: false };
// var rightField = {name: "", value: ""}
const kickField = { name: 'Kicks', value: 'No kicks today', inline: false };
const banField = { name: 'Bans', value: 'No bans today', inline: false };
const embFields = [muteField, kickField, banField];
const embObj = {
title: 'Daily Briefing',
description: '',
fields: embFields,
footer: { text: '>> More info in #vaebot-log <<' },
thumbnail: { url: './resources/avatar.png' },
color: 0x00E676,
};
if (exports.dailyMutes.length > 0) {
const dataValues = [];
for (let i = 0; i < exports.dailyMutes.length; i++) {
const nowData = exports.dailyMutes[i];
const userId = nowData[0];
// const userName = nowData[1];
const userReason = nowData[2];
// const userTime = nowData[3];
const targMention = `<@${userId}>`;
let reasonStr = '';
if (userReason != null && userReason.trim().length > 0) {
reasonStr = ` : ${userReason}`;
}
dataValues.push(targMention + reasonStr);
}
muteField.value = dataValues.join('\n\n');
}
muteField.value = `\n${muteField.value}\n`;
if (exports.dailyKicks.length > 0) {
const dataValues = [];
for (let i = 0; i < exports.dailyKicks.length; i++) {
const nowData = exports.dailyKicks[i];
const userId = nowData[0];
// const userName = nowData[1];
const userReason = nowData[2];
const targMention = `<@${userId}>`;
let reasonStr = '';
if (userReason != null && userReason.trim().length > 0) {
reasonStr = ` : ${userReason}`;
}
dataValues.push(targMention + reasonStr);
}
kickField.value = dataValues.join('\n\n');
}
kickField.value = `\n${kickField.value}\n`;
if (exports.dailyBans.length > 0) {
const dataValues = [];
for (let i = 0; i < exports.dailyBans.length; i++) {
const nowData = exports.dailyBans[i];
const userId = nowData[0];
// const userName = nowData[1];
const userReason = nowData[2];
const targMention = `<@${userId}>`;
let reasonStr = '';
if (userReason != null && userReason.trim().length > 0) {
reasonStr = ` : ${userReason}`;
}
dataValues.push(targMention + reasonStr);
}
banField.value = dataValues.join('\n\n');
}
banField.value = `\n${banField.value}\n`;
if (exports.dailyMutes.length > 0
|| exports.dailyKicks.length > 0
|| exports.dailyBans.length > 0) {
channel.send(undefined, { embed: embObj })
.catch(error => Util.log(`[E_SendBriefing] ${error}`));
}
exports.dailyMutes = []; // Reset
exports.dailyKicks = [];
exports.dailyBans = [];
setBriefing();
}, t3);
}, 2000); // Let's wait 2 seconds before starting countdown, just in case of floating point errors triggering multiple countdowns
}
exports.globalBan = {
'201740276472086528': true,
'75736018761818112': true,
'123146298504380416': true,
'263372398059847681': true,
'238981466606927873': true, // Lindah
'189687397951209472': true, // xCraySECx / Nico Nico
'154255141317378050': true, // HighDefinition
'157749388964265985': true, // Zetroxer
'280419231181307906': true, // Solarical
'169261309353918464': true, // Slappy826
};
function securityFunc(guild, member, sendRoleParam) {
const guildName = guild.name;
// const guildId = guild.id;
const memberId = member.id;
const memberName = Util.getFullName(member);
let sendRole = sendRoleParam;
if (sendRole == null) sendRole = Util.getRole('SendMessages', guild);
if (has.call(exports.globalBan, memberId)) {
member.kick()
.catch(console.error);
Util.log(`Globally banned user ${memberName} had already joined ${guildName}`);
return;
}
if (sendRole != null) {
const isMuted = Mutes.checkMuted(guild, memberId);
if (isMuted) {
if (Util.hasRole(member, sendRole)) {
member.removeRole(sendRole)
.catch(console.error);
Util.log(`Muted user ${memberName} had already joined ${guildName}`);
}
} else if (!Util.hasRole(member, sendRole)) {
member.addRole(sendRole)
.catch(console.error);
Util.log(`Assigned SendMessages to old member ${memberName}`);
}
}
}
function setupSecurity(guild) {
const sendRole = Util.getRole('SendMessages', guild);
Util.logc('Security1', `Setting up security for ${guild.name} (${guild.members.size} members)`);
guild.members.forEach((member) => {
securityFunc(guild, member, sendRole);
});
}
function setupSecurityVeil() {
const veilGuild = client.guilds.get('284746138995785729');
if (!veilGuild) return Util.log('[ERROR_VP] Veil guild not found!');
const guild = client.guilds.get('309785618932563968');
if (!guild) return Util.log('[ERROR_VP] New Veil guild not found!');
const veilBuyer = veilGuild.roles.find('name', 'Buyer');
if (!veilBuyer) return Util.log('[ERROR_VP] Veil Buyer role not found!');
const newBuyer = guild.roles.find('name', 'Buyer');
if (!newBuyer) return Util.log('[ERROR_VP] New Buyer role not found!');
// const guildId = guild.id;
// const guildName = guild.name;
Util.logc('AutoKick1', `Setting up auto-kick for ${guild.name} (${guild.members.size} members)`);
guild.members.forEach((member) => {
const memberId = member.id;
if (memberId === vaebId || memberId === selfId) return;
const memberName = Util.getFullName(member);
const veilMember = Util.getMemberById(memberId, veilGuild);
if (!veilMember) {
Util.log(`[Auto-Old-Kick 1] User not in Veil: ${memberName}`);
member.kick()
.catch(error => Util.log(`[E_AutoOldKick1] ${memberName} | ${error}`));
return;
}
if (!veilMember.roles.has(veilBuyer.id)) {
Util.log(`[Auto-Old-Kick 2] User does not have Buyer role: ${memberName}`);
member.kick()
.catch(error => Util.log(`[E_AutoOldKick2] ${memberName} | ${error}`));
return;
}
if (!member.roles.has(newBuyer.id)) {
member.addRole(newBuyer)
.catch(error => Util.log(`[E_AutoOldAddRole1] ${memberName} | ${error}`));
Util.log(`Updated old member with Buyer role: ${memberName}`);
}
});
return undefined;
}
const veilGuilds = {
'284746138995785729': true,
'309785618932563968': true,
};
exports.secure = async function () {
Util.log('> Securing guilds...');
let securityNum = 0;
const veilGuildsNum = Object.keys(veilGuilds).length;
await Promise.all(client.guilds.map(async (guild) => {
const newGuild = await guild.fetchMembers();
if (newGuild == null) {
Util.log(newGuild);
Util.log('Found null guild');
return;
}
if (has.call(veilGuilds, newGuild.id)) {
securityNum++;
if (securityNum === veilGuildsNum) setupSecurityVeil();
}
setupSecurity(newGuild);
Trello.setupCache(newGuild);
}));
Util.log('> Security setup complete');
};
// //////////////////////////////////////////////////////////////////////////////////////////////
Cmds.initCommands();
// Index_Ready -> Data_SQL -> Mutes_Initialize -> Index_Secure
client.on('ready', async () => {
Util.log(`> Connected as ${client.user.username}!`);
if (madeBriefing === false) {
madeBriefing = true;
setBriefing();
}
const dbGuilds = [];
await Promise.all(client.guilds.map(async (guild) => {
const newGuild = await guild.fetchMembers();
dbGuilds.push(newGuild);
}));
Util.log('> Cached all guild members!');
Data.connectInitial(dbGuilds)
.catch(err => Util.log(`[E_DataConnect] ${err}`));
});
client.on('disconnect', (closeEvent) => {
Util.log('DISCONNECTED');
Util.log(closeEvent);
Util.log(`Code: ${closeEvent.code}`);
Util.log(`Reason: ${closeEvent.reason}`);
Util.log(`Clean: ${closeEvent.wasClean}`);
});
client.on('guildMemberRemove', (member) => {
const guild = member.guild;
Events.emit(guild, 'UserLeave', member);
const sendLogData = [
'User Left',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Highest Role', value: member.highestRole.name },
];
Util.sendLog(sendLogData, colUser);
});
client.on('guildMemberAdd', (member) => {
const guild = member.guild;
const guildId = guild.id;
const guildName = guild.name;
const memberId = member.id;
const memberName = Util.getFullName(member);
Util.log(`User joined: ${memberName} (${memberId}) @ ${guildName}`);
// test
if (guildId === '309785618932563968') {
const veilGuild = client.guilds.get('284746138995785729');
const veilBuyer = veilGuild.roles.find('name', 'Buyer');
const newBuyer = guild.roles.find('name', 'Buyer');
if (!veilGuild) {
Util.log('[ERROR_VP] Veil guild not found!');
} else if (!veilBuyer) {
Util.log('[ERROR_VP] Veil Buyer role not found!');
} else if (!newBuyer) {
Util.log('[ERROR_VP] New Buyer role not found!');
} else {
const veilMember = Util.getMemberById(memberId, veilGuild);
if (!veilMember) {
Util.log(`[Auto-Kick 1] User not in Veil: ${memberName}`);
member.kick()
.catch(error => Util.log(`[E_AutoKick1] ${error}`));
return;
}
if (!veilMember.roles.has(veilBuyer.id)) {
Util.log(`[Auto-Kick 2] User does not have Buyer role: ${memberName}`);
member.kick()
.catch(error => Util.log(`[E_AutoKick2] ${error}`));
return;
}
member.addRole(newBuyer)
.catch(error => Util.log(`[E_AutoAddRole1] ${error}`));
Util.log('Awarded new member with Buyer role');
}
}
if (has.call(exports.globalBan, memberId)) {
member.kick()
.catch(console.error);
Util.log(`Globally banned user ${memberName} joined ${guildName}`);
return;
}
const isMuted = Mutes.checkMuted(guild, memberId);
if (isMuted) {
Util.log(`Muted user ${memberName} joined ${guildName}`);
} else {
const sendRole = Util.getRole('SendMessages', guild);
if (sendRole) {
member.addRole(sendRole)
.catch(console.error);
Util.log(`Assigned SendMessages to new member ${memberName}`);
}
}
if (memberId === '280579952263430145') member.setNickname('<- mentally challenged');
Events.emit(guild, 'UserJoin', member);
const sendLogData = [
'User Joined',
guild,
member,
{ name: 'Username', value: member.toString() },
];
Util.sendLog(sendLogData, colUser);
});
client.on('guildMemberUpdate', (oldMember, member) => {
const guild = member.guild;
const previousNick = oldMember.nickname;
const nowNick = member.nickname;
const oldRoles = oldMember.roles;
const nowRoles = member.roles;
const rolesAdded = nowRoles.filter(role => (!oldRoles.has(role.id)));
const rolesRemoved = oldRoles.filter(role => (!nowRoles.has(role.id)));
if (rolesAdded.size > 0) {
rolesAdded.forEach((nowRole) => {
if ((member.id === '214047714059616257' || member.id === '148931616452902912') && (nowRole.id === '293458258042159104' || nowRole.id === '284761589155102720')) {
member.removeRole(nowRole);
}
if (nowRole.name === 'Buyer' && guild.id === '284746138995785729') {
const message = 'Please join the Veil Buyers Discord:\n\nhttps://discord.gg/PRq6fcg\n\nThis is very important, thank you.';
const title = 'Congratulations on your purchase of Veil';
const footer = Util.makeEmbedFooter('AutoMessage');
Util.sendDescEmbed(member, title, message, footer, null, 0x00BCD4);
}
const isMuted = Mutes.checkMuted(guild, member.id);
if (nowRole.name === 'SendMessages' && isMuted) {
member.removeRole(nowRole);
Util.log(`Force re-muted ${Util.getName(member)} (${member.id})`);
} else {
const sendLogData = [
'Role Added',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Role Name', value: nowRole.name },
];
Util.sendLog(sendLogData, colUser);
}
Events.emit(guild, 'UserRoleAdd', member, nowRole);
});
}
if (rolesRemoved.size > 0) {
rolesRemoved.forEach((nowRole) => {
const isMuted = Mutes.checkMuted(guild, member.id);
if (nowRole.name === 'SendMessages' && !isMuted) {
member.addRole(nowRole)
.catch(console.error);
Util.log(`Force re-unmuted ${Util.getName(member)} (${member.id})`);
} else {
const sendLogData = [
'Role Removed',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Role Name', value: nowRole.name },
];
Util.sendLog(sendLogData, colUser);
}
Events.emit(guild, 'UserRoleRemove', member, nowRole);
});
}
if (previousNick !== nowNick) {
if (member.id === '280579952263430145' && nowNick !== '<- mentally challenged') member.setNickname('<- mentally challenged');
Events.emit(guild, 'UserNicknameUpdate', member, previousNick, nowNick);
const sendLogData = [
'Nickname Updated',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Old Nickname', value: previousNick },
{ name: 'New Nickname', value: nowNick },
];
Util.sendLog(sendLogData, colUser);
}
});
/* client.on('userUpdate', (oldUser, user) => {
const oldUsername = oldUser.username;
const newUsername = user.username;
if (oldUsername !== newUsername) {
Events.emit(guild, 'UserNicknameUpdate', member, previousNick, nowNick);
const sendLogData = [
'Username Updated',
guild,
member,
{ name: 'Username', value: member.toString() },
{ name: 'Old Nickname', value: previousNick },
{ name: 'New Nickname', value: nowNick },
];
Util.sendLog(sendLogData, colUser);
}
});*/
client.on('messageUpdate', (oldMsgObj, newMsgObj) => {
if (newMsgObj == null) return;
const channel = newMsgObj.channel;
if (channel.name === 'vaebot-log') return;
const guild = newMsgObj.guild;
const member = newMsgObj.member;
const author = newMsgObj.author;
const content = newMsgObj.content;
const contentLower = content.toLowerCase();
// const isStaff = author.id == vaebId;
// const msgId = newMsgObj.id;
const oldContent = oldMsgObj.content;
for (let i = 0; i < exports.blockedWords.length; i++) {
if (contentLower.includes(exports.blockedWords[i].toLowerCase())) {
newMsgObj.delete();
return;
}
}
if (exports.runFuncs.length > 0) {
for (let i = 0; i < exports.runFuncs.length; i++) {
exports.runFuncs[i](newMsgObj, member, channel, guild, true);
}
}
Events.emit(guild, 'MessageUpdate', member, channel, oldContent, content);
if (oldContent !== content) {
const sendLogData = [
'Message Updated',
guild,
author,
{ name: 'Username', value: author.toString() },
{ name: 'Channel Name', value: channel.toString() },
{ name: 'Old Message', value: oldContent },
{ name: 'New Message', value: content },
];
Util.sendLog(sendLogData, colMessage);
}
});
exports.lockChannel = null;
exports.calmSpeed = 7000;
exports.slowChat = {};
exports.slowInterval = {};
exports.chatQueue = {};
exports.chatNext = {};
client.on('voiceStateUpdate', (oldMember, member) => {
const oldChannel = oldMember.voiceChannel; // May be null
const newChannel = member.voiceChannel; // May be null
const oldChannelId = oldChannel ? oldChannel.id : null;
const newChannelId = newChannel ? newChannel.id : null;
// const guild = member.guild;
if (member.id === selfId) {
if (member.serverMute) {
member.setMute(false);
Util.log('Force removed server-mute from bot');
}
if (exports.lockChannel != null && oldChannelId === exports.lockChannel && newChannelId !== exports.lockChannel) {
Util.log('Force re-joined locked channel');
oldChannel.join();
}
}
});
/*
Audit log types
const Actions = {
GUILD_UPDATE: 1,
CHANNEL_CREATE: 10,
CHANNEL_UPDATE: 11,
CHANNEL_DELETE: 12,
CHANNEL_OVERWRITE_CREATE: 13,
CHANNEL_OVERWRITE_UPDATE: 14,
CHANNEL_OVERWRITE_DELETE: 15,
MEMBER_KICK: 20,
MEMBER_PRUNE: 21,
MEMBER_BAN_ADD: 22,
MEMBER_BAN_REMOVE: 23,
MEMBER_UPDATE: 24,
MEMBER_ROLE_UPDATE: 25,
ROLE_CREATE: 30,
ROLE_UPDATE: 31,
ROLE_DELETE: 32,
INVITE_CREATE: 40,
INVITE_UPDATE: 41,
INVITE_DELETE: 42,
WEBHOOK_CREATE: 50,
WEBHOOK_UPDATE: 51,
WEBHOOK_DELETE: 52,
EMOJI_CREATE: 60,
EMOJI_UPDATE: 61,
EMOJI_DELETE: 62,
MESSAGE_DELETE: 72,
};
*/
/* function chooseRelevantEntry(entries, options) {
if (options.action == null || options.time == null) {
Util.log(options);
Util.log('Options did not contain necessary properties');
return undefined;
}
const strongest = [null, null];
entries.forEach((entry) => {
if (entry.action !== options.action || (options.target != null && entry.target.id !== options.target.id)) return;
const timeScore = -Math.abs(options.time - entry.createdTimestamp);
if (strongest[0] == null || timeScore > strongest[0]) {
strongest[0] = timeScore;
strongest[1] = entry;
}
});
return strongest[1];
} */
client.on('messageDelete', (msgObj) => {
if (msgObj == null) return;
const channel = msgObj.channel;
const guild = msgObj.guild;
const member = msgObj.member;
const author = msgObj.author;
const content = msgObj.content;
// const evTime = +new Date();
// const contentLower = content.toLowerCase();
// const isStaff = author.id == vaebId;
// const msgId = msgObj.id;
// if (author.id === vaebId) return;
Events.emit(guild, 'MessageDelete', member, channel, content);
if (guild != null) {
const attachmentLinks = [];
msgObj.attachments.forEach(obj => attachmentLinks.push(obj.url));
const sendLogData = [
'Message Deleted',
guild,
author,
{ name: 'Username', value: author.toString() },
// { name: 'Moderator', value: entry.executor.toString() },
{ name: 'Channel Name', value: channel.toString() },
{ name: 'Message', value: content },
{ name: 'Attachments', value: attachmentLinks.join('\n') },
];
Util.sendLog(sendLogData, colMessage);
/* setTimeout(() => {
guild.fetchAuditLogs({
// user: member,
type: 72,
})
.then((logs) => {
Util.log('[MD] Got audit log data');
const entries = logs.entries;
const entry = chooseRelevantEntry(entries, {
time: evTime,
target: author,
action: 'MESSAGE_DELETE',
});
Util.log(entry);
Util.log(entry.executor.toString());
Util.log(entry.target.toString());
const sendLogData = [
'Message Deleted',
guild,
author,
{ name: 'Username', value: author.toString() },
{ name: 'Moderator', value: entry.executor.toString() },
{ name: 'Channel Name', value: channel.toString() },
{ name: 'Message', value: content },
];
Util.sendLog(sendLogData, colMessage);
})
.catch((error) => {
Util.log(error);
Util.log('[MD] Failed to get audit log data');
});
}, 5000); */
}
});
const messageStamps = {};
const userStatus = {};
const lastWarn = {};
const checkMessages = 5; // (n)
const warnGrad = 13.5; // Higher = More Spam (Messages per Second) | 10 = 1 message per second
const sameGrad = 4;
const muteGrad = 8; // 9
const waitTime = 5.5;
const endAlert = 40;
/* const replaceAll = function (str, search, replacement) {
return str.split(search).join(replacement);
};
let contentLower = 'lol <qe23> tege <> <e321z> dz';
contentLower = contentLower.replace(/<[^ ]*?[:#@][^ ]*?>/gm, '');
// contentLower = replaceAll(contentLower, ' ', '');
Util.log(contentLower); */
/* exports.runFuncs.push((msgObj, speaker, channel, guild) => { // More sensitive
if (guild == null || msgObj == null || speaker == null || speaker.user.bot === true || speaker.id === vaebId) return;
let contentLower = msgObj.content.toLowerCase();
contentLower = contentLower.replace(/<[^ ]*?[:#@][^ ]*?>/gm, '');
contentLower = Util.replaceAll(contentLower, ' ', '');
contentLower = Util.replaceAll(contentLower, 'one', '1');
contentLower = Util.replaceAll(contentLower, 'won', '1');
contentLower = Util.replaceAll(contentLower, 'uno', '1');
contentLower = Util.replaceAll(contentLower, 'una', '1');
contentLower = Util.replaceAll(contentLower, 'two', '2');
contentLower = Util.replaceAll(contentLower, 'dose', '2');
contentLower = Util.replaceAll(contentLower, 'dos', '2');
contentLower = Util.replaceAll(contentLower, 'too', '2');
contentLower = Util.replaceAll(contentLower, 'to', '2');
contentLower = Util.replaceAll(contentLower, 'three', '3');
contentLower = Util.replaceAll(contentLower, 'tres', '3');
contentLower = Util.replaceAll(contentLower, 'free', '3');
let triggered = false;
if (contentLower === '3') {
triggered = true;
} else {
// const trigger = [/11./g, /12[^8]/g, /13./g, /21./g, /22./g, /23./g, /31./g, /32[^h]/g, /33./g, /muteme/g, /onet.?o/g, /threet.?o/g];
// const trigger = [/[123][123][123]/g, /muteme/g];
const trigger = [/[123][^\d]?[^\d]?[123][^\d]?[^\d]?[123]/g, /[123][123]\d/g, /muteme/g];
for (let i = 0; i < trigger.length; i++) {
if (trigger[i].test(contentLower)) {
triggered = true;
break;
}
}
}
if (triggered) {
Mutes.addMute(guild, channel, speaker, 'System', { 'reason': 'Muted Themself' });
}
}); */
exports.runFuncs.push((msgObj, speaker, channel, guild) => {
if (guild == null || msgObj == null || speaker == null || speaker.user.bot === true) return;
let contentLower = msgObj.content.toLowerCase();
contentLower = contentLower.replace(/\s/g, '');
contentLower = contentLower.replace(/which/g, 'what');
contentLower = contentLower.replace(/great/g, 'best');
contentLower = contentLower.replace(/finest/g, 'best');
contentLower = contentLower.replace(/perfect/g, 'best');
contentLower = contentLower.replace(/top/g, 'best');
contentLower = contentLower.replace(/hack/g, 'exploit');
contentLower = contentLower.replace(/h\Sx/g, 'exploit');
contentLower = contentLower.replace(/le?v\S?l(?:\d|s|f)/g, 'exploit');
let triggered = 0;
const trigger = [/wh?[au]t/g, /b\S?st/g, /explo\S?t/g];
for (let i = 0; i < trigger.length; i++) {
if (trigger[i].test(contentLower)) triggered++;
}
if (triggered == trigger.length) {
Mutes.addMute(guild, channel, speaker, 'System', { 'time': 1800000, 'reason': '[Auto-Mute] Asking stupid questions' });
}
});
exports.runFuncs.push((msgObj, speaker, channel, guild, isEdit) => {
if (isEdit || guild == null || guild.id != '284746138995785729' || msgObj == null || speaker == null || speaker.user.bot === true) return;
let contentLower = msgObj.content.toLowerCase().trim();
if (contentLower == '!buy') return;
// contentLower = contentLower.replace(/\s/g, '');
contentLower = contentLower.replace(/\bthe /g, '');
contentLower = contentLower.replace(/\bit\b/g, 'veil');
contentLower = contentLower.replace(/\bthis\b/g, 'veil');
contentLower = contentLower.replace(/\bvel\b/g, 'veil');
contentLower = contentLower.replace(/\bveli/g, 'veil');
contentLower = contentLower.replace(/\bv[ie][ie]l/g, 'veil');
contentLower = contentLower.replace(/hack\b/g, 'veil');
contentLower = contentLower.replace(/\bh\Sx\b/g, 'veil');
contentLower = contentLower.replace(/le?v\S?l.?(?:\d|s|f)/g, 'veil');
contentLower = contentLower.replace(/explo\S?t\b/g, 'veil');
contentLower = contentLower.replace(/\bpay\b/g, 'buy');
// contentLower = contentLower.replace(/get/g, 'buy');
contentLower = contentLower.replace(/get veil/g, 'buy');
contentLower = contentLower.replace(/purchas.?/g, 'buy');
let triggered = false;
if ((/\s/g).test(contentLower) && contentLower.substr(contentLower.length - 3, 3) == 'buy') {
triggered = true;
}
if (!triggered) {
let triggeredNum = 0;
const trigger = [/buy\b/g, /veil/g];
for (let i = 0; i < trigger.length; i++) {
if (trigger[i].test(contentLower)) triggeredNum++;
}
if (triggeredNum == trigger.length) triggered = true;
}
if (triggered) {
Util.sendDescEmbed(channel, 'How To Buy', 'To buy veil send a message saying !buy', null, null, 0x00E676);
}
});
function antiScam(msgObj, contentLower, speaker, channel, guild, isEdit, original) {
if (speaker == null || msgObj == null || speaker.user.bot === true) return false;
if (original) {
contentLower = contentLower.replace(/[\n\r]/g, ' ');
contentLower = contentLower.replace(/0/g, 'o');
contentLower = contentLower.replace(/1/g, 'i');
contentLower = contentLower.replace(/3/g, 'e');
contentLower = contentLower.replace(/4/g, 'a');
contentLower = contentLower.replace(/5/g, 's');
contentLower = contentLower.replace(/8/g, 'b');
contentLower = contentLower.replace(/@/g, 'a');
if (antiScam(msgObj, Util.reverse(contentLower), speaker, channel, guild, isEdit, false)) return true;
}
contentLower = contentLower.replace(/https?/g, '');
contentLower = contentLower.replace(/[^a-z .]+/g, '');
contentLower = contentLower.replace(/dot/g, '.');
contentLower = contentLower.replace(/(.)\1+/g, '$1');
if (original) {
if (antiScam(msgObj, Util.reverse(contentLower), speaker, channel, guild, isEdit, false)) return true;
}
if (guild.id == '166601083584643072') console.log(contentLower);
let triggered = false;
const trigger = [ // Change: consecutive characters, non letter/dot characters
{
regex: /[^\s.]*steam([^\s.]+)\.com/g,
allow: [/^powered$/g],
}, {
regex: /[^\s.]+steam[^\s.]*\.com/g,
allow: [],
},
];
for (let i = 0; i < trigger.length; i++) {
let matches = trigger[i].regex.exec(contentLower);
if (guild.id == '166601083584643072') console.log(matches);
if (!matches) continue;
for (let j = 0; j < matches.length; j++) {
if (original && trigger[i].allow[j].test(matches[j + 1])) {
matches = null;
break;
}
}
if (!matches) continue;
triggered = true;
break;
}
if (triggered) {
Mutes.addMute(guild, channel, speaker, 'System', { 'time': 1800000, 'reason': '[Anti-Scam] Posting a suspicious link' });
return true;
}
return false;
}
exports.runFuncs.push((msgObj, speaker, channel, guild, isEdit) => {
antiScam(msgObj, msgObj.content.toLowerCase().trim(), speaker, channel, guild, isEdit, true);
});
client.on('message', (msgObj) => {
const channel = msgObj.channel;
if (channel.name === 'vaebot-log') return;
const guild = msgObj.guild;
let speaker = msgObj.member;
let author = msgObj.author;
let content = msgObj.content;
const authorId = author.id;
// if (guild.id !== '166601083584643072') return;
if (content.substring(content.length - 5) === ' -del' && authorId === vaebId) {
msgObj.delete();
content = content.substring(0, content.length - 5);
}
let contentLower = content.toLowerCase();
const isStaff = (guild && speaker) ? Util.checkStaff(guild, speaker) : authorId === vaebId;
if (exports.blockedUsers[authorId]) {
msgObj.delete();
return;
}
if (!isStaff) {
for (let i = 0; i < exports.blockedWords.length; i++) {
if (contentLower.includes(exports.blockedWords[i].toLowerCase())) {
msgObj.delete();
return;
}
}
}
if (guild != null && contentLower.substr(0, 5) === 'sudo ' && authorId === vaebId) {
author = Util.getUserById(selfId);
speaker = Util.getMemberById(selfId, guild);
content = content.substring(5);
contentLower = content.toLowerCase();
}
if (exports.runFuncs.length > 0) {
for (let i = 0; i < exports.runFuncs.length; i++) {
exports.runFuncs[i](msgObj, speaker, channel, guild, false);
}
}
if (guild != null && author.bot === false && content.length > 0 && author.id !== guild.owner.id && !Mutes.checkMuted(guild, author.id)) {
if (!has.call(userStatus, authorId)) userStatus[authorId] = 0;
if (!has.call(messageStamps, authorId)) messageStamps[authorId] = [];
const nowStamps = messageStamps[authorId];
const stamp = (+new Date());
nowStamps.unshift({ stamp, message: contentLower });
if (Util.isSpam(content)) {
if (userStatus[authorId] == 0) {
Util.logc('AntiSpam1', `[4] ${Util.getName(speaker)} warned`);
Util.print(channel, speaker.toString(), 'Warning: If you continue to spam you will be auto-muted');
lastWarn[authorId] = stamp;
userStatus[authorId] = 2;
} else {
Util.logc('AntiSpam1', `[4] ${Util.getName(speaker)} muted`);
Mutes.addMute(guild, channel, speaker, 'System', { 'reason': '[Auto-Mute] Spamming' });
userStatus[authorId] = 0;
}
}
if (!Mutes.checkMuted(guild, author.id) && userStatus[authorId] !== 1) {
if (nowStamps.length > checkMessages) {
nowStamps.splice(checkMessages, nowStamps.length - checkMessages);
}
if (nowStamps.length >= checkMessages) {
const oldStamp = nowStamps[checkMessages - 1].stamp;
const elapsed = (stamp - oldStamp) / 1000;
const grad1 = (checkMessages / elapsed) * 10;
let checkGrad1 = sameGrad;
const latestMsg = nowStamps[0].message;
for (let i = 0; i < checkMessages; i++) {
if (nowStamps[i].message !== latestMsg) {
checkGrad1 = warnGrad;
break;
}
}
// Util.log("User: " + Util.getName(speaker) + " | Elapsed Since " + checkMessages + " Messages: " + elapsed + " | Gradient1: " + grad1);
if (grad1 >= checkGrad1) { // Is spamming
if (userStatus[authorId] === 0) {
Util.logc('AntiSpam1', `[1] ${Util.getName(speaker)} warned, gradient ${grad1} larger than ${checkGrad1}`);
userStatus[authorId] = 1;
Util.print(channel, speaker.toString(), 'Warning: If you continue to spam you will be auto-muted');
setTimeout(() => {
const lastStamp = nowStamps[0].stamp;
setTimeout(() => {
if (Mutes.checkMuted(guild, author.id)) {
Util.logc('AntiSpam1', `[2] ${Util.getName(speaker)} is already muted`);
userStatus[authorId] = 0;
return;
}
let numNew = 0;
let checkGrad2 = sameGrad;
const newStamp = (+new Date());
const latestMsg2 = nowStamps[0].message;
// var origStamp2;
for (let i = 0; i < nowStamps.length; i++) {
const curStamp = nowStamps[i];
const isFinal = curStamp.stamp === lastStamp;
if (isFinal && stamp === lastStamp) break;
numNew++;
// origStamp2 = curStamp.stamp;
if (curStamp.message !== latestMsg2) checkGrad2 = muteGrad;
if (isFinal) break;
}
if (numNew <= 1) {
Util.logc('AntiSpam1', `[2_] ${Util.getName(speaker)} stopped spamming and was put on alert`);
lastWarn[authorId] = newStamp;
userStatus[authorId] = 2;
return;
}
let numNew2 = 0;
let elapsed2 = 0;
let grad2 = 0;
// var elapsed2 = (newStamp-origStamp2)/1000;
// var grad2 = (numNew/elapsed2)*10;
for (let i = 2; i < numNew; i++) {
const curStamp = nowStamps[i].stamp;
const nowElapsed = (newStamp - curStamp) / 1000;
const nowGradient = ((i + 1) / nowElapsed) * 10;
if (nowGradient > grad2) {
grad2 = nowGradient;
elapsed2 = nowElapsed;
numNew2 = i + 1;
}
}
Util.logc('AntiSpam1', `[2] User: ${Util.getName(speaker)} | Messages Since ${elapsed2} Seconds: ${numNew2} | Gradient2: ${grad2}`);
if (grad2 >= checkGrad2) {
Util.logc('AntiSpam1', `[2] ${Util.getName(speaker)} muted, gradient ${grad2} larger than ${checkGrad2}`);
Mutes.addMute(guild, channel, speaker, 'System', { 'reason': '[Auto-Mute] Spamming' });
userStatus[authorId] = 0;
} else {
Util.logc('AntiSpam1', `[2] ${Util.getName(speaker)} was put on alert`);
lastWarn[authorId] = newStamp;
userStatus[authorId] = 2;
}
}, waitTime * 1000);
}, 350);
} else if (userStatus[authorId] === 2) {
Util.logc('AntiSpam1', `[3] ${Util.getName(speaker)} muted, repeated warns`);
Mutes.addMute(guild, channel, speaker, 'System', { 'reason': '[Auto-Mute] Spamming' });
userStatus[authorId] = 0;
}
} else if (userStatus[authorId] === 2 && (stamp - lastWarn[authorId]) > (endAlert * 1000)) {
Util.logc('AntiSpam1', `[3] ${Util.getName(speaker)} ended their alert`);
userStatus[authorId] = 0;
}
}
}
}
if (guild != null) {
if (Music.guildQueue[guild.id] == null) Music.guildQueue[guild.id] = [];
if (Music.guildMusicInfo[guild.id] == null) {
Music.guildMusicInfo[guild.id] = {
activeSong: null,
activeAuthor: null,
voteSkips: [],
isAuto: false,
};
}
}
if (guild && exports.slowChat[guild.id] && author.bot === false && !isStaff) {
const nowTime = +new Date();
if (nowTime > exports.chatNext[guild.id]) {
exports.chatNext[guild.id] = nowTime + exports.calmSpeed;
} else {
msgObj.delete()
.catch(console.error);
const intervalNum = exports.calmSpeed / 1000;
// var timeUntilSend = (exports.chatNext[guild.id] - nowTime) / 1000;
author.send(`Your message has been deleted. ${guild.name} is temporarily in slow mode, meaning everyone must wait ${intervalNum} seconds
after the previous message before they can send one.`)
.catch(console.error);
}
// exports.chatQueue[guild.id].push(msgObj);
}
Cmds.checkMessage(msgObj, speaker || author, channel, guild, content, contentLower, authorId, isStaff);
if (author.bot === true) { // RETURN IF BOT
return;
}
Events.emit(guild, 'MessageCreate', speaker, channel, msgObj, content);
if (contentLower.includes(('��').toLowerCase())) Util.print(channel, '��');
});
// //////////////////////////////////////////////////////////////////////////////////////////////
Util.log('-CONNECTING-');
client.login(Auth.discordToken);
process.on('unhandledRejection', (err) => {
console.error(`Uncaught Promise Error: \n${err.stack}`);
});
| Length check fix
| index.js | Length check fix | <ide><path>ndex.js
<ide> let matches = trigger[i].regex.exec(contentLower);
<ide> if (guild.id == '166601083584643072') console.log(matches);
<ide> if (!matches) continue;
<del> for (let j = 0; j < matches.length; j++) {
<del> if (original && trigger[i].allow[j].test(matches[j + 1])) {
<add> const triggerAllow = trigger[i].allow;
<add> for (let j = 0; j < triggerAllow.length; j++) {
<add> if (original && triggerAllow[j].test(matches[j + 1])) {
<ide> matches = null;
<ide> break;
<ide> } |
|
Java | bsd-3-clause | dbb64999fb8442d67174c69471f7058a6aaec48d | 0 | fbastian/owltools,fbastian/owltools,owlcollab/owltools,dhimmel/owltools,fbastian/owltools,dhimmel/owltools,fbastian/owltools,dhimmel/owltools,owlcollab/owltools,dhimmel/owltools,dhimmel/owltools,fbastian/owltools,dhimmel/owltools,fbastian/owltools,owlcollab/owltools,owlcollab/owltools,owlcollab/owltools,owlcollab/owltools | package owltools.gaf.lego;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.semanticweb.elk.owlapi.ElkReasonerFactory;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import owltools.OWLToolsTestBasics;
import owltools.gaf.GafDocument;
import owltools.gaf.GafObjectsBuilder;
import owltools.graph.OWLGraphWrapper;
import owltools.io.ParserWrapper;
import owltools.util.MinimalModelGeneratorTest;
import owltools.vocab.OBOUpperVocabulary;
public class MolecularModelManagerTest extends AbstractLegoModelGeneratorTest {
private static Logger LOG = Logger.getLogger(MolecularModelManagerTest.class);
MolecularModelManager mmm;
static{
Logger.getLogger("org.semanticweb.elk").setLevel(Level.ERROR);
//Logger.getLogger("org.semanticweb.elk.reasoner.indexing.hierarchy").setLevel(Level.ERROR);
}
@Test
public void testM3() throws Exception {
ParserWrapper pw = new ParserWrapper();
//w = new FileWriter(new File("target/lego.out"));
g = pw.parseToOWLGraph(getResourceIRIString("go-mgi-signaling-test.obo"));
g.mergeOntology(pw.parseOBO(getResourceIRIString("disease.obo")));
//g.m
mmm = new MolecularModelManager(g);
File gafPath = getResource("mgi-signaling.gaf");
mmm.loadGaf("mgi", gafPath);
OWLClass p = g.getOWLClassByIdentifier("GO:0014029"); // neural crest formation
String modelId = mmm.generateModel(p, "mgi");
LOG.info("Model: "+modelId);
LegoModelGenerator model = mmm.getModel(modelId);
Set<OWLNamedIndividual> inds = mmm.getIndividuals(modelId);
LOG.info("Individuals: "+inds.size());
for (OWLNamedIndividual i : inds) {
LOG.info("I="+i);
}
assertTrue(inds.size() == 15);
// GO:0001158 ! enhancer sequence-specific DNA binding
String bindingId = mmm.createActivityIndividual(modelId, g.getOWLClassByIdentifier("GO:0001158"));
LOG.info("New: "+bindingId);
// GO:0005654 ! nucleoplasm
mmm.addOccursIn(modelId, bindingId, "GO:0005654");
mmm.addEnabledBy(modelId, bindingId, "PR:P123456");
// todo - add a test that results in an inconsistency
List<Map> objs = mmm.getIndividualObjects(modelId);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String js = gson.toJson(objs);
LOG.info("INDS:" + js);
LOG.info(mmm.generateDot(modelId));
// LOG.info(mmm.generateImage(modelId)); // problematic due to missing dot application
}
}
| OWLTools-Annotation/src/test/java/owltools/gaf/lego/MolecularModelManagerTest.java | package owltools.gaf.lego;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.semanticweb.elk.owlapi.ElkReasonerFactory;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import owltools.OWLToolsTestBasics;
import owltools.gaf.GafDocument;
import owltools.gaf.GafObjectsBuilder;
import owltools.graph.OWLGraphWrapper;
import owltools.io.ParserWrapper;
import owltools.util.MinimalModelGeneratorTest;
import owltools.vocab.OBOUpperVocabulary;
public class MolecularModelManagerTest extends AbstractLegoModelGeneratorTest {
private static Logger LOG = Logger.getLogger(MolecularModelManagerTest.class);
MolecularModelManager mmm;
static{
Logger.getLogger("org.semanticweb.elk").setLevel(Level.ERROR);
//Logger.getLogger("org.semanticweb.elk.reasoner.indexing.hierarchy").setLevel(Level.ERROR);
}
@Test
public void testM3() throws Exception {
ParserWrapper pw = new ParserWrapper();
//w = new FileWriter(new File("target/lego.out"));
g = pw.parseToOWLGraph(getResourceIRIString("go-mgi-signaling-test.obo"));
g.mergeOntology(pw.parseOBO(getResourceIRIString("disease.obo")));
//g.m
mmm = new MolecularModelManager(g);
File gafPath = getResource("mgi-signaling.gaf");
mmm.loadGaf("mgi", gafPath);
OWLClass p = g.getOWLClassByIdentifier("GO:0014029"); // neural crest formation
String modelId = mmm.generateModel(p, "mgi");
LOG.info("Model: "+modelId);
LegoModelGenerator model = mmm.getModel(modelId);
Set<OWLNamedIndividual> inds = mmm.getIndividuals(modelId);
LOG.info("Individuals: "+inds.size());
for (OWLNamedIndividual i : inds) {
LOG.info("I="+i);
}
assertTrue(inds.size() == 15);
// GO:0001158 ! enhancer sequence-specific DNA binding
String bindingId = mmm.createActivityIndividual(modelId, g.getOWLClassByIdentifier("GO:0001158"));
LOG.info("New: "+bindingId);
// GO:0005654 ! nucleoplasm
mmm.addOccursIn(modelId, bindingId, "GO:0005654");
mmm.addEnabledBy(modelId, bindingId, "PR:P123456");
// todo - add a test that results in an inconsistency
List<Map> objs = mmm.getIndividualObjects(modelId);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String js = gson.toJson(objs);
LOG.info("INDS:" + js);
LOG.info(mmm.generateDot(modelId));
LOG.info(mmm.generateImage(modelId));
}
}
| fixes issue 87
git-svn-id: f705032614e1ff11fed11a7e506afa6fa6966044@1835 18f1da76-1bb4-b526-5913-e828fe20442d
| OWLTools-Annotation/src/test/java/owltools/gaf/lego/MolecularModelManagerTest.java | fixes issue 87 | <ide><path>WLTools-Annotation/src/test/java/owltools/gaf/lego/MolecularModelManagerTest.java
<ide> LOG.info("INDS:" + js);
<ide>
<ide> LOG.info(mmm.generateDot(modelId));
<del> LOG.info(mmm.generateImage(modelId));
<add>// LOG.info(mmm.generateImage(modelId)); // problematic due to missing dot application
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | b9ebe154b01b5c1a3233ca8dbf38be2901ce25a6 | 0 | adrcotfas/Goodtime | /*
* Copyright 2016-2019 Adrian Cotfas
*
* 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.
*/
package com.apps.adrcotfas.goodtime.Settings;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TimePicker;
import android.widget.Toast;
import com.apps.adrcotfas.goodtime.R;
import com.apps.adrcotfas.goodtime.Util.StringUtils;
import com.apps.adrcotfas.goodtime.Util.ThemeHelper;
import com.apps.adrcotfas.goodtime.Util.TimePickerDialogFixedNougatSpinner;
import com.takisoft.preferencex.PreferenceFragmentCompat;
import com.takisoft.preferencex.RingtonePreferenceDialogFragmentCompat;
import com.takisoft.preferencex.RingtonePreference;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.preference.CheckBoxPreference;
import androidx.preference.Preference;
import androidx.preference.SwitchPreferenceCompat;
import org.joda.time.DateTime;
import org.joda.time.LocalTime;
import static com.apps.adrcotfas.goodtime.Settings.PreferenceHelper.DISABLE_SOUND_AND_VIBRATION;
import static com.apps.adrcotfas.goodtime.Settings.PreferenceHelper.VIBRATION_TYPE;
import static com.apps.adrcotfas.goodtime.Util.UpgradeActivityHelper.launchUpgradeActivity;
public class SettingsFragment extends PreferenceFragmentCompat implements ActivityCompat.OnRequestPermissionsResultCallback, TimePickerDialog.OnTimeSetListener {
private static final String TAG = "SettingsFragment";
private CheckBoxPreference mPrefDisableSoundCheckbox;
private SwitchPreferenceCompat mPrefReminder;
@Override
public void onCreatePreferencesFix(@Nullable Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.settings, rootKey);
mPrefDisableSoundCheckbox = findPreference(DISABLE_SOUND_AND_VIBRATION);
setupReminderPreference();
}
private void setupReminderPreference() {
mPrefReminder = findPreference(PreferenceHelper.ENABLE_REMINDER);
mPrefReminder.setSummaryOn(StringUtils.formatTime(PreferenceHelper.getTimeOfReminder()));
mPrefReminder.setSummaryOff("");
mPrefReminder.setOnPreferenceClickListener(preference -> {
mPrefReminder.setChecked(!mPrefReminder.isChecked());
return true;
});
mPrefReminder.setOnPreferenceChangeListener((preference, newValue) -> {
if ((boolean)newValue) {
final long millis = PreferenceHelper.getTimeOfReminder();
final DateTime time = new DateTime(millis);
TimePickerDialogFixedNougatSpinner d = new TimePickerDialogFixedNougatSpinner(
getActivity(),
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
? R.style.DialogTheme : AlertDialog.THEME_HOLO_DARK,
SettingsFragment.this,
time.getHourOfDay(),
time.getMinuteOfHour(),
DateFormat.is24HourFormat(getContext()));
d.show();
return true;
}
return false;
});
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setAlpha(0.f);
view.animate().alpha(1.f).setDuration(100);
return view;
}
@SuppressLint("BatteryLife")
@Override
public void onResume() {
super.onResume();
getActivity().setTitle(getString(R.string.settings));
setupTheme();
setupRingtone();
setupScreensaver();
setupAutoStartSessionVsInsistentNotification();
setupDisableSoundCheckBox();
final Preference disableBatteryOptimizationPref = findPreference(PreferenceHelper.DISABLE_BATTERY_OPTIMIZATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isIgnoringBatteryOptimizations()) {
disableBatteryOptimizationPref.setVisible(true);
disableBatteryOptimizationPref.setOnPreferenceClickListener(preference -> {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
startActivity(intent);
return true;
});
} else {
disableBatteryOptimizationPref.setVisible(false);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
findPreference(PreferenceHelper.DISABLE_WIFI).setVisible(false);
}
}
@Override
public void onDisplayPreferenceDialog(Preference preference) {
if (preference instanceof RingtonePreference) {
try {
RingtonePreferenceDialogFragmentCompat dialog =
RingtonePreferenceDialogFragmentCompat.newInstance(preference.getKey());
dialog.setTargetFragment(this, 0);
if (preference.getKey().equals(PreferenceHelper.RINGTONE_BREAK_FINISHED)
&& !PreferenceHelper.isPro()) {
launchUpgradeActivity(getActivity());
}
else {
dialog.show(getParentFragmentManager(), null);
}
} catch (NumberFormatException e) {
//TODO: handle this later
Log.e(TAG, "The annoying RingtonePreferenceDialog exception was thrown");
Toast.makeText(
requireActivity(),
"Something went wrong",
Toast.LENGTH_SHORT).show();
}
} else if (preference.getKey().equals(PreferenceHelper.TIMER_STYLE)) {
super.onDisplayPreferenceDialog(preference);
} else if (preference.getKey().equals(VIBRATION_TYPE)) {
VibrationPreferenceDialogFragment dialog = VibrationPreferenceDialogFragment.newInstance(preference.getKey());
dialog.setTargetFragment(this, 0);
dialog.show(getParentFragmentManager(), null);
} else {
super.onDisplayPreferenceDialog(preference);
}
}
private void setupAutoStartSessionVsInsistentNotification() {
// Continuous mode versus insistent notification
CheckBoxPreference autoWork = findPreference(PreferenceHelper.AUTO_START_WORK);
autoWork.setOnPreferenceChangeListener((preference, newValue) -> {
final CheckBoxPreference pref = findPreference(PreferenceHelper.INSISTENT_RINGTONE);
if ((boolean)newValue) {
pref.setChecked(false);
}
return true;
});
CheckBoxPreference autoBreak = findPreference(PreferenceHelper.AUTO_START_BREAK);
autoBreak.setOnPreferenceChangeListener((preference, newValue) -> {
final CheckBoxPreference pref = findPreference(PreferenceHelper.INSISTENT_RINGTONE);
if ((boolean)newValue) {
pref.setChecked(false);
}
return true;
});
final CheckBoxPreference insistentRingPref = findPreference(PreferenceHelper.INSISTENT_RINGTONE);
insistentRingPref.setOnPreferenceClickListener(PreferenceHelper.isPro() ? null : preference -> {
launchUpgradeActivity(getActivity());
insistentRingPref.setChecked(false);
return true;
});
insistentRingPref.setOnPreferenceChangeListener(PreferenceHelper.isPro() ? (preference, newValue) -> {
final CheckBoxPreference p1 = findPreference(PreferenceHelper.AUTO_START_BREAK);
final CheckBoxPreference p2 = findPreference(PreferenceHelper.AUTO_START_WORK);
if ((boolean)newValue) {
p1.setChecked(false);
p2.setChecked(false);
}
return true;
} : null);
}
private void setupRingtone() {
final RingtonePreference prefWork = findPreference(PreferenceHelper.RINGTONE_WORK_FINISHED);
final RingtonePreference prefBreak = findPreference(PreferenceHelper.RINGTONE_BREAK_FINISHED);
if (PreferenceHelper.isPro()) {
prefWork.setOnPreferenceChangeListener(null);
} else {
prefBreak.setRingtone(prefWork.getRingtone());
prefWork.setOnPreferenceChangeListener((preference, newValue) -> {
prefBreak.setRingtone((Uri) newValue);
prefBreak.setSummary(prefBreak.getSummary());
return true;
});
}
final SwitchPreferenceCompat prefEnableRingtone = findPreference(PreferenceHelper.ENABLE_RINGTONE);
toggleEnableRingtonePreference(prefEnableRingtone.isChecked());
prefEnableRingtone.setOnPreferenceChangeListener((preference, newValue) -> {
toggleEnableRingtonePreference((Boolean) newValue);
return true;
});
}
private void setupScreensaver() {
final CheckBoxPreference screensaverPref = SettingsFragment.this.findPreference(PreferenceHelper.ENABLE_SCREENSAVER_MODE);
findPreference(PreferenceHelper.ENABLE_SCREENSAVER_MODE).setOnPreferenceClickListener(PreferenceHelper.isPro() ? null : preference -> {
launchUpgradeActivity(getActivity());
screensaverPref.setChecked(false);
return true;
});
findPreference(PreferenceHelper.ENABLE_SCREEN_ON).setOnPreferenceChangeListener((preference, newValue) -> {
if (!((boolean) newValue)) {
if (screensaverPref.isChecked()) {
screensaverPref.setChecked(false);
}
}
return true;
});
}
private void setupTheme() {
SwitchPreferenceCompat prefAmoled = findPreference(PreferenceHelper.AMOLED);
prefAmoled.setOnPreferenceClickListener(PreferenceHelper.isPro() ? null : preference -> {
launchUpgradeActivity(getActivity());
prefAmoled.setChecked(true);
return true;
});
prefAmoled.setOnPreferenceChangeListener(PreferenceHelper.isPro() ? (preference, newValue) -> {
ThemeHelper.setTheme((SettingsActivity)getActivity());
getActivity().recreate();
return true;
} : null);
}
private void updateDisableSoundCheckBoxSummary(boolean notificationPolicyAccessGranted) {
if (notificationPolicyAccessGranted) {
mPrefDisableSoundCheckbox.setSummary("");
} else {
mPrefDisableSoundCheckbox.setSummary(R.string.settings_grant_permission);
}
}
private void setupDisableSoundCheckBox() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isNotificationPolicyAccessDenied()) {
updateDisableSoundCheckBoxSummary(false);
mPrefDisableSoundCheckbox.setChecked(false);
mPrefDisableSoundCheckbox.setOnPreferenceClickListener(
preference -> {
requestNotificationPolicyAccess();
return false;
}
);
} else {
updateDisableSoundCheckBoxSummary(true);
}
}
private boolean isIgnoringBatteryOptimizations(){
PowerManager pwrm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return pwrm.isIgnoringBatteryOptimizations(getActivity().getPackageName());
}
return true;
}
private void requestNotificationPolicyAccess() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isNotificationPolicyAccessDenied()) {
Intent intent = new Intent(android.provider.Settings.
ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
@TargetApi(Build.VERSION_CODES.M)
private boolean isNotificationPolicyAccessDenied() {
NotificationManager notificationManager = (NotificationManager)
getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
return !notificationManager.isNotificationPolicyAccessGranted();
}
private void toggleEnableRingtonePreference(Boolean newValue) {
findPreference(PreferenceHelper.RINGTONE_WORK_FINISHED).setVisible(newValue);
findPreference(PreferenceHelper.RINGTONE_BREAK_FINISHED).setVisible(newValue);
findPreference(PreferenceHelper.PRIORITY_ALARM).setVisible(newValue);
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
final long millis = new LocalTime(hourOfDay, minute).toDateTimeToday().getMillis();
PreferenceHelper.setTimeOfReminder(millis);
mPrefReminder.setSummaryOn(StringUtils.formatTime(millis));
mPrefReminder.setChecked(true);
}
}
| app/src/main/java/com/apps/adrcotfas/goodtime/Settings/SettingsFragment.java | /*
* Copyright 2016-2019 Adrian Cotfas
*
* 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.
*/
package com.apps.adrcotfas.goodtime.Settings;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TimePicker;
import android.widget.Toast;
import com.apps.adrcotfas.goodtime.R;
import com.apps.adrcotfas.goodtime.Util.StringUtils;
import com.apps.adrcotfas.goodtime.Util.ThemeHelper;
import com.apps.adrcotfas.goodtime.Util.TimePickerDialogFixedNougatSpinner;
import com.takisoft.preferencex.PreferenceFragmentCompat;
import com.takisoft.preferencex.RingtonePreferenceDialogFragmentCompat;
import com.takisoft.preferencex.RingtonePreference;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.preference.CheckBoxPreference;
import androidx.preference.Preference;
import androidx.preference.SwitchPreferenceCompat;
import org.joda.time.DateTime;
import org.joda.time.LocalTime;
import static com.apps.adrcotfas.goodtime.Settings.PreferenceHelper.DISABLE_SOUND_AND_VIBRATION;
import static com.apps.adrcotfas.goodtime.Settings.PreferenceHelper.VIBRATION_TYPE;
import static com.apps.adrcotfas.goodtime.Util.UpgradeActivityHelper.launchUpgradeActivity;
public class SettingsFragment extends PreferenceFragmentCompat implements ActivityCompat.OnRequestPermissionsResultCallback, TimePickerDialog.OnTimeSetListener {
private static final String TAG = "SettingsFragment";
private CheckBoxPreference mPrefDisableSoundCheckbox;
private SwitchPreferenceCompat mPrefReminder;
@Override
public void onCreatePreferencesFix(@Nullable Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.settings, rootKey);
mPrefDisableSoundCheckbox = findPreference(DISABLE_SOUND_AND_VIBRATION);
setupReminderPreference();
}
private void setupReminderPreference() {
mPrefReminder = findPreference(PreferenceHelper.ENABLE_REMINDER);
mPrefReminder.setSummaryOn(StringUtils.formatTime(PreferenceHelper.getTimeOfReminder()));
mPrefReminder.setSummaryOff("");
mPrefReminder.setOnPreferenceClickListener(preference -> {
mPrefReminder.setChecked(!mPrefReminder.isChecked());
return true;
});
mPrefReminder.setOnPreferenceChangeListener((preference, newValue) -> {
if ((boolean)newValue) {
final long millis = PreferenceHelper.getTimeOfReminder();
final DateTime time = new DateTime(millis);
TimePickerDialogFixedNougatSpinner d = new TimePickerDialogFixedNougatSpinner(
getActivity(),
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
? R.style.DialogTheme : AlertDialog.THEME_HOLO_DARK,
SettingsFragment.this,
time.getHourOfDay(),
time.getMinuteOfHour(),
DateFormat.is24HourFormat(getContext()));
d.show();
return true;
}
return false;
});
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view.setAlpha(0.f);
view.animate().alpha(1.f).setDuration(100);
return view;
}
@SuppressLint("BatteryLife")
@Override
public void onResume() {
super.onResume();
getActivity().setTitle(getString(R.string.settings));
setupTheme();
setupRingtone();
setupScreensaver();
setupAutoStartSessionVsInsistentNotification();
setupDisableSoundCheckBox();
final Preference disableBatteryOptimizationPref = findPreference(PreferenceHelper.DISABLE_BATTERY_OPTIMIZATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !isIgnoringBatteryOptimizations()) {
disableBatteryOptimizationPref.setVisible(true);
disableBatteryOptimizationPref.setOnPreferenceClickListener(preference -> {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
startActivity(intent);
return true;
});
} else {
disableBatteryOptimizationPref.setVisible(false);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
findPreference(PreferenceHelper.DISABLE_WIFI).setVisible(false);
}
}
@Override
public void onDisplayPreferenceDialog(Preference preference) {
if (preference instanceof RingtonePreference) {
RingtonePreferenceDialogFragmentCompat dialog =
RingtonePreferenceDialogFragmentCompat.newInstance(preference.getKey());
dialog.setTargetFragment(this, 0);
if (preference.getKey().equals(PreferenceHelper.RINGTONE_BREAK_FINISHED)
&& !PreferenceHelper.isPro()) {
launchUpgradeActivity(getActivity());
}
else {
try {
dialog.show(getParentFragmentManager(), null);
} catch (NumberFormatException e) {
//TODO: handle this later
Log.e(TAG, "The annoying RingtonePreferenceDialog exception was thrown");
Toast.makeText(
requireActivity(),
"Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
} else if (preference.getKey().equals(PreferenceHelper.TIMER_STYLE)) {
super.onDisplayPreferenceDialog(preference);
} else if (preference.getKey().equals(VIBRATION_TYPE)) {
VibrationPreferenceDialogFragment dialog = VibrationPreferenceDialogFragment.newInstance(preference.getKey());
dialog.setTargetFragment(this, 0);
dialog.show(getParentFragmentManager(), null);
} else {
super.onDisplayPreferenceDialog(preference);
}
}
private void setupAutoStartSessionVsInsistentNotification() {
// Continuous mode versus insistent notification
CheckBoxPreference autoWork = findPreference(PreferenceHelper.AUTO_START_WORK);
autoWork.setOnPreferenceChangeListener((preference, newValue) -> {
final CheckBoxPreference pref = findPreference(PreferenceHelper.INSISTENT_RINGTONE);
if ((boolean)newValue) {
pref.setChecked(false);
}
return true;
});
CheckBoxPreference autoBreak = findPreference(PreferenceHelper.AUTO_START_BREAK);
autoBreak.setOnPreferenceChangeListener((preference, newValue) -> {
final CheckBoxPreference pref = findPreference(PreferenceHelper.INSISTENT_RINGTONE);
if ((boolean)newValue) {
pref.setChecked(false);
}
return true;
});
final CheckBoxPreference insistentRingPref = findPreference(PreferenceHelper.INSISTENT_RINGTONE);
insistentRingPref.setOnPreferenceClickListener(PreferenceHelper.isPro() ? null : preference -> {
launchUpgradeActivity(getActivity());
insistentRingPref.setChecked(false);
return true;
});
insistentRingPref.setOnPreferenceChangeListener(PreferenceHelper.isPro() ? (preference, newValue) -> {
final CheckBoxPreference p1 = findPreference(PreferenceHelper.AUTO_START_BREAK);
final CheckBoxPreference p2 = findPreference(PreferenceHelper.AUTO_START_WORK);
if ((boolean)newValue) {
p1.setChecked(false);
p2.setChecked(false);
}
return true;
} : null);
}
private void setupRingtone() {
final RingtonePreference prefWork = findPreference(PreferenceHelper.RINGTONE_WORK_FINISHED);
final RingtonePreference prefBreak = findPreference(PreferenceHelper.RINGTONE_BREAK_FINISHED);
if (PreferenceHelper.isPro()) {
prefWork.setOnPreferenceChangeListener(null);
} else {
prefBreak.setRingtone(prefWork.getRingtone());
prefWork.setOnPreferenceChangeListener((preference, newValue) -> {
prefBreak.setRingtone((Uri) newValue);
prefBreak.setSummary(prefBreak.getSummary());
return true;
});
}
final SwitchPreferenceCompat prefEnableRingtone = findPreference(PreferenceHelper.ENABLE_RINGTONE);
toggleEnableRingtonePreference(prefEnableRingtone.isChecked());
prefEnableRingtone.setOnPreferenceChangeListener((preference, newValue) -> {
toggleEnableRingtonePreference((Boolean) newValue);
return true;
});
}
private void setupScreensaver() {
final CheckBoxPreference screensaverPref = SettingsFragment.this.findPreference(PreferenceHelper.ENABLE_SCREENSAVER_MODE);
findPreference(PreferenceHelper.ENABLE_SCREENSAVER_MODE).setOnPreferenceClickListener(PreferenceHelper.isPro() ? null : preference -> {
launchUpgradeActivity(getActivity());
screensaverPref.setChecked(false);
return true;
});
findPreference(PreferenceHelper.ENABLE_SCREEN_ON).setOnPreferenceChangeListener((preference, newValue) -> {
if (!((boolean) newValue)) {
if (screensaverPref.isChecked()) {
screensaverPref.setChecked(false);
}
}
return true;
});
}
private void setupTheme() {
SwitchPreferenceCompat prefAmoled = findPreference(PreferenceHelper.AMOLED);
prefAmoled.setOnPreferenceClickListener(PreferenceHelper.isPro() ? null : preference -> {
launchUpgradeActivity(getActivity());
prefAmoled.setChecked(true);
return true;
});
prefAmoled.setOnPreferenceChangeListener(PreferenceHelper.isPro() ? (preference, newValue) -> {
ThemeHelper.setTheme((SettingsActivity)getActivity());
getActivity().recreate();
return true;
} : null);
}
private void updateDisableSoundCheckBoxSummary(boolean notificationPolicyAccessGranted) {
if (notificationPolicyAccessGranted) {
mPrefDisableSoundCheckbox.setSummary("");
} else {
mPrefDisableSoundCheckbox.setSummary(R.string.settings_grant_permission);
}
}
private void setupDisableSoundCheckBox() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isNotificationPolicyAccessDenied()) {
updateDisableSoundCheckBoxSummary(false);
mPrefDisableSoundCheckbox.setChecked(false);
mPrefDisableSoundCheckbox.setOnPreferenceClickListener(
preference -> {
requestNotificationPolicyAccess();
return false;
}
);
} else {
updateDisableSoundCheckBoxSummary(true);
}
}
private boolean isIgnoringBatteryOptimizations(){
PowerManager pwrm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return pwrm.isIgnoringBatteryOptimizations(getActivity().getPackageName());
}
return true;
}
private void requestNotificationPolicyAccess() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isNotificationPolicyAccessDenied()) {
Intent intent = new Intent(android.provider.Settings.
ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
@TargetApi(Build.VERSION_CODES.M)
private boolean isNotificationPolicyAccessDenied() {
NotificationManager notificationManager = (NotificationManager)
getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
return !notificationManager.isNotificationPolicyAccessGranted();
}
private void toggleEnableRingtonePreference(Boolean newValue) {
findPreference(PreferenceHelper.RINGTONE_WORK_FINISHED).setVisible(newValue);
findPreference(PreferenceHelper.RINGTONE_BREAK_FINISHED).setVisible(newValue);
findPreference(PreferenceHelper.PRIORITY_ALARM).setVisible(newValue);
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
final long millis = new LocalTime(hourOfDay, minute).toDateTimeToday().getMillis();
PreferenceHelper.setTimeOfReminder(millis);
mPrefReminder.setSummaryOn(StringUtils.formatTime(millis));
mPrefReminder.setChecked(true);
}
}
| RingtonePreference: extend the try catch
| app/src/main/java/com/apps/adrcotfas/goodtime/Settings/SettingsFragment.java | RingtonePreference: extend the try catch | <ide><path>pp/src/main/java/com/apps/adrcotfas/goodtime/Settings/SettingsFragment.java
<ide> @Override
<ide> public void onDisplayPreferenceDialog(Preference preference) {
<ide> if (preference instanceof RingtonePreference) {
<del> RingtonePreferenceDialogFragmentCompat dialog =
<del> RingtonePreferenceDialogFragmentCompat.newInstance(preference.getKey());
<del> dialog.setTargetFragment(this, 0);
<del> if (preference.getKey().equals(PreferenceHelper.RINGTONE_BREAK_FINISHED)
<del> && !PreferenceHelper.isPro()) {
<del> launchUpgradeActivity(getActivity());
<del> }
<del> else {
<del> try {
<add> try {
<add> RingtonePreferenceDialogFragmentCompat dialog =
<add> RingtonePreferenceDialogFragmentCompat.newInstance(preference.getKey());
<add> dialog.setTargetFragment(this, 0);
<add> if (preference.getKey().equals(PreferenceHelper.RINGTONE_BREAK_FINISHED)
<add> && !PreferenceHelper.isPro()) {
<add> launchUpgradeActivity(getActivity());
<add> }
<add> else {
<ide> dialog.show(getParentFragmentManager(), null);
<del> } catch (NumberFormatException e) {
<del> //TODO: handle this later
<del> Log.e(TAG, "The annoying RingtonePreferenceDialog exception was thrown");
<del> Toast.makeText(
<del> requireActivity(),
<del> "Something went wrong",
<del> Toast.LENGTH_SHORT).show();
<ide> }
<add> } catch (NumberFormatException e) {
<add> //TODO: handle this later
<add> Log.e(TAG, "The annoying RingtonePreferenceDialog exception was thrown");
<add> Toast.makeText(
<add> requireActivity(),
<add> "Something went wrong",
<add> Toast.LENGTH_SHORT).show();
<ide> }
<ide> } else if (preference.getKey().equals(PreferenceHelper.TIMER_STYLE)) {
<ide> super.onDisplayPreferenceDialog(preference); |
|
Java | apache-2.0 | 4058836b3398cda683858052e62cd3081929f7e1 | 0 | fjoglar/ETSIT-News | /*
* Copyright (C) 2016 Felipe Joglar Santos
*
* 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.
*/
package com.fjoglar.etsitnoticias.view.adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.fjoglar.etsitnoticias.R;
import com.fjoglar.etsitnoticias.data.entities.NewsItem;
import com.fjoglar.etsitnoticias.utils.CategoryUtils;
import com.fjoglar.etsitnoticias.utils.DateUtils;
import com.fjoglar.etsitnoticias.utils.FormatTextUtils;
import com.fjoglar.etsitnoticias.view.widget.bookmark.BookmarkButtonView;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class NewsListAdapter extends RecyclerView.Adapter<NewsListAdapter.NewsViewHolder> {
public static final String BOOKMARK_ON_TAG = "bookmark_on_tag";
public static final String BOOKMARK_OFF_TAG = "bookmark_off_tag";
private List<NewsItem> mNewsItemList;
private OnItemClickListener mOnItemClickListener;
private OnBookmarkClickListener mOnBookmarkClickListener;
public NewsListAdapter(@NonNull OnItemClickListener onItemClickListener,
@NonNull OnBookmarkClickListener onBookmarkClickListener) {
this.mNewsItemList = Collections.emptyList();
this.mOnItemClickListener = onItemClickListener;
this.mOnBookmarkClickListener = onBookmarkClickListener;
}
@Override
public NewsListAdapter.NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.item_news_list, parent, false);
return new NewsViewHolder(itemView);
}
@Override
public void onBindViewHolder(final NewsListAdapter.NewsViewHolder holder, int position) {
final NewsItem item = mNewsItemList.get(position);
holder.title.setText(item.getTitle());
holder.date.setText(DateUtils.formatListViewTime(item.getFormattedPubDate()));
if (!TextUtils.isEmpty(item.getDescription())) {
holder.description.setVisibility(View.VISIBLE);
holder.description.setText(FormatTextUtils.formatSmallText(item.getDescription()));
} else {
holder.description.setVisibility(View.GONE);
}
holder.category.setText(CategoryUtils.categoryToString(holder.category.getContext(),
item.getCategory()));
holder.bookmark.setImage(item.getBookmarked());
holder.bookmark.setTag(
(item.getBookmarked() == 1) ? BOOKMARK_ON_TAG : BOOKMARK_OFF_TAG);
holder.bookmark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnBookmarkClickListener.onBookmarkClicked(item);
item.changeBookmarkedStatus(item.getBookmarked());
notifyItemChanged(holder.getAdapterPosition());
}
});
holder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnItemClickListener.onItemClicked(item.getFormattedPubDate());
}
});
}
@Override
public int getItemCount() {
return mNewsItemList.size();
}
public void setNewsListAdapter(List<NewsItem> newsItemList) {
this.mNewsItemList = newsItemList;
}
final static class NewsViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.item_title) TextView title;
@BindView(R.id.item_date) TextView date;
@BindView(R.id.item_description) TextView description;
@BindView(R.id.item_category) TextView category;
@BindView(R.id.item_bookmark) BookmarkButtonView bookmark;
public NewsViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void setOnClickListener(View.OnClickListener listener) {
itemView.setOnClickListener(listener);
}
}
public interface OnItemClickListener {
void onItemClicked(long date);
}
public interface OnBookmarkClickListener {
void onBookmarkClicked(NewsItem newsItem);
}
}
| app/src/main/java/com/fjoglar/etsitnoticias/view/adapter/NewsListAdapter.java | /*
* Copyright (C) 2016 Felipe Joglar Santos
*
* 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.
*/
package com.fjoglar.etsitnoticias.view.adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.fjoglar.etsitnoticias.R;
import com.fjoglar.etsitnoticias.data.entities.NewsItem;
import com.fjoglar.etsitnoticias.utils.CategoryUtils;
import com.fjoglar.etsitnoticias.utils.DateUtils;
import com.fjoglar.etsitnoticias.utils.FormatTextUtils;
import com.fjoglar.etsitnoticias.view.widget.bookmark.BookmarkButtonView;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class NewsListAdapter extends RecyclerView.Adapter<NewsListAdapter.NewsViewHolder> {
private final String LOG_TAG = NewsListAdapter.class.getSimpleName();
public static final String BOOKMARK_ON_TAG = "bookmark_on_tag";
public static final String BOOKMARK_OFF_TAG = "bookmark_off_tag";
private List<NewsItem> mNewsItemList;
private OnItemClickListener mOnItemClickListener;
private OnBookmarkClickListener mOnBookmarkClickListener;
public NewsListAdapter(@NonNull OnItemClickListener onItemClickListener,
@NonNull OnBookmarkClickListener onBookmarkClickListener) {
this.mNewsItemList = Collections.emptyList();
this.mOnItemClickListener = onItemClickListener;
this.mOnBookmarkClickListener = onBookmarkClickListener;
}
@Override
public NewsListAdapter.NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.
from(parent.getContext()).
inflate(R.layout.item_news_list, parent, false);
return new NewsViewHolder(itemView);
}
@Override
public void onBindViewHolder(final NewsListAdapter.NewsViewHolder holder, int position) {
final NewsItem item = mNewsItemList.get(position);
holder.title.setText(item.getTitle());
holder.date.setText(DateUtils.formatListViewTime(item.getFormattedPubDate()));
if (!TextUtils.isEmpty(item.getDescription())) {
holder.description.setVisibility(View.VISIBLE);
holder.description.setText(FormatTextUtils.formatSmallText(item.getDescription()));
} else {
holder.description.setVisibility(View.GONE);
}
holder.category.setText(CategoryUtils.categoryToString(holder.category.getContext(),
item.getCategory()));
holder.bookmark.setImage(item.getBookmarked());
holder.bookmark.setTag(
(item.getBookmarked() == 1) ? BOOKMARK_ON_TAG : BOOKMARK_OFF_TAG);
holder.bookmark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnBookmarkClickListener.onBookmarkClicked(item);
item.changeBookmarkedStatus(item.getBookmarked());
notifyItemChanged(holder.getAdapterPosition());
}
});
holder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnItemClickListener.onItemClicked(item.getFormattedPubDate());
}
});
}
@Override
public int getItemCount() {
return mNewsItemList.size();
}
public void setNewsListAdapter(List<NewsItem> newsItemList) {
this.mNewsItemList = newsItemList;
}
final static class NewsViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.item_title) TextView title;
@BindView(R.id.item_date) TextView date;
@BindView(R.id.item_description) TextView description;
@BindView(R.id.item_category) TextView category;
@BindView(R.id.item_bookmark) BookmarkButtonView bookmark;
public NewsViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void setOnClickListener(View.OnClickListener listener) {
itemView.setOnClickListener(listener);
}
}
public interface OnItemClickListener {
void onItemClicked(long date);
}
public interface OnBookmarkClickListener {
void onBookmarkClicked(NewsItem newsItem);
}
}
| 170 - Remove unused constant
| app/src/main/java/com/fjoglar/etsitnoticias/view/adapter/NewsListAdapter.java | 170 - Remove unused constant | <ide><path>pp/src/main/java/com/fjoglar/etsitnoticias/view/adapter/NewsListAdapter.java
<ide> import butterknife.ButterKnife;
<ide>
<ide> public class NewsListAdapter extends RecyclerView.Adapter<NewsListAdapter.NewsViewHolder> {
<del>
<del> private final String LOG_TAG = NewsListAdapter.class.getSimpleName();
<ide>
<ide> public static final String BOOKMARK_ON_TAG = "bookmark_on_tag";
<ide> public static final String BOOKMARK_OFF_TAG = "bookmark_off_tag"; |
|
Java | mit | fbd7cff90330bfc7d74e6c10651b50550e540910 | 0 | kir-dev/korok,kir-dev/korok,kir-dev/korok,kir-dev/korok,kir-dev/korok | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hu.sch.kp.ejb;
import hu.sch.domain.BelepoIgeny;
import hu.sch.domain.BelepoTipus;
import hu.sch.domain.ElbiraltErtekeles;
import hu.sch.domain.Ertekeles;
import hu.sch.domain.ErtekelesStatusz;
import hu.sch.domain.ErtekelesUzenet;
import hu.sch.domain.PontIgeny;
import hu.sch.domain.Szemeszter;
import hu.sch.domain.Csoport;
import hu.sch.domain.ElfogadottBelepo;
import hu.sch.domain.ErtekelesIdoszak;
import hu.sch.domain.ErtekelesStatisztika;
import hu.sch.domain.Felhasznalo;
import hu.sch.kp.services.ErtekelesManagerLocal;
import hu.sch.kp.services.SystemManagerLocal;
import hu.sch.kp.services.UserManagerLocal;
import hu.sch.kp.services.exceptions.NoSuchAttributeException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author hege
*/
@Stateless
public class ErtekelesManagerBean implements ErtekelesManagerLocal {
private static final String defaultSortColumnForErtekelesLista = "csoportNev";
private static final Map<String, String> sortMapForErtekelesLista;
private static final String statisztikaQuery = "SELECT new hu.sch.domain.ErtekelesStatisztika(e, " + "(SELECT avg(p.pont) FROM PontIgeny p WHERE p.ertekeles = e AND p.pont > 0) as atlagpont, " + "(SELECT count(*) as numKDO FROM BelepoIgeny as b WHERE b.ertekeles = e AND b.belepotipus=\'KDO\') as igenyeltkdo, " + "(SELECT count(*) as numKB FROM BelepoIgeny as b WHERE b.ertekeles = e AND b.belepotipus=\'KB\') as igenyeltkb, " + "(SELECT count(*) as numAB FROM BelepoIgeny as b WHERE b.ertekeles = e AND b.belepotipus=\'AB\') as igenyeltab" + ") FROM Ertekeles e ";
@PersistenceContext
EntityManager em;
@EJB
UserManagerLocal userManager;
@EJB
SystemManagerLocal systemManager;
static {
/* Hibernate BUG:
* http://opensource.atlassian.com/projects/hibernate/browse/HHH-1902
*/
sortMapForErtekelesLista = new HashMap<String, String>();
sortMapForErtekelesLista.put("csoportNev", "e.csoport.nev ASC");
sortMapForErtekelesLista.put("atlagPont", "col_1_0_ DESC");
sortMapForErtekelesLista.put("kiosztottKDO", "col_2_0_ DESC");
sortMapForErtekelesLista.put("kiosztottKB", "col_3_0_ DESC");
sortMapForErtekelesLista.put("kiosztottAB", "col_4_0_ DESC");
sortMapForErtekelesLista.put("pontStatusz", "e.pontStatusz DESC");
sortMapForErtekelesLista.put("belepoStatusz", "e.belepoStatusz DESC");
}
public void createErtekeles(Ertekeles ertekeles) {
em.persist(ertekeles);
em.flush();
}
public Ertekeles findErtekeles(Csoport csoport, Szemeszter szemeszter) {
Query q = em.createNamedQuery(Ertekeles.findBySzemeszterAndCsoport);
q.setParameter("szemeszter", szemeszter);
q.setParameter("csoport", csoport);
try {
return (Ertekeles) q.getSingleResult();
} catch (NoResultException ignored) {
return null;
}
}
@SuppressWarnings({"unchecked"})
public List<ErtekelesStatisztika> getStatisztikaForErtekelesek(List<Long> ertekelesId) {
String ids = Arrays.toString(ertekelesId.toArray());
ids = ids.substring(1, ids.length() - 1);
Query q = em.createQuery(statisztikaQuery + "WHERE e.id in (" + ids + ")");
return (List<ErtekelesStatisztika>) q.getResultList();
}
public List<ErtekelesStatisztika> findErtekelesStatisztikaForSzemeszter(Szemeszter szemeszter) {
return findErtekelesStatisztikaForSzemeszter(szemeszter, defaultSortColumnForErtekelesLista);
}
@SuppressWarnings({"unchecked"})
public List<ErtekelesStatisztika> findErtekelesStatisztikaForSzemeszter(Szemeszter szemeszter, String sortColumn) {
String sc = sortMapForErtekelesLista.get(sortColumn);
if (sc == null) {
throw new RuntimeException("Az eredményt nem lehet a megadott attribútum alapján rendezni");
}
Query q = em.createQuery(statisztikaQuery + "WHERE e.szemeszter=:szemeszter ORDER BY " + sc);
q.setParameter("szemeszter", systemManager.getSzemeszter());
return (List<ErtekelesStatisztika>) q.getResultList();
}
@SuppressWarnings({"unchecked"})
public List<ErtekelesStatisztika> findElbiralatlanErtekelesStatisztika() {
Query q = em.createQuery(statisztikaQuery + "WHERE e.szemeszter=:szemeszter " +
"AND (e.pontStatusz=:pontStatusz OR e.belepoStatusz=:belepoStatusz)");
q.setParameter("szemeszter", systemManager.getSzemeszter());
q.setParameter("pontStatusz", ErtekelesStatusz.ELBIRALATLAN);
q.setParameter("belepoStatusz", ErtekelesStatusz.ELBIRALATLAN);
return (List<ErtekelesStatisztika>) q.getResultList();
}
protected Ertekeles elbiralastElokeszit(Ertekeles ertekeles, Felhasznalo elbiralo) {
Ertekeles e = findErtekeles(ertekeles.getCsoport(), ertekeles.getSzemeszter());
e.setElbiralo(elbiralo);
e.setUtolsoElbiralas(new Date());
return e;
}
private void PontIgenyElbiral(Ertekeles ertekeles, Felhasznalo elbiralo, boolean elfogad) {
Ertekeles e = elbiralastElokeszit(ertekeles, elbiralo);
if (elfogad) {
e.setPontStatusz(ErtekelesStatusz.ELFOGADVA);
} else {
e.setPontStatusz(ErtekelesStatusz.ELUTASITVA);
}
}
private void BelepoIgenyElbiral(Ertekeles ertekeles, Felhasznalo elbiralo, boolean elfogad) {
Ertekeles e = elbiralastElokeszit(ertekeles, elbiralo);
if (elfogad) {
e.setBelepoStatusz(ErtekelesStatusz.ELFOGADVA);
} else {
e.setBelepoStatusz(ErtekelesStatusz.ELUTASITVA);
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean ErtekeleseketElbiral(Collection<ElbiraltErtekeles> elbiralas, Felhasznalo felhasznalo) {
for (ElbiraltErtekeles ee : elbiralas) {
if ((ee.getPontStatusz().equals(ErtekelesStatusz.ELUTASITVA) ||
ee.getBelepoStatusz().equals(ErtekelesStatusz.ELUTASITVA)) &&
ee.getIndoklas() == null) {
return false;
}
if (ee.getPontStatusz().equals(ErtekelesStatusz.ELFOGADVA) || ee.getPontStatusz().equals(ErtekelesStatusz.ELUTASITVA)) {
PontIgenyElbiral(ee.getErtekeles(), felhasznalo, ee.getPontStatusz().equals(ErtekelesStatusz.ELFOGADVA));
}
if (ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA) || ee.getBelepoStatusz().equals(ErtekelesStatusz.ELUTASITVA)) {
BelepoIgenyElbiral(ee.getErtekeles(), felhasznalo, ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA));
}
if (ee.getIndoklas() != null) {
Uzen(ee.getErtekeles().getId(), felhasznalo, ee.getIndoklas());
}
}
return true;
}
public void Uzen(Long ertekelesId, Felhasznalo uzeno, String uzenetStr) {
Ertekeles ertekeles = em.find(Ertekeles.class, ertekelesId);
ErtekelesUzenet uzenet = new ErtekelesUzenet();
uzenet.setUzenet(uzenetStr);
uzenet.setFelado(uzeno);
uzenet.setDatum(new Date());
uzenet.setErtekeles(ertekeles);
ertekeles.getUzenetek().add(uzenet);
ertekeles.setUtolsoModositas(new Date());
em.persist(uzenet);
em.merge(ertekeles);
}
public Ertekeles getErtekelesWithUzenetek(Long ertekelesId) {
Query q = em.createNamedQuery(Ertekeles.findByIdUzenetJoined);
q.setParameter("id", ertekelesId);
return (Ertekeles) q.getSingleResult();
}
private void add(Ertekeles ertekeles, ErtekelesUzenet ertekelesUzenet) {
//em.refresh(ertekeles);
ertekeles.getUzenetek().add(ertekelesUzenet);
ertekelesUzenet.setErtekeles(ertekeles);
ertekeles.setUtolsoModositas(new Date());
em.persist(ertekelesUzenet);
}
private void add(Ertekeles ertekeles, BelepoIgeny belepoIgeny) {
//em.refresh(ertekeles);
ertekeles.getBelepoIgenyek().add(belepoIgeny);
belepoIgeny.setErtekeles(ertekeles);
ertekeles.setUtolsoModositas(new Date());
em.persist(belepoIgeny);
}
private void add(Ertekeles ertekeles, PontIgeny pontIgeny) {
//em.refresh(ertekeles);
ertekeles.getPontIgenyek().add(pontIgeny);
pontIgeny.setErtekeles(ertekeles);
ertekeles.setUtolsoModositas(new Date());
em.persist(pontIgeny);
}
@SuppressWarnings({"unchecked"})
public List<Ertekeles> findErtekeles(Csoport csoport) {
Query q = em.createNamedQuery(Ertekeles.findByCsoport);
q.setParameter("csoport", csoport);
return (List<Ertekeles>) q.getResultList();
}
public void ujErtekeles(Csoport csoport, Felhasznalo felado, String szovegesErtekeles) {
Ertekeles e = new Ertekeles();
e.setFelado(felado);
try {
e.setSzemeszter(systemManager.getSzemeszter());
} catch (NoSuchAttributeException ex) {
throw new RuntimeException("Fatális hiba: szemeszter nincs beállítva?!", ex);
}
e.setCsoport(csoport);
e.setSzovegesErtekeles(szovegesErtekeles);
//TODO csoport flag alapján van-e joga rá?!
em.persist(e);
}
public boolean isErtekelesLeadhato(Csoport csoport) {
try {
if (systemManager.getErtekelesIdoszak() !=
ErtekelesIdoszak.ERTEKELESLEADAS) {
return false;
}
// leadási időszakban akkor adhat le, ha még nem adott le
Ertekeles e = findErtekeles(csoport, systemManager.getSzemeszter());
if (e == null) {
return true;
}
} catch (NoSuchAttributeException ex) {
}
return false;
}
public void ujErtekelesUzenet(Long ertekelesId, Felhasznalo felado, String uzenet) {
Ertekeles e = findErtekelesById(ertekelesId);
ErtekelesUzenet uz = new ErtekelesUzenet();
uz.setFelado(felado);
uz.setUzenet(uzenet);
add(e, uz);
}
public void pontIgenyekLeadasa(Long ertekelesId, List<PontIgeny> igenyek) {
Ertekeles ertekeles = findErtekelesById(ertekelesId);
if (ertekeles.getPontStatusz().equals(ErtekelesStatusz.ELFOGADVA)) {
throw new RuntimeException("Elfogadott értékelésen nem változtathat");
}
for (PontIgeny igeny : igenyek) {
if (igeny.getErtekeles() == null) { //Új
add(ertekeles, igeny);
} else { //módosítás
PontIgeny ig = em.find(PontIgeny.class, igeny.getId());
ig.setPont(igeny.getPont());
}
}
ertekeles.setPontStatusz(ErtekelesStatusz.ELBIRALATLAN);
ertekeles.setUtolsoModositas(new Date());
}
public boolean belepoIgenyekLeadasa(Long ertekelesId, List<BelepoIgeny> igenyek) {
Ertekeles ertekeles = findErtekelesById(ertekelesId);
if (ertekeles.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA)) {
throw new RuntimeException("Elfogadott értékelésen nem változtathat");
}
for (BelepoIgeny igeny : igenyek) {
if ((igeny.getBelepotipus().equals(BelepoTipus.AB) ||
igeny.getBelepotipus().equals(BelepoTipus.KB)) &&
(igeny.getSzovegesErtekeles() == null)) {
return false;
}
}
for (BelepoIgeny igeny : igenyek) {
if (igeny.getErtekeles() == null) { //új
add(ertekeles, igeny);
} else { //módosítás
BelepoIgeny ig = em.find(BelepoIgeny.class, igeny.getId());
ig.setBelepotipus(igeny.getBelepotipus());
if (ig.getBelepotipus() != BelepoTipus.KDO) {
ig.setSzovegesErtekeles(igeny.getSzovegesErtekeles());
} else {
ig.setSzovegesErtekeles(null);
}
}
}
ertekeles.setBelepoStatusz(ErtekelesStatusz.ELBIRALATLAN);
ertekeles.setUtolsoModositas(new Date());
return true;
}
public Ertekeles findErtekelesById(Long ertekelesId) {
return em.find(Ertekeles.class, ertekelesId);
}
@SuppressWarnings({"unchecked"})
public List<BelepoIgeny> findBelepoIgenyekForErtekeles(Long ertekelesId) {
Query q = em.createQuery("SELECT i FROM BelepoIgeny i JOIN FETCH i.felhasznalo " +
"JOIN i.ertekeles WHERE i.ertekeles.id=:ertekelesId " +
"ORDER BY i.felhasznalo.vezeteknev ASC, i.felhasznalo.keresztnev ASC");
q.setParameter("ertekelesId", ertekelesId);
return q.getResultList();
}
@SuppressWarnings({"unchecked"})
public List<PontIgeny> findPontIgenyekForErtekeles(Long ertekelesId) {
Query q = em.createQuery("SELECT i FROM PontIgeny i JOIN FETCH i.felhasznalo " +
"JOIN i.ertekeles WHERE i.ertekeles.id=:ertekelesId " +
"ORDER BY i.felhasznalo.vezeteknev ASC, i.felhasznalo.keresztnev ASC");
q.setParameter("ertekelesId", ertekelesId);
return q.getResultList();
}
public List<ElfogadottBelepo> findElfogadottBelepoIgenyekForSzemeszter(Szemeszter szemeszter) {
Query q = em.createQuery("SELECT new hu.sch.domain.ElfogadottBelepo(i.felhasznalo.neptunkod," +
"i.belepotipus) FROM BelepoIgeny i " +
"WHERE i.ertekeles.szemeszter = :szemeszter AND i.ertekeles.belepoStatusz=:statusz");
q.setParameter("statusz", ErtekelesStatusz.ELBIRALATLAN);
q.setParameter("szemeszter", szemeszter);
return q.getResultList();
}
}
| sch-kp-ejb-impl/src/main/java/hu/sch/kp/ejb/ErtekelesManagerBean.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hu.sch.kp.ejb;
import hu.sch.domain.BelepoIgeny;
import hu.sch.domain.BelepoTipus;
import hu.sch.domain.ElbiraltErtekeles;
import hu.sch.domain.Ertekeles;
import hu.sch.domain.ErtekelesStatusz;
import hu.sch.domain.ErtekelesUzenet;
import hu.sch.domain.PontIgeny;
import hu.sch.domain.Szemeszter;
import hu.sch.domain.Csoport;
import hu.sch.domain.ElfogadottBelepo;
import hu.sch.domain.ErtekelesIdoszak;
import hu.sch.domain.ErtekelesStatisztika;
import hu.sch.domain.Felhasznalo;
import hu.sch.kp.services.ErtekelesManagerLocal;
import hu.sch.kp.services.SystemManagerLocal;
import hu.sch.kp.services.UserManagerLocal;
import hu.sch.kp.services.exceptions.NoSuchAttributeException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author hege
*/
@Stateless
public class ErtekelesManagerBean implements ErtekelesManagerLocal {
private static final String defaultSortColumnForErtekelesLista = "csoportNev";
private static final Map<String, String> sortMapForErtekelesLista;
private static final String statisztikaQuery = "SELECT new hu.sch.domain.ErtekelesStatisztika(e, " + "(SELECT avg(p.pont) FROM PontIgeny p WHERE p.ertekeles = e AND p.pont > 0) as atlagpont, " + "(SELECT count(*) as numKDO FROM BelepoIgeny as b WHERE b.ertekeles = e AND b.belepotipus=\'KDO\') as igenyeltkdo, " + "(SELECT count(*) as numKB FROM BelepoIgeny as b WHERE b.ertekeles = e AND b.belepotipus=\'KB\') as igenyeltkb, " + "(SELECT count(*) as numAB FROM BelepoIgeny as b WHERE b.ertekeles = e AND b.belepotipus=\'AB\') as igenyeltab" + ") FROM Ertekeles e ";
@PersistenceContext
EntityManager em;
@EJB
UserManagerLocal userManager;
@EJB
SystemManagerLocal systemManager;
static {
/* Hibernate BUG:
* http://opensource.atlassian.com/projects/hibernate/browse/HHH-1902
*/
sortMapForErtekelesLista = new HashMap<String, String>();
sortMapForErtekelesLista.put("csoportNev", "e.csoport.nev ASC");
sortMapForErtekelesLista.put("atlagPont", "col_1_0_ DESC");
sortMapForErtekelesLista.put("kiosztottKDO", "col_2_0_ DESC");
sortMapForErtekelesLista.put("kiosztottKB", "col_3_0_ DESC");
sortMapForErtekelesLista.put("kiosztottAB", "col_4_0_ DESC");
sortMapForErtekelesLista.put("pontStatusz", "e.pontStatusz DESC");
sortMapForErtekelesLista.put("belepoStatusz", "e.belepoStatusz DESC");
}
public void createErtekeles(Ertekeles ertekeles) {
em.persist(ertekeles);
em.flush();
}
public Ertekeles findErtekeles(Csoport csoport, Szemeszter szemeszter) {
Query q = em.createNamedQuery(Ertekeles.findBySzemeszterAndCsoport);
q.setParameter("szemeszter", szemeszter);
q.setParameter("csoport", csoport);
try {
return (Ertekeles) q.getSingleResult();
} catch (NoResultException ignored) {
return null;
}
}
@SuppressWarnings({"unchecked"})
public List<ErtekelesStatisztika> getStatisztikaForErtekelesek(List<Long> ertekelesId) {
String ids = Arrays.toString(ertekelesId.toArray());
ids = ids.substring(1, ids.length() - 1);
Query q = em.createQuery(statisztikaQuery + "WHERE e.id in (" + ids + ")");
return (List<ErtekelesStatisztika>) q.getResultList();
}
public List<ErtekelesStatisztika> findErtekelesStatisztikaForSzemeszter(Szemeszter szemeszter) {
return findErtekelesStatisztikaForSzemeszter(szemeszter, defaultSortColumnForErtekelesLista);
}
@SuppressWarnings({"unchecked"})
public List<ErtekelesStatisztika> findErtekelesStatisztikaForSzemeszter(Szemeszter szemeszter, String sortColumn) {
String sc = sortMapForErtekelesLista.get(sortColumn);
if (sc == null) {
throw new RuntimeException("Az eredményt nem lehet a megadott attribútum alapján rendezni");
}
Query q = em.createQuery(statisztikaQuery + "WHERE e.szemeszter=:szemeszter ORDER BY " + sc);
q.setParameter("szemeszter", systemManager.getSzemeszter());
return (List<ErtekelesStatisztika>) q.getResultList();
}
@SuppressWarnings({"unchecked"})
public List<ErtekelesStatisztika> findElbiralatlanErtekelesStatisztika() {
Query q = em.createQuery(statisztikaQuery + "WHERE e.szemeszter=:szemeszter " +
"AND (e.pontStatusz=:pontStatusz OR e.belepoStatusz=:belepoStatusz)");
q.setParameter("szemeszter", systemManager.getSzemeszter());
q.setParameter("pontStatusz", ErtekelesStatusz.ELBIRALATLAN);
q.setParameter("belepoStatusz", ErtekelesStatusz.ELBIRALATLAN);
return (List<ErtekelesStatisztika>) q.getResultList();
}
protected Ertekeles elbiralastElokeszit(Ertekeles ertekeles, Felhasznalo elbiralo) {
Ertekeles e = findErtekeles(ertekeles.getCsoport(), ertekeles.getSzemeszter());
e.setElbiralo(elbiralo);
e.setUtolsoElbiralas(new Date());
return e;
}
private void PontIgenyElbiral(Ertekeles ertekeles, Felhasznalo elbiralo, boolean elfogad) {
Ertekeles e = elbiralastElokeszit(ertekeles, elbiralo);
if (elfogad) {
e.setPontStatusz(ErtekelesStatusz.ELFOGADVA);
} else {
e.setPontStatusz(ErtekelesStatusz.ELUTASITVA);
}
}
private void BelepoIgenyElbiral(Ertekeles ertekeles, Felhasznalo elbiralo, boolean elfogad) {
Ertekeles e = elbiralastElokeszit(ertekeles, elbiralo);
if (elfogad) {
e.setBelepoStatusz(ErtekelesStatusz.ELFOGADVA);
} else {
e.setBelepoStatusz(ErtekelesStatusz.ELUTASITVA);
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public boolean ErtekeleseketElbiral(Collection<ElbiraltErtekeles> elbiralas, Felhasznalo felhasznalo) {
for (ElbiraltErtekeles ee : elbiralas) {
if ((ee.getPontStatusz().equals(ErtekelesStatusz.ELUTASITVA) ||
ee.getBelepoStatusz().equals(ErtekelesStatusz.ELUTASITVA)) &&
ee.getIndoklas() == null) {
return false;
}
if (ee.getPontStatusz().equals(ErtekelesStatusz.ELFOGADVA) || ee.getPontStatusz().equals(ErtekelesStatusz.ELUTASITVA)) {
PontIgenyElbiral(ee.getErtekeles(), felhasznalo, ee.getPontStatusz().equals(ErtekelesStatusz.ELFOGADVA));
}
if (ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA) || ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA)) {
BelepoIgenyElbiral(ee.getErtekeles(), felhasznalo, ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA));
}
if (ee.getIndoklas() != null) {
Uzen(ee.getErtekeles().getId(), felhasznalo, ee.getIndoklas());
}
}
return true;
}
public void Uzen(Long ertekelesId, Felhasznalo uzeno, String uzenetStr) {
Ertekeles ertekeles = em.find(Ertekeles.class, ertekelesId);
ErtekelesUzenet uzenet = new ErtekelesUzenet();
uzenet.setUzenet(uzenetStr);
uzenet.setFelado(uzeno);
uzenet.setDatum(new Date());
uzenet.setErtekeles(ertekeles);
ertekeles.getUzenetek().add(uzenet);
ertekeles.setUtolsoModositas(new Date());
em.persist(uzenet);
em.merge(ertekeles);
}
public Ertekeles getErtekelesWithUzenetek(Long ertekelesId) {
Query q = em.createNamedQuery(Ertekeles.findByIdUzenetJoined);
q.setParameter("id", ertekelesId);
return (Ertekeles) q.getSingleResult();
}
private void add(Ertekeles ertekeles, ErtekelesUzenet ertekelesUzenet) {
//em.refresh(ertekeles);
ertekeles.getUzenetek().add(ertekelesUzenet);
ertekelesUzenet.setErtekeles(ertekeles);
ertekeles.setUtolsoModositas(new Date());
em.persist(ertekelesUzenet);
}
private void add(Ertekeles ertekeles, BelepoIgeny belepoIgeny) {
//em.refresh(ertekeles);
ertekeles.getBelepoIgenyek().add(belepoIgeny);
belepoIgeny.setErtekeles(ertekeles);
ertekeles.setUtolsoModositas(new Date());
em.persist(belepoIgeny);
}
private void add(Ertekeles ertekeles, PontIgeny pontIgeny) {
//em.refresh(ertekeles);
ertekeles.getPontIgenyek().add(pontIgeny);
pontIgeny.setErtekeles(ertekeles);
ertekeles.setUtolsoModositas(new Date());
em.persist(pontIgeny);
}
@SuppressWarnings({"unchecked"})
public List<Ertekeles> findErtekeles(Csoport csoport) {
Query q = em.createNamedQuery(Ertekeles.findByCsoport);
q.setParameter("csoport", csoport);
return (List<Ertekeles>) q.getResultList();
}
public void ujErtekeles(Csoport csoport, Felhasznalo felado, String szovegesErtekeles) {
Ertekeles e = new Ertekeles();
e.setFelado(felado);
try {
e.setSzemeszter(systemManager.getSzemeszter());
} catch (NoSuchAttributeException ex) {
throw new RuntimeException("Fatális hiba: szemeszter nincs beállítva?!", ex);
}
e.setCsoport(csoport);
e.setSzovegesErtekeles(szovegesErtekeles);
//TODO csoport flag alapján van-e joga rá?!
em.persist(e);
}
public boolean isErtekelesLeadhato(Csoport csoport) {
try {
if (systemManager.getErtekelesIdoszak() !=
ErtekelesIdoszak.ERTEKELESLEADAS) {
return false;
}
// leadási időszakban akkor adhat le, ha még nem adott le
Ertekeles e = findErtekeles(csoport, systemManager.getSzemeszter());
if (e == null) {
return true;
}
} catch (NoSuchAttributeException ex) {
}
return false;
}
public void ujErtekelesUzenet(Long ertekelesId, Felhasznalo felado, String uzenet) {
Ertekeles e = findErtekelesById(ertekelesId);
ErtekelesUzenet uz = new ErtekelesUzenet();
uz.setFelado(felado);
uz.setUzenet(uzenet);
add(e, uz);
}
public void pontIgenyekLeadasa(Long ertekelesId, List<PontIgeny> igenyek) {
Ertekeles ertekeles = findErtekelesById(ertekelesId);
if (ertekeles.getPontStatusz().equals(ErtekelesStatusz.ELFOGADVA)) {
throw new RuntimeException("Elfogadott értékelésen nem változtathat");
}
for (PontIgeny igeny : igenyek) {
if (igeny.getErtekeles() == null) { //Új
add(ertekeles, igeny);
} else { //módosítás
PontIgeny ig = em.find(PontIgeny.class, igeny.getId());
ig.setPont(igeny.getPont());
}
}
ertekeles.setPontStatusz(ErtekelesStatusz.ELBIRALATLAN);
ertekeles.setUtolsoModositas(new Date());
}
public boolean belepoIgenyekLeadasa(Long ertekelesId, List<BelepoIgeny> igenyek) {
Ertekeles ertekeles = findErtekelesById(ertekelesId);
if (ertekeles.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA)) {
throw new RuntimeException("Elfogadott értékelésen nem változtathat");
}
for (BelepoIgeny igeny : igenyek) {
if ((igeny.getBelepotipus().equals(BelepoTipus.AB) ||
igeny.getBelepotipus().equals(BelepoTipus.KB)) &&
(igeny.getSzovegesErtekeles() == null)) {
return false;
}
}
for (BelepoIgeny igeny : igenyek) {
if (igeny.getErtekeles() == null) { //új
add(ertekeles, igeny);
} else { //módosítás
BelepoIgeny ig = em.find(BelepoIgeny.class, igeny.getId());
ig.setBelepotipus(igeny.getBelepotipus());
if (ig.getBelepotipus() != BelepoTipus.KDO) {
ig.setSzovegesErtekeles(igeny.getSzovegesErtekeles());
} else {
ig.setSzovegesErtekeles(null);
}
}
}
ertekeles.setBelepoStatusz(ErtekelesStatusz.ELBIRALATLAN);
ertekeles.setUtolsoModositas(new Date());
return true;
}
public Ertekeles findErtekelesById(Long ertekelesId) {
return em.find(Ertekeles.class, ertekelesId);
}
@SuppressWarnings({"unchecked"})
public List<BelepoIgeny> findBelepoIgenyekForErtekeles(Long ertekelesId) {
Query q = em.createQuery("SELECT i FROM BelepoIgeny i JOIN FETCH i.felhasznalo " +
"JOIN i.ertekeles WHERE i.ertekeles.id=:ertekelesId " +
"ORDER BY i.felhasznalo.vezeteknev ASC, i.felhasznalo.keresztnev ASC");
q.setParameter("ertekelesId", ertekelesId);
return q.getResultList();
}
@SuppressWarnings({"unchecked"})
public List<PontIgeny> findPontIgenyekForErtekeles(Long ertekelesId) {
Query q = em.createQuery("SELECT i FROM PontIgeny i JOIN FETCH i.felhasznalo " +
"JOIN i.ertekeles WHERE i.ertekeles.id=:ertekelesId " +
"ORDER BY i.felhasznalo.vezeteknev ASC, i.felhasznalo.keresztnev ASC");
q.setParameter("ertekelesId", ertekelesId);
return q.getResultList();
}
public List<ElfogadottBelepo> findElfogadottBelepoIgenyekForSzemeszter(Szemeszter szemeszter) {
Query q = em.createQuery("SELECT new hu.sch.domain.ElfogadottBelepo(i.felhasznalo.neptunkod," +
"i.belepotipus) FROM BelepoIgeny i " +
"WHERE i.ertekeles.szemeszter = :szemeszter AND i.ertekeles.belepoStatusz=:statusz");
q.setParameter("statusz", ErtekelesStatusz.ELBIRALATLAN);
q.setParameter("szemeszter", szemeszter);
return q.getResultList();
}
}
| Fixed bug for BelepoErtekeles.
Corresponding ticket:
- #169 - Belépőigénylés elfogadásánál probléma
git-svn-id: 4e071a0e7000adde8431b2b9f8ede30baceca476@636 81257025-f8dc-45f4-8694-d92bdbe95a3d
| sch-kp-ejb-impl/src/main/java/hu/sch/kp/ejb/ErtekelesManagerBean.java | Fixed bug for BelepoErtekeles. | <ide><path>ch-kp-ejb-impl/src/main/java/hu/sch/kp/ejb/ErtekelesManagerBean.java
<ide> if (ee.getPontStatusz().equals(ErtekelesStatusz.ELFOGADVA) || ee.getPontStatusz().equals(ErtekelesStatusz.ELUTASITVA)) {
<ide> PontIgenyElbiral(ee.getErtekeles(), felhasznalo, ee.getPontStatusz().equals(ErtekelesStatusz.ELFOGADVA));
<ide> }
<del> if (ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA) || ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA)) {
<add> if (ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA) || ee.getBelepoStatusz().equals(ErtekelesStatusz.ELUTASITVA)) {
<ide> BelepoIgenyElbiral(ee.getErtekeles(), felhasznalo, ee.getBelepoStatusz().equals(ErtekelesStatusz.ELFOGADVA));
<ide> }
<ide> if (ee.getIndoklas() != null) { |
|
Java | apache-2.0 | a9a41aaad44fb2b8ff3d505984a2f52411d226ac | 0 | mizdebsk/maven,olamy/maven,lbndev/maven,josephw/maven,atanasenko/maven,pkozelka/maven,stephenc/maven,keith-turner/maven,apache/maven,ChristianSchulte/maven,pkozelka/maven,skitt/maven,gorcz/maven,runepeter/maven-deploy-plugin-2.8.1,vedmishr/demo1,wangyuesong/maven,atanasenko/maven,mizdebsk/maven,skitt/maven,keith-turner/maven,gorcz/maven,xasx/maven,barthel/maven,keith-turner/maven,apache/maven,Tibor17/maven,wangyuesong0/maven,kidaa/maven-1,wangyuesong/maven,wangyuesong/maven,wangyuesong0/maven,aheritier/maven,runepeter/maven-deploy-plugin-2.8.1,pkozelka/maven,lbndev/maven,trajano/maven,dsyer/maven,vedmishr/demo1,likaiwalkman/maven,karthikjaps/maven,wangyuesong0/maven,Mounika-Chirukuri/maven,barthel/maven,josephw/maven,olamy/maven,changbai1980/maven,karthikjaps/maven,Distrotech/maven,rogerchina/maven,aheritier/maven,xasx/maven,Distrotech/maven,dsyer/maven,njuneau/maven,lbndev/maven,mcculls/maven,stephenc/maven,kidaa/maven-1,skitt/maven,rogerchina/maven,stephenc/maven,mizdebsk/maven,atanasenko/maven,Mounika-Chirukuri/maven,trajano/maven,xasx/maven,vedmishr/demo1,barthel/maven,kidaa/maven-1,cstamas/maven,dsyer/maven,likaiwalkman/maven,cstamas/maven,mcculls/maven,trajano/maven,cstamas/maven,njuneau/maven,gorcz/maven,Mounika-Chirukuri/maven,aheritier/maven,likaiwalkman/maven,karthikjaps/maven,josephw/maven,njuneau/maven,changbai1980/maven,mcculls/maven,ChristianSchulte/maven,olamy/maven,Tibor17/maven,apache/maven,ChristianSchulte/maven,rogerchina/maven,changbai1980/maven | package org.apache.maven.plugin.idea;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* 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 org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractPlugin;
import org.apache.maven.plugin.PluginExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.util.xml.Xpp3DomBuilder;
import org.codehaus.plexus.util.xml.Xpp3DomWriter;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Iterator;
/**
* @goal idea
* @requiresDependencyResolution test
* @description Goal for generating IDEA files from a POM
* @parameter name="project"
* type="org.apache.maven.project.MavenProject"
* required="true"
* validator=""
* expression="#project"
* description=""
* @todo use dom4j or something. Xpp3Dom can't cope properly with entities and so on
*/
public class IdeaMojo
extends AbstractPlugin
{
private MavenProject project;
public void execute()
throws PluginExecutionException
{
rewriteModule();
rewriteProject();
rewriteWorkspace();
}
private void rewriteWorkspace()
throws PluginExecutionException
{
File workspaceFile = new File( project.getBasedir(), project.getArtifactId() + ".iws" );
if ( !workspaceFile.exists() )
{
FileWriter w = null;
try
{
w = new FileWriter( workspaceFile );
IOUtil.copy( getClass().getResourceAsStream( "/templates/default/workspace.xml" ), w );
}
catch ( IOException e )
{
throw new PluginExecutionException( "Unable to create workspace file", e );
}
finally
{
IOUtil.close( w );
}
}
}
private void rewriteProject()
throws PluginExecutionException
{
try
{
File projectFile = new File( project.getBasedir(), project.getArtifactId() + ".ipr" );
Reader reader;
if ( projectFile.exists() )
{
reader = new FileReader( projectFile );
}
else
{
reader = new InputStreamReader( getClass().getResourceAsStream( "/templates/default/project.xml" ) );
}
Xpp3Dom module;
try
{
module = Xpp3DomBuilder.build( reader );
}
finally
{
IOUtil.close( reader );
}
Xpp3Dom component = findComponent( module, "ProjectModuleManager" );
Xpp3Dom modules = findElement( component, "modules" );
removeOldElements( modules, "module" );
for ( Iterator i = project.getCollectedProjects().iterator(); i.hasNext(); )
{
MavenProject p = (MavenProject) i.next();
Xpp3Dom m = createElement( modules, "module" );
String modulePath = new File( p.getBasedir(), p.getArtifactId() + ".iml" ).getAbsolutePath();
m.setAttribute( "filepath", "$PROJECT_DIR$/" + toRelative( project.getBasedir(), modulePath ) );
}
FileWriter writer = new FileWriter( projectFile );
try
{
Xpp3DomWriter.write( writer, module );
}
finally
{
IOUtil.close( writer );
}
}
catch ( XmlPullParserException e )
{
throw new PluginExecutionException( "Error parsing existing IML file", e );
}
catch ( IOException e )
{
throw new PluginExecutionException( "Error parsing existing IML file", e );
}
}
private void rewriteModule()
throws PluginExecutionException
{
try
{
File moduleFile = new File( project.getBasedir(), project.getArtifactId() + ".iml" );
Reader reader;
if ( moduleFile.exists() )
{
reader = new FileReader( moduleFile );
}
else
{
reader = new InputStreamReader( getClass().getResourceAsStream( "/templates/default/module.xml" ) );
}
Xpp3Dom module;
try
{
module = Xpp3DomBuilder.build( reader );
}
finally
{
IOUtil.close( reader );
}
// TODO: how can we let the WAR/EJBs plugin hook in and provide this?
// TODO: merge in ejb-module, etc.
if ( project.getPackaging().equals( "war" ) )
{
addWebModule( module );
}
else if ( project.getPackaging().equals( "ejb" ) )
{
module.setAttribute( "type", "J2EE_EJB_MODULE" );
}
Xpp3Dom component = findComponent( module, "NewModuleRootManager" );
Xpp3Dom output = findElement( component, "output" );
output.setAttribute( "url", getModuleFileUrl( project.getBuild().getOutputDirectory() ) );
Xpp3Dom outputTest = findElement( component, "output-test" );
outputTest.setAttribute( "url", getModuleFileUrl( project.getBuild().getTestOutputDirectory() ) );
Xpp3Dom content = findElement( component, "content" );
removeOldElements( content, "sourceFolder" );
for ( Iterator i = project.getCompileSourceRoots().iterator(); i.hasNext(); )
{
String directory = (String) i.next();
addSourceFolder( content, directory, false );
}
for ( Iterator i = project.getTestCompileSourceRoots().iterator(); i.hasNext(); )
{
String directory = (String) i.next();
addSourceFolder( content, directory, true );
}
for ( Iterator i = project.getBuild().getResources().iterator(); i.hasNext(); )
{
Resource resource = (Resource) i.next();
String directory = resource.getDirectory();
addSourceFolder( content, directory, false );
}
for ( Iterator i = project.getBuild().getTestResources().iterator(); i.hasNext(); )
{
Resource resource = (Resource) i.next();
String directory = resource.getDirectory();
addSourceFolder( content, directory, true );
}
removeOldDependencies( component );
// Must loop artifacts, not dependencies to resolve transitivity
for ( Iterator i = project.getArtifacts().iterator(); i.hasNext(); )
{
Artifact a = (Artifact) i.next();
// TODO: resolve projects in reactor as references
Xpp3Dom dep = createElement( component, "orderEntry" );
dep.setAttribute( "type", "module-library" );
dep = createElement( dep, "library" );
dep.setAttribute( "name", a.getArtifactId() );
Xpp3Dom el = createElement( dep, "CLASSES" );
el = createElement( el, "root" );
el.setAttribute( "url", "jar://" + a.getFile().getAbsolutePath().replace( '\\', '/' ) + "!/" );
createElement( dep, "JAVADOC" );
createElement( dep, "SOURCES" );
}
FileWriter writer = new FileWriter( moduleFile );
try
{
Xpp3DomWriter.write( writer, module );
}
finally
{
IOUtil.close( writer );
}
}
catch ( XmlPullParserException e )
{
throw new PluginExecutionException( "Error parsing existing IML file", e );
}
catch ( IOException e )
{
throw new PluginExecutionException( "Error parsing existing IML file", e );
}
}
private void addWebModule( Xpp3Dom module )
{
// TODO: this is bad - reproducing war plugin defaults, etc!
// --> this is where the OGNL out of a plugin would be helpful as we could run package first and
// grab stuff from the mojo
/*
Can't run this anyway as Xpp3Dom is in both classloaders...
Xpp3Dom configuration = project.getGoalConfiguration( "maven-war-plugin", "war" );
String warWebapp = configuration.getChild( "webappDirectory" ).getValue();
if ( warWebapp == null )
{
warWebapp = project.getBuild().getDirectory() + "/" + project.getArtifactId();
}
String warSrc = configuration.getChild( "warSrc" ).getValue();
if ( warSrc == null )
{
warSrc = "src/main/webapp";
}
String webXml = configuration.getChild( "webXml" ).getValue();
if ( webXml == null )
{
webXml = warSrc + "/WEB-INF/web.xml";
}
*/
String warWebapp = project.getBuild().getDirectory() + "/" + project.getArtifactId();
String warSrc = "src/main/webapp";
String webXml = warSrc + "/WEB-INF/web.xml";
module.setAttribute( "type", "J2EE_WEB_MODULE" );
Xpp3Dom component = findComponent( module, "WebModuleBuildComponent" );
Xpp3Dom setting = findSetting( component, "EXPLODED_URL" );
setting.setAttribute( "value", getModuleFileUrl( warWebapp ) );
component = findComponent( module, "WebModuleProperties" );
Xpp3Dom element = findElement( component, "deploymentDescriptor" );
if ( element.getAttribute( "version" ) == null )
{
// TODO: should derive from web.xml - does IDEA do this if omitted?
// element.setAttribute( "version", "2.3" );
}
if ( element.getAttribute( "name" ) == null )
{
element.setAttribute( "name", "web.xml" );
}
element.setAttribute( "url", getModuleFileUrl( webXml ) );
element = findElement( component, "webroots" );
removeOldElements( element, "root" );
element = createElement( element, "root" );
element.setAttribute( "relative", "/" );
element.setAttribute( "url", getModuleFileUrl( warSrc ) );
}
private void addSourceFolder( Xpp3Dom content, String directory, boolean isTest )
{
if ( !StringUtils.isEmpty( directory ) && new File( directory ).isDirectory() )
{
Xpp3Dom sourceFolder = createElement( content, "sourceFolder" );
sourceFolder.setAttribute( "url", getModuleFileUrl( directory ) );
sourceFolder.setAttribute( "isTestSource", Boolean.toString( isTest ) );
}
}
// TODO: to FileUtils
private static String toRelative( File basedir, String absolutePath )
{
String relative;
if ( absolutePath.startsWith( basedir.getAbsolutePath() ) )
{
relative = absolutePath.substring( basedir.getAbsolutePath().length() + 1 );
}
else
{
relative = absolutePath;
}
relative = StringUtils.replace( relative, "\\", "/" );
return relative;
}
private String getModuleFileUrl( String file )
{
return "file://$MODULE_DIR$/" + toRelative( project.getBasedir(), file );
}
// TODO: some xpath may actually be more appropriate here
private void removeOldElements( Xpp3Dom content, String name )
{
Xpp3Dom[] children = content.getChildren();
for ( int i = children.length - 1; i >= 0; i-- )
{
Xpp3Dom child = children[i];
if ( child.getName().equals( name ) )
{
content.removeChild( i );
}
}
}
private void removeOldDependencies( Xpp3Dom component )
{
Xpp3Dom[] children = component.getChildren();
for ( int i = children.length - 1; i >= 0; i-- )
{
Xpp3Dom child = children[i];
if ( child.getName().equals( "orderEntry" ) && child.getAttribute( "type" ).equals( "module-library" ) )
{
component.removeChild( i );
}
}
}
private Xpp3Dom findComponent( Xpp3Dom module, String name )
{
Xpp3Dom[] components = module.getChildren( "component" );
for ( int i = 0; i < components.length; i++ )
{
if ( name.equals( components[i].getAttribute( "name" ) ) )
{
return components[i];
}
}
Xpp3Dom component = createElement( module, "component" );
component.setAttribute( "name", name );
return component;
}
private Xpp3Dom findSetting( Xpp3Dom component, String name )
{
Xpp3Dom[] settings = component.getChildren( "setting" );
for ( int i = 0; i < settings.length; i++ )
{
if ( name.equals( settings[i].getAttribute( "name" ) ) )
{
return settings[i];
}
}
Xpp3Dom setting = createElement( component, "setting" );
setting.setAttribute( "name", name );
return setting;
}
private static Xpp3Dom createElement( Xpp3Dom module, String name )
{
Xpp3Dom component = new Xpp3Dom( name );
module.addChild( component );
return component;
}
private Xpp3Dom findElement( Xpp3Dom component, String name )
{
Xpp3Dom element = component.getChild( name );
if ( element == null )
{
element = createElement( component, name );
}
return element;
}
}
| maven-plugins/maven-idea-plugin/src/main/java/org/apache/maven/plugin/idea/IdeaMojo.java | package org.apache.maven.plugin.idea;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* 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 org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractPlugin;
import org.apache.maven.plugin.PluginExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.util.xml.Xpp3DomBuilder;
import org.codehaus.plexus.util.xml.Xpp3DomWriter;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Iterator;
/**
* @goal idea
* @requiresDependencyResolution test
* @description Goal for generating IDEA files from a POM
* @parameter name="project"
* type="MavenProject"
* required="true"
* validator=""
* expression="#project"
* description=""
* @todo use dom4j or something. Xpp3Dom can't cope properly with entities and so on
*/
public class IdeaMojo
extends AbstractPlugin
{
private MavenProject project;
public void execute()
throws PluginExecutionException
{
rewriteModule();
rewriteProject();
rewriteWorkspace();
}
private void rewriteWorkspace()
throws PluginExecutionException
{
File workspaceFile = new File( project.getBasedir(), project.getArtifactId() + ".iws" );
if ( !workspaceFile.exists() )
{
FileWriter w = null;
try
{
w = new FileWriter( workspaceFile );
IOUtil.copy( getClass().getResourceAsStream( "/templates/default/workspace.xml" ), w );
}
catch ( IOException e )
{
throw new PluginExecutionException( "Unable to create workspace file", e );
}
finally
{
IOUtil.close( w );
}
}
}
private void rewriteProject()
throws PluginExecutionException
{
try
{
File projectFile = new File( project.getBasedir(), project.getArtifactId() + ".ipr" );
Reader reader;
if ( projectFile.exists() )
{
reader = new FileReader( projectFile );
}
else
{
reader = new InputStreamReader( getClass().getResourceAsStream( "/templates/default/project.xml" ) );
}
Xpp3Dom module;
try
{
module = Xpp3DomBuilder.build( reader );
}
finally
{
IOUtil.close( reader );
}
Xpp3Dom component = findComponent( module, "ProjectModuleManager" );
Xpp3Dom modules = findElement( component, "modules" );
removeOldElements( modules, "module" );
for ( Iterator i = project.getCollectedProjects().iterator(); i.hasNext(); )
{
MavenProject p = (MavenProject) i.next();
Xpp3Dom m = createElement( modules, "module" );
String modulePath = new File( p.getBasedir(), p.getArtifactId() + ".iml" ).getAbsolutePath();
m.setAttribute( "filepath", "$PROJECT_DIR$/" + toRelative( project.getBasedir(), modulePath ) );
}
FileWriter writer = new FileWriter( projectFile );
try
{
Xpp3DomWriter.write( writer, module );
}
finally
{
IOUtil.close( writer );
}
}
catch ( XmlPullParserException e )
{
throw new PluginExecutionException( "Error parsing existing IML file", e );
}
catch ( IOException e )
{
throw new PluginExecutionException( "Error parsing existing IML file", e );
}
}
private void rewriteModule()
throws PluginExecutionException
{
try
{
File moduleFile = new File( project.getBasedir(), project.getArtifactId() + ".iml" );
Reader reader;
if ( moduleFile.exists() )
{
reader = new FileReader( moduleFile );
}
else
{
reader = new InputStreamReader( getClass().getResourceAsStream( "/templates/default/module.xml" ) );
}
Xpp3Dom module;
try
{
module = Xpp3DomBuilder.build( reader );
}
finally
{
IOUtil.close( reader );
}
// TODO: how can we let the WAR/EJBs plugin hook in and provide this?
// TODO: merge in ejb-module, etc.
if ( project.getPackaging().equals( "war" ) )
{
addWebModule( module );
}
else if ( project.getPackaging().equals( "ejb" ) )
{
module.setAttribute( "type", "J2EE_EJB_MODULE" );
}
Xpp3Dom component = findComponent( module, "NewModuleRootManager" );
Xpp3Dom output = findElement( component, "output" );
output.setAttribute( "url", getModuleFileUrl( project.getBuild().getOutputDirectory() ) );
Xpp3Dom outputTest = findElement( component, "output-test" );
outputTest.setAttribute( "url", getModuleFileUrl( project.getBuild().getTestOutputDirectory() ) );
Xpp3Dom content = findElement( component, "content" );
removeOldElements( content, "sourceFolder" );
for ( Iterator i = project.getCompileSourceRoots().iterator(); i.hasNext(); )
{
String directory = (String) i.next();
addSourceFolder( content, directory, false );
}
for ( Iterator i = project.getTestCompileSourceRoots().iterator(); i.hasNext(); )
{
String directory = (String) i.next();
addSourceFolder( content, directory, true );
}
for ( Iterator i = project.getBuild().getResources().iterator(); i.hasNext(); )
{
Resource resource = (Resource) i.next();
String directory = resource.getDirectory();
addSourceFolder( content, directory, false );
}
for ( Iterator i = project.getBuild().getTestResources().iterator(); i.hasNext(); )
{
Resource resource = (Resource) i.next();
String directory = resource.getDirectory();
addSourceFolder( content, directory, true );
}
removeOldDependencies( component );
// Must loop artifacts, not dependencies to resolve transitivity
for ( Iterator i = project.getArtifacts().iterator(); i.hasNext(); )
{
Artifact a = (Artifact) i.next();
// TODO: resolve projects in reactor as references
Xpp3Dom dep = createElement( component, "orderEntry" );
dep.setAttribute( "type", "module-library" );
dep = createElement( dep, "library" );
dep.setAttribute( "name", a.getArtifactId() );
Xpp3Dom el = createElement( dep, "CLASSES" );
el = createElement( el, "root" );
el.setAttribute( "url", "jar://" + a.getFile().getAbsolutePath().replace( '\\', '/' ) + "!/" );
createElement( dep, "JAVADOC" );
createElement( dep, "SOURCES" );
}
FileWriter writer = new FileWriter( moduleFile );
try
{
Xpp3DomWriter.write( writer, module );
}
finally
{
IOUtil.close( writer );
}
}
catch ( XmlPullParserException e )
{
throw new PluginExecutionException( "Error parsing existing IML file", e );
}
catch ( IOException e )
{
throw new PluginExecutionException( "Error parsing existing IML file", e );
}
}
private void addWebModule( Xpp3Dom module )
{
// TODO: this is bad - reproducing war plugin defaults, etc!
// --> this is where the OGNL out of a plugin would be helpful as we could run package first and
// grab stuff from the mojo
/*
Can't run this anyway as Xpp3Dom is in both classloaders...
Xpp3Dom configuration = project.getGoalConfiguration( "maven-war-plugin", "war" );
String warWebapp = configuration.getChild( "webappDirectory" ).getValue();
if ( warWebapp == null )
{
warWebapp = project.getBuild().getDirectory() + "/" + project.getArtifactId();
}
String warSrc = configuration.getChild( "warSrc" ).getValue();
if ( warSrc == null )
{
warSrc = "src/main/webapp";
}
String webXml = configuration.getChild( "webXml" ).getValue();
if ( webXml == null )
{
webXml = warSrc + "/WEB-INF/web.xml";
}
*/
String warWebapp = project.getBuild().getDirectory() + "/" + project.getArtifactId();
String warSrc = "src/main/webapp";
String webXml = warSrc + "/WEB-INF/web.xml";
module.setAttribute( "type", "J2EE_WEB_MODULE" );
Xpp3Dom component = findComponent( module, "WebModuleBuildComponent" );
Xpp3Dom setting = findSetting( component, "EXPLODED_URL" );
setting.setAttribute( "value", getModuleFileUrl( warWebapp ) );
component = findComponent( module, "WebModuleProperties" );
Xpp3Dom element = findElement( component, "deploymentDescriptor" );
if ( element.getAttribute( "version" ) == null )
{
// TODO: should derive from web.xml - does IDEA do this if omitted?
// element.setAttribute( "version", "2.3" );
}
if ( element.getAttribute( "name" ) == null )
{
element.setAttribute( "name", "web.xml" );
}
element.setAttribute( "url", getModuleFileUrl( webXml ) );
element = findElement( component, "webroots" );
removeOldElements( element, "root" );
element = createElement( element, "root" );
element.setAttribute( "relative", "/" );
element.setAttribute( "url", getModuleFileUrl( warSrc ) );
}
private void addSourceFolder( Xpp3Dom content, String directory, boolean isTest )
{
if ( !StringUtils.isEmpty( directory ) && new File( directory ).isDirectory() )
{
Xpp3Dom sourceFolder = createElement( content, "sourceFolder" );
sourceFolder.setAttribute( "url", getModuleFileUrl( directory ) );
sourceFolder.setAttribute( "isTestSource", Boolean.toString( isTest ) );
}
}
// TODO: to FileUtils
private static String toRelative( File basedir, String absolutePath )
{
String relative;
if ( absolutePath.startsWith( basedir.getAbsolutePath() ) )
{
relative = absolutePath.substring( basedir.getAbsolutePath().length() + 1 );
}
else
{
relative = absolutePath;
}
relative = StringUtils.replace( relative, "\\", "/" );
return relative;
}
private String getModuleFileUrl( String file )
{
return "file://$MODULE_DIR$/" + toRelative( project.getBasedir(), file );
}
// TODO: some xpath may actually be more appropriate here
private void removeOldElements( Xpp3Dom content, String name )
{
Xpp3Dom[] children = content.getChildren();
for ( int i = children.length - 1; i >= 0; i-- )
{
Xpp3Dom child = children[i];
if ( child.getName().equals( name ) )
{
content.removeChild( i );
}
}
}
private void removeOldDependencies( Xpp3Dom component )
{
Xpp3Dom[] children = component.getChildren();
for ( int i = children.length - 1; i >= 0; i-- )
{
Xpp3Dom child = children[i];
if ( child.getName().equals( "orderEntry" ) && child.getAttribute( "type" ).equals( "module-library" ) )
{
component.removeChild( i );
}
}
}
private Xpp3Dom findComponent( Xpp3Dom module, String name )
{
Xpp3Dom[] components = module.getChildren( "component" );
for ( int i = 0; i < components.length; i++ )
{
if ( name.equals( components[i].getAttribute( "name" ) ) )
{
return components[i];
}
}
Xpp3Dom component = createElement( module, "component" );
component.setAttribute( "name", name );
return component;
}
private Xpp3Dom findSetting( Xpp3Dom component, String name )
{
Xpp3Dom[] settings = component.getChildren( "setting" );
for ( int i = 0; i < settings.length; i++ )
{
if ( name.equals( settings[i].getAttribute( "name" ) ) )
{
return settings[i];
}
}
Xpp3Dom setting = createElement( component, "setting" );
setting.setAttribute( "name", name );
return setting;
}
private static Xpp3Dom createElement( Xpp3Dom module, String name )
{
Xpp3Dom component = new Xpp3Dom( name );
module.addChild( component );
return component;
}
private Xpp3Dom findElement( Xpp3Dom component, String name )
{
Xpp3Dom element = component.getChild( name );
if ( element == null )
{
element = createElement( component, name );
}
return element;
}
}
| Fix type for MavenProject
git-svn-id: 2c527eb49caa05e19d6b2be874bf74fa9d7ea670@163781 13f79535-47bb-0310-9956-ffa450edef68
| maven-plugins/maven-idea-plugin/src/main/java/org/apache/maven/plugin/idea/IdeaMojo.java | Fix type for MavenProject | <ide><path>aven-plugins/maven-idea-plugin/src/main/java/org/apache/maven/plugin/idea/IdeaMojo.java
<ide> * @requiresDependencyResolution test
<ide> * @description Goal for generating IDEA files from a POM
<ide> * @parameter name="project"
<del> * type="MavenProject"
<add> * type="org.apache.maven.project.MavenProject"
<ide> * required="true"
<ide> * validator=""
<ide> * expression="#project" |
|
JavaScript | mit | cd1b7563aa61577704b673e778ea9e6932fef5dc | 0 | bellenot/jsroot,bellenot/jsroot,root-project/jsroot,linev/jsroot,root-project/jsroot,linev/jsroot,bellenot/jsroot |
function ThreeBSPfactory() {
var ThreeBSP,
EPSILON = 1e-5,
COPLANAR = 0,
FRONT = 1,
BACK = 2,
SPANNING = 3;
ThreeBSP = function( geometry, transfer_matrix ) {
// Convert THREE.Geometry to ThreeBSP
var i, _length_i,
face, vertex, /* faceVertexUvs, uvs, */
polygon,
polygons = [],
tree;
if ( geometry instanceof THREE.Geometry ) {
this.matrix = null; // new THREE.Matrix4; not create matrix when do not needed
} else if ( geometry instanceof THREE.Mesh ) {
// #todo: add hierarchy support
geometry.updateMatrix();
transfer_matrix = this.matrix = geometry.matrix.clone();
geometry = geometry.geometry;
} else if ( geometry instanceof ThreeBSP.Node ) {
this.tree = geometry;
this.matrix = null; // new THREE.Matrix4;
return this;
} else if ( geometry instanceof THREE.BufferGeometry ) {
var pos_buf = geometry.getAttribute('position').array,
norm_buf = geometry.getAttribute('normal').array;
for (var i=0; i < pos_buf.length; i+=9) {
polygon = new ThreeBSP.Polygon;
vertex = new ThreeBSP.Vertex( pos_buf[i], pos_buf[i+1], pos_buf[i+2], new THREE.Vector3(norm_buf[i], norm_buf[i+1], norm_buf[i+2]));
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = new ThreeBSP.Vertex( pos_buf[i+3], pos_buf[i+4], pos_buf[i+5], new THREE.Vector3(norm_buf[i+3], norm_buf[i+4], norm_buf[i+5]));
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = new ThreeBSP.Vertex( pos_buf[i+6], pos_buf[i+7], pos_buf[i+8], new THREE.Vector3(norm_buf[i+6], norm_buf[i+7], norm_buf[i+8]));
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
polygon.calculateProperties();
polygons.push( polygon );
}
this.tree = new ThreeBSP.Node( polygons );
return this;
} else if (geometry.polygons && (geometry.polygons[0] instanceof ThreeBSP.Polygon)) {
polygons = geometry.polygons;
// console.log('create from direct polygons size ' + polygons.length);
for (var i=0;i<polygons.length;++i) {
var polygon = polygons[i];
if (transfer_matrix)
for (var n=0;n<polygon.vertices.length;++n)
polygon.vertices[n].applyMatrix4(transfer_matrix);
polygon.calculateProperties();
}
this.tree = new ThreeBSP.Node( polygons );
return this;
} else {
throw 'ThreeBSP: Given geometry is unsupported';
}
for ( i = 0, _length_i = geometry.faces.length; i < _length_i; i++ ) {
face = geometry.faces[i];
// faceVertexUvs = geometry.faceVertexUvs[0][i];
polygon = new ThreeBSP.Polygon;
if ( face instanceof THREE.Face3 ) {
vertex = geometry.vertices[ face.a ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[0].x, faceVertexUvs[0].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[0] /*face.normal , uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.b ];
//uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[1].x, faceVertexUvs[1].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[1]/*face.normal , uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.c ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[2].x, faceVertexUvs[2].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[2] /*face.normal, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
} else if ( typeof THREE.Face4 ) {
vertex = geometry.vertices[ face.a ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[0].x, faceVertexUvs[0].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[0] /*, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.b ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[1].x, faceVertexUvs[1].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[1] /*, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.c ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[2].x, faceVertexUvs[2].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[2] /*, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.d ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[3].x, faceVertexUvs[3].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[3] /*, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
} else {
throw 'Invalid face type at index ' + i;
}
polygon.calculateProperties();
polygons.push( polygon );
};
this.tree = new ThreeBSP.Node( polygons );
};
ThreeBSP.prototype.subtract = function( other_tree ) {
var a = this.tree.clone(),
b = other_tree.tree.clone();
a.invert();
a.clipTo( b );
b.clipTo( a );
b.invert();
b.clipTo( a );
b.invert();
a.build( b.allPolygons() );
a.invert();
a = new ThreeBSP( a );
a.matrix = this.matrix;
return a;
};
ThreeBSP.prototype.union = function( other_tree ) {
var a = this.tree.clone(),
b = other_tree.tree.clone();
a.clipTo( b );
b.clipTo( a );
b.invert();
b.clipTo( a );
b.invert();
a.build( b.allPolygons() );
a = new ThreeBSP( a );
a.matrix = this.matrix;
return a;
};
ThreeBSP.prototype.intersect = function( other_tree ) {
var a = this.tree.clone(),
b = other_tree.tree.clone();
a.invert();
b.clipTo( a );
b.invert();
a.clipTo( b );
b.clipTo( a );
a.build( b.allPolygons() );
a.invert();
a = new ThreeBSP( a );
a.matrix = this.matrix;
return a;
};
ThreeBSP.prototype.toGeometry = function() {
var i, j,
matrix = this.matrix ? new THREE.Matrix4().getInverse( this.matrix ) : null,
geometry = new THREE.Geometry(),
polygons = this.tree.allPolygons(),
polygon_count = polygons.length,
polygon, polygon_vertice_count,
vertice_dict = {},
vertex_idx_a, vertex_idx_b, vertex_idx_c,
vertex, face;
// verticeUvs;
for ( i = 0; i < polygon_count; i++ ) {
polygon = polygons[i];
polygon_vertice_count = polygon.vertices.length;
for ( j = 2; j < polygon_vertice_count; j++ ) {
// verticeUvs = [];
vertex = polygon.vertices[0];
// verticeUvs.push( new THREE.Vector2( vertex.uv.x, vertex.uv.y ) );
vertex = new THREE.Vector3( vertex.x, vertex.y, vertex.z );
if (matrix) vertex.applyMatrix4(matrix);
if ( typeof vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] !== 'undefined' ) {
vertex_idx_a = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ];
} else {
geometry.vertices.push( vertex );
vertex_idx_a = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] = geometry.vertices.length - 1;
}
vertex = polygon.vertices[j-1];
// verticeUvs.push( new THREE.Vector2( vertex.uv.x, vertex.uv.y ) );
vertex = new THREE.Vector3( vertex.x, vertex.y, vertex.z );
if (matrix) vertex.applyMatrix4(matrix);
if ( typeof vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] !== 'undefined' ) {
vertex_idx_b = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ];
} else {
geometry.vertices.push( vertex );
vertex_idx_b = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] = geometry.vertices.length - 1;
}
vertex = polygon.vertices[j];
// verticeUvs.push( new THREE.Vector2( vertex.uv.x, vertex.uv.y ) );
vertex = new THREE.Vector3( vertex.x, vertex.y, vertex.z );
if (matrix) vertex.applyMatrix4(matrix);
if ( typeof vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] !== 'undefined' ) {
vertex_idx_c = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ];
} else {
geometry.vertices.push( vertex );
vertex_idx_c = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] = geometry.vertices.length - 1;
}
face = new THREE.Face3(
vertex_idx_a,
vertex_idx_b,
vertex_idx_c,
new THREE.Vector3( polygon.normal.x, polygon.normal.y, polygon.normal.z )
);
geometry.faces.push( face );
// geometry.faceVertexUvs[0].push( verticeUvs );
}
}
return geometry;
};
ThreeBSP.prototype.toBufferGeometry = function() {
var i, j,
polygons = this.tree.allPolygons(),
polygon_count = polygons.length,
buf_size = 0;
for ( i = 0; i < polygon_count; ++i ) {
buf_size += (polygons[i].vertices.length - 2) * 9;
}
var positions_buf = new Float32Array(buf_size),
normals_buf = new Float32Array(buf_size),
iii = 0, polygon;
function CopyVertex(vertex) {
positions_buf[iii] = vertex.x;
positions_buf[iii+1] = vertex.y;
positions_buf[iii+2] = vertex.z;
var norm = /*vertex.normal.lengthSq() > 0 ? vertex.normal :*/ polygon.normal;
normals_buf[iii] = norm.x;
normals_buf[iii+1] = norm.y;
normals_buf[iii+2] = norm.z;
iii+=3;
}
for ( i = 0; i < polygon_count; ++i ) {
polygon = polygons[i];
for ( j = 2; j < polygon.vertices.length; ++j ) {
CopyVertex(polygon.vertices[0]);
CopyVertex(polygon.vertices[j-1]);
CopyVertex(polygon.vertices[j]);
}
}
var geometry = new THREE.BufferGeometry();
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions_buf, 3 ) );
geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals_buf, 3 ) );
return geometry;
};
ThreeBSP.prototype.toMesh = function( material ) {
var geometry = this.toGeometry(),
mesh = new THREE.Mesh( geometry, material );
if (this.matrix) {
mesh.position.setFromMatrixPosition( this.matrix );
mesh.rotation.setFromRotationMatrix( this.matrix );
}
return mesh;
};
ThreeBSP.Polygon = function( vertices, normal, w ) {
if ( !( vertices instanceof Array ) ) {
vertices = [];
}
this.vertices = vertices;
if ( vertices.length > 0 ) {
this.calculateProperties();
} else {
this.normal = this.w = undefined;
}
};
ThreeBSP.Polygon.prototype.calculateProperties = function() {
var a = this.vertices[0],
b = this.vertices[1],
c = this.vertices[2];
this.normal = b.clone().subtract( a ).cross(
c.clone().subtract( a )
).normalize();
this.w = this.normal.clone().dot( a );
return this;
};
ThreeBSP.Polygon.prototype.clone = function() {
var i, vertice_count,
polygon = new ThreeBSP.Polygon;
for ( i = 0, vertice_count = this.vertices.length; i < vertice_count; i++ ) {
polygon.vertices.push( this.vertices[i].clone() );
};
polygon.calculateProperties();
return polygon;
};
ThreeBSP.Polygon.prototype.flip = function() {
var i, vertices = [];
this.normal.multiplyScalar( -1 );
this.w *= -1;
for ( i = this.vertices.length - 1; i >= 0; i-- ) {
vertices.push( this.vertices[i] );
};
this.vertices = vertices;
return this;
};
ThreeBSP.Polygon.prototype.classifyVertex = function( vertex ) {
var side_value = this.normal.dot( vertex ) - this.w;
if ( side_value < -EPSILON ) {
return BACK;
} else if ( side_value > EPSILON ) {
return FRONT;
} else {
return COPLANAR;
}
};
ThreeBSP.Polygon.prototype.classifySide = function( polygon ) {
var i, vertex, classification,
num_positive = 0,
num_negative = 0,
vertice_count = polygon.vertices.length;
for ( i = 0; i < vertice_count; i++ ) {
vertex = polygon.vertices[i];
classification = this.classifyVertex( vertex );
if ( classification === FRONT ) {
num_positive++;
} else if ( classification === BACK ) {
num_negative++;
}
}
if ( num_positive > 0 && num_negative === 0 ) {
return FRONT;
} else if ( num_positive === 0 && num_negative > 0 ) {
return BACK;
} else if ( num_positive === 0 && num_negative === 0 ) {
return COPLANAR;
} else {
return SPANNING;
}
};
ThreeBSP.Polygon.prototype.splitPolygon = function( polygon, coplanar_front, coplanar_back, front, back ) {
var classification = this.classifySide( polygon );
if ( classification === COPLANAR ) {
( this.normal.dot( polygon.normal ) > 0 ? coplanar_front : coplanar_back ).push( polygon );
} else if ( classification === FRONT ) {
front.push( polygon );
} else if ( classification === BACK ) {
back.push( polygon );
} else {
var vertice_count,
i, j, ti, tj, vi, vj,
t, v,
f = [],
b = [];
for ( i = 0, vertice_count = polygon.vertices.length; i < vertice_count; i++ ) {
j = (i + 1) % vertice_count;
vi = polygon.vertices[i];
vj = polygon.vertices[j];
ti = this.classifyVertex( vi );
tj = this.classifyVertex( vj );
if ( ti != BACK ) f.push( vi );
if ( ti != FRONT ) b.push( vi );
if ( (ti | tj) === SPANNING ) {
t = ( this.w - this.normal.dot( vi ) ) / this.normal.dot( vj.clone().subtract( vi ) );
v = vi.interpolate( vj, t );
f.push( v );
b.push( v );
}
}
if ( f.length >= 3 ) front.push( new ThreeBSP.Polygon( f ).calculateProperties() );
if ( b.length >= 3 ) back.push( new ThreeBSP.Polygon( b ).calculateProperties() );
}
};
ThreeBSP.Vertex = function( x, y, z, normal /*, uv */ ) {
this.x = x;
this.y = y;
this.z = z;
this.normal = normal || new THREE.Vector3;
// this.uv = uv || new THREE.Vector2;
};
ThreeBSP.Vertex.prototype.clone = function() {
return new ThreeBSP.Vertex( this.x, this.y, this.z, this.normal.clone() /*, this.uv.clone() */ );
};
ThreeBSP.Vertex.prototype.add = function( vertex ) {
this.x += vertex.x;
this.y += vertex.y;
this.z += vertex.z;
return this;
};
ThreeBSP.Vertex.prototype.subtract = function( vertex ) {
this.x -= vertex.x;
this.y -= vertex.y;
this.z -= vertex.z;
return this;
};
ThreeBSP.Vertex.prototype.multiplyScalar = function( scalar ) {
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
return this;
};
ThreeBSP.Vertex.prototype.cross = function( vertex ) {
var x = this.x,
y = this.y,
z = this.z;
this.x = y * vertex.z - z * vertex.y;
this.y = z * vertex.x - x * vertex.z;
this.z = x * vertex.y - y * vertex.x;
return this;
};
ThreeBSP.Vertex.prototype.normalize = function() {
var length = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
this.x /= length;
this.y /= length;
this.z /= length;
return this;
};
ThreeBSP.Vertex.prototype.dot = function( vertex ) {
return this.x * vertex.x + this.y * vertex.y + this.z * vertex.z;
};
ThreeBSP.Vertex.prototype.diff = function( vertex ) {
var dx = (this.x - vertex.x),
dy = (this.y - vertex.y),
dz = (this.z - vertex.z),
len2 = this.x * this.x + this.y * this.y + this.z * this.z;
return (dx*dx+dy*dy+dz*dz) / (len2>0 ? len2 : 1e-10);
};
ThreeBSP.Vertex.prototype.lerp = function( a, t ) {
this.add(
a.clone().subtract( this ).multiplyScalar( t )
);
this.normal.add(
a.normal.clone().sub( this.normal ).multiplyScalar( t )
);
//this.uv.add(
// a.uv.clone().sub( this.uv ).multiplyScalar( t )
//);
return this;
};
ThreeBSP.Vertex.prototype.interpolate = function( other, t ) {
return this.clone().lerp( other, t );
};
ThreeBSP.Vertex.prototype.applyMatrix4 = function ( m ) {
// input: THREE.Matrix4 affine matrix
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
return this;
}
ThreeBSP.Node = function( polygons ) {
var i, polygon_count,
front = [],
back = [];
this.polygons = [];
this.front = this.back = undefined;
if ( !(polygons instanceof Array) || polygons.length === 0 ) return;
this.divider = polygons[0].clone();
// console.log('divider length ' + polygons.length);
for ( i = 0, polygon_count = polygons.length; i < polygon_count; i++ ) {
this.divider.splitPolygon( polygons[i], this.polygons, this.polygons, front, back );
}
// console.log('divider done ' + front.length + ' ' + back.length);
if ( front.length > 0 ) {
this.front = new ThreeBSP.Node( front );
}
if ( back.length > 0 ) {
this.back = new ThreeBSP.Node( back );
}
};
ThreeBSP.Node.isConvex = function( polygons ) {
var i, j;
for ( i = 0; i < polygons.length; i++ ) {
for ( j = 0; j < polygons.length; j++ ) {
if ( i !== j && polygons[i].classifySide( polygons[j] ) !== BACK ) {
return false;
}
}
}
return true;
};
ThreeBSP.Node.prototype.build = function( polygons ) {
var i, polygon_count,
front = [],
back = [];
if ( !this.divider ) {
this.divider = polygons[0].clone();
}
for ( i = 0, polygon_count = polygons.length; i < polygon_count; i++ ) {
this.divider.splitPolygon( polygons[i], this.polygons, this.polygons, front, back );
}
if ( front.length > 0 ) {
if ( !this.front ) this.front = new ThreeBSP.Node();
this.front.build( front );
}
if ( back.length > 0 ) {
if ( !this.back ) this.back = new ThreeBSP.Node();
this.back.build( back );
}
};
ThreeBSP.Node.prototype.allPolygons = function() {
var polygons = this.polygons.slice();
if ( this.front ) polygons = polygons.concat( this.front.allPolygons() );
if ( this.back ) polygons = polygons.concat( this.back.allPolygons() );
return polygons;
};
ThreeBSP.Node.prototype.numPolygons = function() {
var res = this.polygons.length;
if ( this.front ) res += this.front.numPolygons();
if ( this.back ) res += this.back.numPolygons();
return res;
}
ThreeBSP.Node.prototype.clone = function() {
var node = new ThreeBSP.Node();
node.divider = this.divider.clone();
node.polygons = this.polygons.map( function( polygon ) { return polygon.clone(); } );
node.front = this.front && this.front.clone();
node.back = this.back && this.back.clone();
return node;
};
ThreeBSP.Node.prototype.invert = function() {
var i, polygon_count, temp;
for ( i = 0, polygon_count = this.polygons.length; i < polygon_count; i++ ) {
this.polygons[i].flip();
}
this.divider.flip();
if ( this.front ) this.front.invert();
if ( this.back ) this.back.invert();
temp = this.front;
this.front = this.back;
this.back = temp;
return this;
};
ThreeBSP.Node.prototype.clipPolygons = function( polygons ) {
var i, polygon_count,
front, back;
if ( !this.divider ) return polygons.slice();
front = [], back = [];
for ( i = 0, polygon_count = polygons.length; i < polygon_count; i++ ) {
this.divider.splitPolygon( polygons[i], front, back, front, back );
}
if ( this.front ) front = this.front.clipPolygons( front );
if ( this.back ) back = this.back.clipPolygons( back );
else back = [];
return front.concat( back );
};
ThreeBSP.Node.prototype.clipTo = function( node ) {
this.polygons = node.clipPolygons( this.polygons );
if ( this.front ) this.front.clipTo( node );
if ( this.back ) this.back.clipTo( node );
};
return ThreeBSP;
};
if ((typeof document !== "undefined") && (typeof window !== "undefined")) {
window.ThreeBSP = ThreeBSPfactory();
} else {
ThreeBSP = ThreeBSPfactory();
} | scripts/ThreeCSG.js |
function ThreeBSPfactory() {
var ThreeBSP,
EPSILON = 1e-5,
COPLANAR = 0,
FRONT = 1,
BACK = 2,
SPANNING = 3;
ThreeBSP = function( geometry, transfer_matrix ) {
// Convert THREE.Geometry to ThreeBSP
var i, _length_i,
face, vertex, /* faceVertexUvs, uvs, */
polygon,
polygons = [],
tree;
if ( geometry instanceof THREE.Geometry ) {
this.matrix = null; // new THREE.Matrix4; not create matrix when do not needed
} else if ( geometry instanceof THREE.Mesh ) {
// #todo: add hierarchy support
geometry.updateMatrix();
transfer_matrix = this.matrix = geometry.matrix.clone();
geometry = geometry.geometry;
} else if ( geometry instanceof ThreeBSP.Node ) {
this.tree = geometry;
this.matrix = null; // new THREE.Matrix4;
return this;
} else if ( geometry instanceof THREE.BufferGeometry ) {
var pos_buf = geometry.getAttribute('position').array,
norm_buf = geometry.getAttribute('normal').array;
for (var i=0; i < pos_buf.length; i+=9) {
polygon = new ThreeBSP.Polygon;
vertex = new ThreeBSP.Vertex( pos_buf[i], pos_buf[i+1], pos_buf[i+2], new THREE.Vector3(norm_buf[i], norm_buf[i+1], norm_buf[i+2]));
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = new ThreeBSP.Vertex( pos_buf[i+3], pos_buf[i+4], pos_buf[i+5], new THREE.Vector3(norm_buf[i+3], norm_buf[i+4], norm_buf[i+5]));
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = new ThreeBSP.Vertex( pos_buf[i+6], pos_buf[i+7], pos_buf[i+8], new THREE.Vector3(norm_buf[i+6], norm_buf[i+7], norm_buf[i+8]));
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
polygon.calculateProperties();
polygons.push( polygon );
}
this.tree = new ThreeBSP.Node( polygons );
return this;
} else if (geometry.polygons && (geometry.polygons[0] instanceof ThreeBSP.Polygon)) {
polygons = geometry.polygons;
// console.log('create from direct polygons size ' + polygons.length);
for (var i=0;i<polygons.length;++i) {
var polygon = polygons[i];
if (transfer_matrix)
for (var n=0;n<polygon.vertices.length;++n)
polygon.vertices[n].applyMatrix4(transfer_matrix);
polygon.calculateProperties();
}
this.tree = new ThreeBSP.Node( polygons );
return this;
} else {
throw 'ThreeBSP: Given geometry is unsupported';
}
for ( i = 0, _length_i = geometry.faces.length; i < _length_i; i++ ) {
face = geometry.faces[i];
// faceVertexUvs = geometry.faceVertexUvs[0][i];
polygon = new ThreeBSP.Polygon;
if ( face instanceof THREE.Face3 ) {
vertex = geometry.vertices[ face.a ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[0].x, faceVertexUvs[0].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[0] /*face.normal , uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.b ];
//uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[1].x, faceVertexUvs[1].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[1]/*face.normal , uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.c ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[2].x, faceVertexUvs[2].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[2] /*face.normal, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
} else if ( typeof THREE.Face4 ) {
vertex = geometry.vertices[ face.a ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[0].x, faceVertexUvs[0].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[0] /*, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.b ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[1].x, faceVertexUvs[1].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[1] /*, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.c ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[2].x, faceVertexUvs[2].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[2] /*, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
vertex = geometry.vertices[ face.d ];
// uvs = faceVertexUvs ? new THREE.Vector2( faceVertexUvs[3].x, faceVertexUvs[3].y ) : null;
vertex = new ThreeBSP.Vertex( vertex.x, vertex.y, vertex.z, face.vertexNormals[3] /*, uvs */ );
if (transfer_matrix) vertex.applyMatrix4(transfer_matrix);
polygon.vertices.push( vertex );
} else {
throw 'Invalid face type at index ' + i;
}
polygon.calculateProperties();
polygons.push( polygon );
};
this.tree = new ThreeBSP.Node( polygons );
};
ThreeBSP.prototype.subtract = function( other_tree ) {
var a = this.tree.clone(),
b = other_tree.tree.clone();
a.invert();
a.clipTo( b );
b.clipTo( a );
b.invert();
b.clipTo( a );
b.invert();
a.build( b.allPolygons() );
a.invert();
a = new ThreeBSP( a );
a.matrix = this.matrix;
return a;
};
ThreeBSP.prototype.union = function( other_tree ) {
var a = this.tree.clone(),
b = other_tree.tree.clone();
a.clipTo( b );
b.clipTo( a );
b.invert();
b.clipTo( a );
b.invert();
a.build( b.allPolygons() );
a = new ThreeBSP( a );
a.matrix = this.matrix;
return a;
};
ThreeBSP.prototype.intersect = function( other_tree ) {
var a = this.tree.clone(),
b = other_tree.tree.clone();
a.invert();
b.clipTo( a );
b.invert();
a.clipTo( b );
b.clipTo( a );
a.build( b.allPolygons() );
a.invert();
a = new ThreeBSP( a );
a.matrix = this.matrix;
return a;
};
ThreeBSP.prototype.toGeometry = function() {
var i, j,
matrix = this.matrix ? new THREE.Matrix4().getInverse( this.matrix ) : null,
geometry = new THREE.Geometry(),
polygons = this.tree.allPolygons(),
polygon_count = polygons.length,
polygon, polygon_vertice_count,
vertice_dict = {},
vertex_idx_a, vertex_idx_b, vertex_idx_c,
vertex, face;
// verticeUvs;
for ( i = 0; i < polygon_count; i++ ) {
polygon = polygons[i];
polygon_vertice_count = polygon.vertices.length;
for ( j = 2; j < polygon_vertice_count; j++ ) {
// verticeUvs = [];
vertex = polygon.vertices[0];
// verticeUvs.push( new THREE.Vector2( vertex.uv.x, vertex.uv.y ) );
vertex = new THREE.Vector3( vertex.x, vertex.y, vertex.z );
if (matrix) vertex.applyMatrix4(matrix);
if ( typeof vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] !== 'undefined' ) {
vertex_idx_a = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ];
} else {
geometry.vertices.push( vertex );
vertex_idx_a = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] = geometry.vertices.length - 1;
}
vertex = polygon.vertices[j-1];
// verticeUvs.push( new THREE.Vector2( vertex.uv.x, vertex.uv.y ) );
vertex = new THREE.Vector3( vertex.x, vertex.y, vertex.z );
if (matrix) vertex.applyMatrix4(matrix);
if ( typeof vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] !== 'undefined' ) {
vertex_idx_b = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ];
} else {
geometry.vertices.push( vertex );
vertex_idx_b = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] = geometry.vertices.length - 1;
}
vertex = polygon.vertices[j];
// verticeUvs.push( new THREE.Vector2( vertex.uv.x, vertex.uv.y ) );
vertex = new THREE.Vector3( vertex.x, vertex.y, vertex.z );
if (matrix) vertex.applyMatrix4(matrix);
if ( typeof vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] !== 'undefined' ) {
vertex_idx_c = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ];
} else {
geometry.vertices.push( vertex );
vertex_idx_c = vertice_dict[ vertex.x + ',' + vertex.y + ',' + vertex.z ] = geometry.vertices.length - 1;
}
face = new THREE.Face3(
vertex_idx_a,
vertex_idx_b,
vertex_idx_c,
new THREE.Vector3( polygon.normal.x, polygon.normal.y, polygon.normal.z )
);
geometry.faces.push( face );
// geometry.faceVertexUvs[0].push( verticeUvs );
}
}
return geometry;
};
ThreeBSP.prototype.toBufferGeometry = function() {
var i, j,
polygons = this.tree.allPolygons(),
polygon_count = polygons.length,
buf_size = 0;
for ( i = 0; i < polygon_count; ++i ) {
buf_size += (polygons[i].vertices.length - 2) * 9;
}
var positions_buf = new Float32Array(buf_size),
normals_buf = new Float32Array(buf_size),
iii = 0, polygon, vertex;
for ( i = 0; i < polygon_count; ++i ) {
polygon = polygons[i];
for ( j = 2; j < polygon.vertices.length; ++j ) {
vertex = polygon.vertices[0];
positions_buf[iii] = vertex.x;
positions_buf[iii+1] = vertex.y;
positions_buf[iii+2] = vertex.z;
normals_buf[iii] = vertex.normal.x;
normals_buf[iii+1] = vertex.normal.y;
normals_buf[iii+2] = vertex.normal.z;
iii+=3;
vertex = polygon.vertices[j-1];
positions_buf[iii] = vertex.x;
positions_buf[iii+1] = vertex.y;
positions_buf[iii+2] = vertex.z;
normals_buf[iii] = vertex.normal.x;
normals_buf[iii+1] = vertex.normal.y;
normals_buf[iii+2] = vertex.normal.z;
iii+=3;
vertex = polygon.vertices[j];
positions_buf[iii] = vertex.x;
positions_buf[iii+1] = vertex.y;
positions_buf[iii+2] = vertex.z;
normals_buf[iii] = vertex.normal.x;
normals_buf[iii+1] = vertex.normal.y;
normals_buf[iii+2] = vertex.normal.z;
iii+=3;
}
}
var geometry = new THREE.BufferGeometry();
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions_buf, 3 ) );
geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals_buf, 3 ) );
return geometry;
};
ThreeBSP.prototype.toMesh = function( material ) {
var geometry = this.toGeometry(),
mesh = new THREE.Mesh( geometry, material );
if (this.matrix) {
mesh.position.setFromMatrixPosition( this.matrix );
mesh.rotation.setFromRotationMatrix( this.matrix );
}
return mesh;
};
ThreeBSP.Polygon = function( vertices, normal, w ) {
if ( !( vertices instanceof Array ) ) {
vertices = [];
}
this.vertices = vertices;
if ( vertices.length > 0 ) {
this.calculateProperties();
} else {
this.normal = this.w = undefined;
}
};
ThreeBSP.Polygon.prototype.calculateProperties = function() {
var a = this.vertices[0],
b = this.vertices[1],
c = this.vertices[2];
this.normal = b.clone().subtract( a ).cross(
c.clone().subtract( a )
).normalize();
this.w = this.normal.clone().dot( a );
return this;
};
ThreeBSP.Polygon.prototype.clone = function() {
var i, vertice_count,
polygon = new ThreeBSP.Polygon;
for ( i = 0, vertice_count = this.vertices.length; i < vertice_count; i++ ) {
polygon.vertices.push( this.vertices[i].clone() );
};
polygon.calculateProperties();
return polygon;
};
ThreeBSP.Polygon.prototype.flip = function() {
var i, vertices = [];
this.normal.multiplyScalar( -1 );
this.w *= -1;
for ( i = this.vertices.length - 1; i >= 0; i-- ) {
vertices.push( this.vertices[i] );
};
this.vertices = vertices;
return this;
};
ThreeBSP.Polygon.prototype.classifyVertex = function( vertex ) {
var side_value = this.normal.dot( vertex ) - this.w;
if ( side_value < -EPSILON ) {
return BACK;
} else if ( side_value > EPSILON ) {
return FRONT;
} else {
return COPLANAR;
}
};
ThreeBSP.Polygon.prototype.classifySide = function( polygon ) {
var i, vertex, classification,
num_positive = 0,
num_negative = 0,
vertice_count = polygon.vertices.length;
for ( i = 0; i < vertice_count; i++ ) {
vertex = polygon.vertices[i];
classification = this.classifyVertex( vertex );
if ( classification === FRONT ) {
num_positive++;
} else if ( classification === BACK ) {
num_negative++;
}
}
if ( num_positive > 0 && num_negative === 0 ) {
return FRONT;
} else if ( num_positive === 0 && num_negative > 0 ) {
return BACK;
} else if ( num_positive === 0 && num_negative === 0 ) {
return COPLANAR;
} else {
return SPANNING;
}
};
ThreeBSP.Polygon.prototype.splitPolygon = function( polygon, coplanar_front, coplanar_back, front, back ) {
var classification = this.classifySide( polygon );
if ( classification === COPLANAR ) {
( this.normal.dot( polygon.normal ) > 0 ? coplanar_front : coplanar_back ).push( polygon );
} else if ( classification === FRONT ) {
front.push( polygon );
} else if ( classification === BACK ) {
back.push( polygon );
} else {
var vertice_count,
i, j, ti, tj, vi, vj,
t, v,
f = [],
b = [];
for ( i = 0, vertice_count = polygon.vertices.length; i < vertice_count; i++ ) {
j = (i + 1) % vertice_count;
vi = polygon.vertices[i];
vj = polygon.vertices[j];
ti = this.classifyVertex( vi );
tj = this.classifyVertex( vj );
if ( ti != BACK ) f.push( vi );
if ( ti != FRONT ) b.push( vi );
if ( (ti | tj) === SPANNING ) {
t = ( this.w - this.normal.dot( vi ) ) / this.normal.dot( vj.clone().subtract( vi ) );
v = vi.interpolate( vj, t );
f.push( v );
b.push( v );
}
}
if ( f.length >= 3 ) front.push( new ThreeBSP.Polygon( f ).calculateProperties() );
if ( b.length >= 3 ) back.push( new ThreeBSP.Polygon( b ).calculateProperties() );
}
};
ThreeBSP.Vertex = function( x, y, z, normal /*, uv */ ) {
this.x = x;
this.y = y;
this.z = z;
this.normal = normal || new THREE.Vector3;
// this.uv = uv || new THREE.Vector2;
};
ThreeBSP.Vertex.prototype.clone = function() {
return new ThreeBSP.Vertex( this.x, this.y, this.z, this.normal.clone() /*, this.uv.clone() */ );
};
ThreeBSP.Vertex.prototype.add = function( vertex ) {
this.x += vertex.x;
this.y += vertex.y;
this.z += vertex.z;
return this;
};
ThreeBSP.Vertex.prototype.subtract = function( vertex ) {
this.x -= vertex.x;
this.y -= vertex.y;
this.z -= vertex.z;
return this;
};
ThreeBSP.Vertex.prototype.multiplyScalar = function( scalar ) {
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
return this;
};
ThreeBSP.Vertex.prototype.cross = function( vertex ) {
var x = this.x,
y = this.y,
z = this.z;
this.x = y * vertex.z - z * vertex.y;
this.y = z * vertex.x - x * vertex.z;
this.z = x * vertex.y - y * vertex.x;
return this;
};
ThreeBSP.Vertex.prototype.normalize = function() {
var length = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
this.x /= length;
this.y /= length;
this.z /= length;
return this;
};
ThreeBSP.Vertex.prototype.dot = function( vertex ) {
return this.x * vertex.x + this.y * vertex.y + this.z * vertex.z;
};
ThreeBSP.Vertex.prototype.diff = function( vertex ) {
var dx = (this.x - vertex.x),
dy = (this.y - vertex.y),
dz = (this.z - vertex.z),
len2 = this.x * this.x + this.y * this.y + this.z * this.z;
return (dx*dx+dy*dy+dz*dz) / (len2>0 ? len2 : 1e-10);
};
ThreeBSP.Vertex.prototype.lerp = function( a, t ) {
this.add(
a.clone().subtract( this ).multiplyScalar( t )
);
this.normal.add(
a.normal.clone().sub( this.normal ).multiplyScalar( t )
);
//this.uv.add(
// a.uv.clone().sub( this.uv ).multiplyScalar( t )
//);
return this;
};
ThreeBSP.Vertex.prototype.interpolate = function( other, t ) {
return this.clone().lerp( other, t );
};
ThreeBSP.Vertex.prototype.applyMatrix4 = function ( m ) {
// input: THREE.Matrix4 affine matrix
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
return this;
}
ThreeBSP.Node = function( polygons ) {
var i, polygon_count,
front = [],
back = [];
this.polygons = [];
this.front = this.back = undefined;
if ( !(polygons instanceof Array) || polygons.length === 0 ) return;
this.divider = polygons[0].clone();
// console.log('divider length ' + polygons.length);
for ( i = 0, polygon_count = polygons.length; i < polygon_count; i++ ) {
this.divider.splitPolygon( polygons[i], this.polygons, this.polygons, front, back );
}
// console.log('divider done ' + front.length + ' ' + back.length);
if ( front.length > 0 ) {
this.front = new ThreeBSP.Node( front );
}
if ( back.length > 0 ) {
this.back = new ThreeBSP.Node( back );
}
};
ThreeBSP.Node.isConvex = function( polygons ) {
var i, j;
for ( i = 0; i < polygons.length; i++ ) {
for ( j = 0; j < polygons.length; j++ ) {
if ( i !== j && polygons[i].classifySide( polygons[j] ) !== BACK ) {
return false;
}
}
}
return true;
};
ThreeBSP.Node.prototype.build = function( polygons ) {
var i, polygon_count,
front = [],
back = [];
if ( !this.divider ) {
this.divider = polygons[0].clone();
}
for ( i = 0, polygon_count = polygons.length; i < polygon_count; i++ ) {
this.divider.splitPolygon( polygons[i], this.polygons, this.polygons, front, back );
}
if ( front.length > 0 ) {
if ( !this.front ) this.front = new ThreeBSP.Node();
this.front.build( front );
}
if ( back.length > 0 ) {
if ( !this.back ) this.back = new ThreeBSP.Node();
this.back.build( back );
}
};
ThreeBSP.Node.prototype.allPolygons = function() {
var polygons = this.polygons.slice();
if ( this.front ) polygons = polygons.concat( this.front.allPolygons() );
if ( this.back ) polygons = polygons.concat( this.back.allPolygons() );
return polygons;
};
ThreeBSP.Node.prototype.numPolygons = function() {
var res = this.polygons.length;
if ( this.front ) res += this.front.numPolygons();
if ( this.back ) res += this.back.numPolygons();
return res;
}
ThreeBSP.Node.prototype.clone = function() {
var node = new ThreeBSP.Node();
node.divider = this.divider.clone();
node.polygons = this.polygons.map( function( polygon ) { return polygon.clone(); } );
node.front = this.front && this.front.clone();
node.back = this.back && this.back.clone();
return node;
};
ThreeBSP.Node.prototype.invert = function() {
var i, polygon_count, temp;
for ( i = 0, polygon_count = this.polygons.length; i < polygon_count; i++ ) {
this.polygons[i].flip();
}
this.divider.flip();
if ( this.front ) this.front.invert();
if ( this.back ) this.back.invert();
temp = this.front;
this.front = this.back;
this.back = temp;
return this;
};
ThreeBSP.Node.prototype.clipPolygons = function( polygons ) {
var i, polygon_count,
front, back;
if ( !this.divider ) return polygons.slice();
front = [], back = [];
for ( i = 0, polygon_count = polygons.length; i < polygon_count; i++ ) {
this.divider.splitPolygon( polygons[i], front, back, front, back );
}
if ( this.front ) front = this.front.clipPolygons( front );
if ( this.back ) back = this.back.clipPolygons( back );
else back = [];
return front.concat( back );
};
ThreeBSP.Node.prototype.clipTo = function( node ) {
this.polygons = node.clipPolygons( this.polygons );
if ( this.front ) this.front.clipTo( node );
if ( this.back ) this.back.clipTo( node );
};
return ThreeBSP;
};
if ((typeof document !== "undefined") && (typeof window !== "undefined")) {
window.ThreeBSP = ThreeBSPfactory();
} else {
ThreeBSP = ThreeBSPfactory();
} | Use polygon normals - not all vertex normals calculated correctly.
To be investiagated | scripts/ThreeCSG.js | Use polygon normals - not all vertex normals calculated correctly. | <ide><path>cripts/ThreeCSG.js
<ide>
<ide> var positions_buf = new Float32Array(buf_size),
<ide> normals_buf = new Float32Array(buf_size),
<del> iii = 0, polygon, vertex;
<add> iii = 0, polygon;
<add>
<add> function CopyVertex(vertex) {
<add>
<add> positions_buf[iii] = vertex.x;
<add> positions_buf[iii+1] = vertex.y;
<add> positions_buf[iii+2] = vertex.z;
<add>
<add> var norm = /*vertex.normal.lengthSq() > 0 ? vertex.normal :*/ polygon.normal;
<add>
<add> normals_buf[iii] = norm.x;
<add> normals_buf[iii+1] = norm.y;
<add> normals_buf[iii+2] = norm.z;
<add> iii+=3;
<add> }
<ide>
<ide> for ( i = 0; i < polygon_count; ++i ) {
<ide> polygon = polygons[i];
<del>
<ide> for ( j = 2; j < polygon.vertices.length; ++j ) {
<del>
<del> vertex = polygon.vertices[0];
<del>
<del> positions_buf[iii] = vertex.x;
<del> positions_buf[iii+1] = vertex.y;
<del> positions_buf[iii+2] = vertex.z;
<del>
<del> normals_buf[iii] = vertex.normal.x;
<del> normals_buf[iii+1] = vertex.normal.y;
<del> normals_buf[iii+2] = vertex.normal.z;
<del>
<del> iii+=3;
<del>
<del> vertex = polygon.vertices[j-1];
<del>
<del> positions_buf[iii] = vertex.x;
<del> positions_buf[iii+1] = vertex.y;
<del> positions_buf[iii+2] = vertex.z;
<del>
<del> normals_buf[iii] = vertex.normal.x;
<del> normals_buf[iii+1] = vertex.normal.y;
<del> normals_buf[iii+2] = vertex.normal.z;
<del>
<del> iii+=3;
<del>
<del> vertex = polygon.vertices[j];
<del>
<del> positions_buf[iii] = vertex.x;
<del> positions_buf[iii+1] = vertex.y;
<del> positions_buf[iii+2] = vertex.z;
<del>
<del> normals_buf[iii] = vertex.normal.x;
<del> normals_buf[iii+1] = vertex.normal.y;
<del> normals_buf[iii+2] = vertex.normal.z;
<del>
<del> iii+=3;
<add> CopyVertex(polygon.vertices[0]);
<add> CopyVertex(polygon.vertices[j-1]);
<add> CopyVertex(polygon.vertices[j]);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | f76b33537e3ef80a1304a401d9ded7642a2b583c | 0 | googleapis/google-cloud-java,googleapis/google-cloud-java,googleapis/google-cloud-java | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
package com.example.video;
import static com.google.common.truth.Truth.assertThat;
import com.google.cloud.videointelligence.v1.ObjectTrackingAnnotation;
import com.google.cloud.videointelligence.v1.TextAnnotation;
import com.google.cloud.videointelligence.v1.VideoAnnotationResults;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for video analysis sample.
*/
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class DetectIT {
static final String LABEL_GCS_LOCATION = "gs://cloud-samples-data/video/cat.mp4";
static final String LABEL_FILE_LOCATION = "./resources/googlework_short.mp4";
static final String SHOTS_FILE_LOCATION = "gs://cloud-samples-data/video/gbikes_dinosaur.mp4";
static final String EXPLICIT_CONTENT_LOCATION = "gs://cloud-samples-data/video/cat.mp4";
static final String SPEECH_GCS_LOCATION =
"gs://java-docs-samples-testing/video/googlework_short.mp4";
private static final List<String> POSSIBLE_TEXTS = Arrays.asList(
"Google", "SUR", "SUR", "ROTO", "Vice President", "58oo9", "LONDRES", "OMAR", "PARIS",
"METRO", "RUE", "CARLO");
private ByteArrayOutputStream bout;
private PrintStream out;
@Before
public void setUp() {
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
System.setOut(out);
}
@After
public void tearDown() {
System.setOut(null);
}
@Test
public void testLabels() throws Exception {
String[] args = {"labels", LABEL_GCS_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
assertThat(got).contains("Video label");
}
@Test
public void testLabelsFile() throws Exception {
String[] args = {"labels-file", LABEL_FILE_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
assertThat(got).contains("Video label");
}
@Test
public void testExplicitContent() throws Exception {
String[] args = {"explicit-content", EXPLICIT_CONTENT_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
assertThat(got).contains("Adult:");
}
@Test
public void testShots() throws Exception {
String[] args = {"shots", SHOTS_FILE_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
assertThat(got).contains("Shots:");
assertThat(got).contains("Location:");
}
@Test
public void testSpeechTranscription() throws Exception {
String[] args = {"speech-transcription", SPEECH_GCS_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
assertThat(got).contains("Transcript");
}
@Test
public void testTrackObjects() throws Exception {
TrackObjects.trackObjects("resources/googlework_short.mp4");
String got = bout.toString();
assertThat(got).contains("Entity id");
}
@Test
public void testTrackObjectsGcs() throws Exception {
VideoAnnotationResults result = TrackObjects.trackObjectsGcs(LABEL_GCS_LOCATION);
String got = bout.toString();
assertThat(got).contains("Entity id");
}
@Test
public void testTextDetection() throws Exception {
VideoAnnotationResults result = TextDetection.detectText("resources/googlework_short.mp4");
boolean textExists = false;
for (TextAnnotation textAnnotation : result.getTextAnnotationsList()) {
for (String possibleText : POSSIBLE_TEXTS) {
if (textAnnotation.getText().toUpperCase().contains(possibleText.toUpperCase())) {
textExists = true;
break;
}
}
}
assertThat(textExists).isTrue();
}
@Test
public void testTextDetectionGcs() throws Exception {
VideoAnnotationResults result = TextDetection.detectTextGcs(SPEECH_GCS_LOCATION);
boolean textExists = false;
for (TextAnnotation textAnnotation : result.getTextAnnotationsList()) {
for (String possibleText : POSSIBLE_TEXTS) {
if (textAnnotation.getText().toUpperCase().contains(possibleText.toUpperCase())) {
textExists = true;
break;
}
}
}
assertThat(textExists).isTrue();
}
}
| java-video-intelligence/samples/snippets/src/test/java/com/example/video/DetectIT.java | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
package com.example.video;
import static com.google.common.truth.Truth.assertThat;
import com.google.cloud.videointelligence.v1.ObjectTrackingAnnotation;
import com.google.cloud.videointelligence.v1.TextAnnotation;
import com.google.cloud.videointelligence.v1.VideoAnnotationResults;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for video analysis sample.
*/
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class DetectIT {
static final String LABEL_GCS_LOCATION = "gs://cloud-samples-data/video/cat.mp4";
static final String LABEL_FILE_LOCATION = "./resources/cat.mp4";
static final String SHOTS_FILE_LOCATION = "gs://cloud-samples-data/video/gbikes_dinosaur.mp4";
static final String EXPLICIT_CONTENT_LOCATION = "gs://cloud-samples-data/video/cat.mp4";
static final String SPEECH_GCS_LOCATION =
"gs://java-docs-samples-testing/video/googlework_short.mp4";
private static final List<String> POSSIBLE_TEXTS = Arrays.asList(
"Google", "SUR", "SUR", "ROTO", "Vice President", "58oo9", "LONDRES", "OMAR", "PARIS",
"METRO", "RUE", "CARLO");
private ByteArrayOutputStream bout;
private PrintStream out;
@Before
public void setUp() {
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
System.setOut(out);
}
@After
public void tearDown() {
System.setOut(null);
}
@Test
public void testLabels() throws Exception {
String[] args = {"labels", LABEL_GCS_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
// Test that the video with a cat has the whiskers label (may change).
assertThat(got.toUpperCase()).contains("WHISKERS");
}
@Test
public void testLabelsFile() throws Exception {
String[] args = {"labels-file", LABEL_FILE_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
// Test that the video with a cat has the whiskers label (may change).
assertThat(got.toUpperCase()).contains("WHISKERS");
}
@Test
public void testExplicitContent() throws Exception {
String[] args = {"explicit-content", EXPLICIT_CONTENT_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
assertThat(got).contains("Adult: VERY_UNLIKELY");
}
@Test
public void testShots() throws Exception {
String[] args = {"shots", SHOTS_FILE_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
assertThat(got).contains("Shots:");
assertThat(got).contains("Location: 0");
}
@Test
public void testSpeechTranscription() throws Exception {
String[] args = {"speech-transcription", SPEECH_GCS_LOCATION};
Detect.argsHelper(args);
String got = bout.toString();
assertThat(got).contains("cultural");
}
@Test
public void testTrackObjects() throws Exception {
VideoAnnotationResults result = TrackObjects.trackObjects(LABEL_FILE_LOCATION);
boolean textExists = false;
for (ObjectTrackingAnnotation objectTrackingAnnotation : result.getObjectAnnotationsList()) {
if (objectTrackingAnnotation.getEntity().getDescription().toUpperCase().contains("CAT")) {
textExists = true;
break;
}
}
assertThat(textExists).isTrue();
}
@Test
public void testTrackObjectsGcs() throws Exception {
VideoAnnotationResults result = TrackObjects.trackObjectsGcs(LABEL_GCS_LOCATION);
boolean textExists = false;
for (ObjectTrackingAnnotation objectTrackingAnnotation : result.getObjectAnnotationsList()) {
if (objectTrackingAnnotation.getEntity().getDescription().toUpperCase().contains("CAT")) {
textExists = true;
break;
}
}
assertThat(textExists).isTrue();
}
@Test
public void testTextDetection() throws Exception {
VideoAnnotationResults result = TextDetection.detectText("resources/googlework_short.mp4");
boolean textExists = false;
for (TextAnnotation textAnnotation : result.getTextAnnotationsList()) {
for (String possibleText : POSSIBLE_TEXTS) {
if (textAnnotation.getText().toUpperCase().contains(possibleText.toUpperCase())) {
textExists = true;
break;
}
}
}
assertThat(textExists).isTrue();
}
@Test
public void testTextDetectionGcs() throws Exception {
VideoAnnotationResults result = TextDetection.detectTextGcs(SPEECH_GCS_LOCATION);
boolean textExists = false;
for (TextAnnotation textAnnotation : result.getTextAnnotationsList()) {
for (String possibleText : POSSIBLE_TEXTS) {
if (textAnnotation.getText().toUpperCase().contains(possibleText.toUpperCase())) {
textExists = true;
break;
}
}
}
assertThat(textExists).isTrue();
}
}
| samples: video: update .mp4 file used in test (#2550)
Fixes https://github.com/GoogleCloudPlatform/java-docs-samples/issues/2545
- [ x] Tests pass
- [ x] Appropriate changes to README are included in PR
- [ x] API's need to be enabled to test (tell us)
- [ x] Environment Variables need to be set (ask us to set them)
| java-video-intelligence/samples/snippets/src/test/java/com/example/video/DetectIT.java | samples: video: update .mp4 file used in test (#2550) | <ide><path>ava-video-intelligence/samples/snippets/src/test/java/com/example/video/DetectIT.java
<ide> @SuppressWarnings("checkstyle:abbreviationaswordinname")
<ide> public class DetectIT {
<ide> static final String LABEL_GCS_LOCATION = "gs://cloud-samples-data/video/cat.mp4";
<del> static final String LABEL_FILE_LOCATION = "./resources/cat.mp4";
<add> static final String LABEL_FILE_LOCATION = "./resources/googlework_short.mp4";
<ide> static final String SHOTS_FILE_LOCATION = "gs://cloud-samples-data/video/gbikes_dinosaur.mp4";
<ide> static final String EXPLICIT_CONTENT_LOCATION = "gs://cloud-samples-data/video/cat.mp4";
<ide> static final String SPEECH_GCS_LOCATION =
<ide> String[] args = {"labels", LABEL_GCS_LOCATION};
<ide> Detect.argsHelper(args);
<ide> String got = bout.toString();
<del> // Test that the video with a cat has the whiskers label (may change).
<del> assertThat(got.toUpperCase()).contains("WHISKERS");
<add> assertThat(got).contains("Video label");
<ide> }
<ide>
<ide> @Test
<ide> String[] args = {"labels-file", LABEL_FILE_LOCATION};
<ide> Detect.argsHelper(args);
<ide> String got = bout.toString();
<del> // Test that the video with a cat has the whiskers label (may change).
<del> assertThat(got.toUpperCase()).contains("WHISKERS");
<add> assertThat(got).contains("Video label");
<ide> }
<ide>
<ide> @Test
<ide> String[] args = {"explicit-content", EXPLICIT_CONTENT_LOCATION};
<ide> Detect.argsHelper(args);
<ide> String got = bout.toString();
<del> assertThat(got).contains("Adult: VERY_UNLIKELY");
<add> assertThat(got).contains("Adult:");
<ide> }
<ide>
<ide> @Test
<ide> Detect.argsHelper(args);
<ide> String got = bout.toString();
<ide> assertThat(got).contains("Shots:");
<del> assertThat(got).contains("Location: 0");
<add> assertThat(got).contains("Location:");
<ide> }
<ide>
<ide> @Test
<ide> Detect.argsHelper(args);
<ide> String got = bout.toString();
<ide>
<del> assertThat(got).contains("cultural");
<add> assertThat(got).contains("Transcript");
<ide> }
<ide>
<ide> @Test
<ide> public void testTrackObjects() throws Exception {
<del> VideoAnnotationResults result = TrackObjects.trackObjects(LABEL_FILE_LOCATION);
<add> TrackObjects.trackObjects("resources/googlework_short.mp4");
<ide>
<del> boolean textExists = false;
<del> for (ObjectTrackingAnnotation objectTrackingAnnotation : result.getObjectAnnotationsList()) {
<del> if (objectTrackingAnnotation.getEntity().getDescription().toUpperCase().contains("CAT")) {
<del> textExists = true;
<del> break;
<del> }
<del> }
<add> String got = bout.toString();
<ide>
<del> assertThat(textExists).isTrue();
<add> assertThat(got).contains("Entity id");
<ide> }
<ide>
<ide> @Test
<ide> public void testTrackObjectsGcs() throws Exception {
<ide> VideoAnnotationResults result = TrackObjects.trackObjectsGcs(LABEL_GCS_LOCATION);
<ide>
<del> boolean textExists = false;
<del> for (ObjectTrackingAnnotation objectTrackingAnnotation : result.getObjectAnnotationsList()) {
<del> if (objectTrackingAnnotation.getEntity().getDescription().toUpperCase().contains("CAT")) {
<del> textExists = true;
<del> break;
<del> }
<del> }
<del>
<del> assertThat(textExists).isTrue();
<add> String got = bout.toString();
<add> assertThat(got).contains("Entity id");
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | a5c860bd21a4838d3d792c385dbf4ff9c912996f | 0 | anchela/jackrabbit-oak,apache/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak | package org.apache.jackrabbit.oak.api;
import java.math.BigDecimal;
import javax.jcr.PropertyType;
import com.google.common.base.Objects;
/**
* Instances of this class map Java types to {@link PropertyType property types}.
* Passing an instance of this class to {@link PropertyState#getValue(Type)} determines
* the return type of that method.
* @param <T>
*/
public final class Type<T> {
/** Map {@code String} to {@link PropertyType#STRING} */
public static final Type<String> STRING = create(PropertyType.STRING, false);
/** Map {@code Blob} to {@link PropertyType#BINARY} */
public static final Type<Blob> BINARY = create(PropertyType.BINARY, false);
/** Map {@code Long} to {@link PropertyType#LONG} */
public static final Type<Long> LONG = create(PropertyType.LONG, false);
/** Map {@code Double} to {@link PropertyType#DOUBLE} */
public static final Type<Double> DOUBLE = create(PropertyType.DOUBLE, false);
/** Map {@code String} to {@link PropertyType#DATE} */
public static final Type<String> DATE = create(PropertyType.DATE, false);
/** Map {@code Boolean} to {@link PropertyType#BOOLEAN} */
public static final Type<Boolean> BOOLEAN = create(PropertyType.BOOLEAN, false);
/** Map {@code String} to {@link PropertyType#STRING} */
public static final Type<String> NAME = create(PropertyType.NAME, false);
/** Map {@code String} to {@link PropertyType#PATH} */
public static final Type<String> PATH = create(PropertyType.PATH, false);
/** Map {@code String} to {@link PropertyType#REFERENCE} */
public static final Type<String> REFERENCE = create(PropertyType.REFERENCE, false);
/** Map {@code String} to {@link PropertyType#WEAKREFERENCE} */
public static final Type<String> WEAKREFERENCE = create(PropertyType.WEAKREFERENCE, false);
/** Map {@code String} to {@link PropertyType#URI} */
public static final Type<String> URI = create(PropertyType.URI, false);
/** Map {@code BigDecimal} to {@link PropertyType#DECIMAL} */
public static final Type<BigDecimal> DECIMAL = create(PropertyType.DECIMAL, false);
/** Map {@code Iterable<String>} to array of {@link PropertyType#STRING} */
public static final Type<Iterable<String>> STRINGS = create(PropertyType.STRING, true);
/** Map {@code Iterable<Blob} to array of {@link PropertyType#BINARY} */
public static final Type<Iterable<Blob>> BINARIES = create(PropertyType.BINARY, true);
/** Map {@code Iterable<Long>} to array of {@link PropertyType#LONG} */
public static final Type<Iterable<Long>> LONGS = create(PropertyType.LONG, true);
/** Map {@code Iterable<Double>} to array of {@link PropertyType#DOUBLE} */
public static final Type<Iterable<Double>> DOUBLES = create(PropertyType.DOUBLE, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#DATE} */
public static final Type<Iterable<String>> DATES = create(PropertyType.DATE, true);
/** Map {@code Iterable<Boolean>} to array of {@link PropertyType#BOOLEAN} */
public static final Type<Iterable<Boolean>> BOOLEANS = create(PropertyType.BOOLEAN, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#NAME} */
public static final Type<Iterable<String>> NAMES = create(PropertyType.NAME, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#PATH} */
public static final Type<Iterable<String>> PATHS = create(PropertyType.PATH, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#REFERENCE} */
public static final Type<Iterable<String>> REFERENCES = create(PropertyType.REFERENCE, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#WEAKREFERENCE} */
public static final Type<Iterable<String>> WEAKREFERENCES = create(PropertyType.WEAKREFERENCE, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#URI} */
public static final Type<Iterable<String>> URIS = create(PropertyType.URI, true);
/** Map {@code Iterable<BigDecimal>} to array of {@link PropertyType#DECIMAL} */
public static final Type<Iterable<BigDecimal>> DECIMALS = create(PropertyType.DECIMAL, true);
private final int tag;
private final boolean array;
private Type(int tag, boolean array){
this.tag = tag;
this.array = array;
}
private static <T> Type<T> create(int tag, boolean array) {
return new Type<T>(tag, array);
}
/**
* Corresponding type tag as defined in {@link PropertyType}.
* @return type tag
*/
public int tag() {
return tag;
}
/**
* Determine whether this is an array type
* @return {@code true} if and only if this is an array type
*/
public boolean isArray() {
return array;
}
/**
* Corresponding {@code Type} for a given type tag and array flag.
* @param tag type tag as defined in {@link PropertyType}.
* @param array whether this is an array or not
* @return {@code Type} instance
* @throws IllegalArgumentException if tag is not valid as per definition in {@link PropertyType}.
*/
public static Type<?> fromTag(int tag, boolean array) {
switch (tag) {
case PropertyType.STRING: return array ? STRINGS : STRING;
case PropertyType.BINARY: return array ? BINARIES : BINARY;
case PropertyType.LONG: return array ? LONGS : LONG;
case PropertyType.DOUBLE: return array ? DOUBLES : DOUBLE;
case PropertyType.DATE: return array ? DATES: DATE;
case PropertyType.BOOLEAN: return array ? BOOLEANS: BOOLEAN;
case PropertyType.NAME: return array ? NAMES : NAME;
case PropertyType.PATH: return array ? PATHS: PATH;
case PropertyType.REFERENCE: return array ? REFERENCES : REFERENCE;
case PropertyType.WEAKREFERENCE: return array ? WEAKREFERENCES : WEAKREFERENCE;
case PropertyType.URI: return array ? URIS: URI;
case PropertyType.DECIMAL: return array ? DECIMALS : DECIMAL;
default: throw new IllegalArgumentException("Invalid type tag: " + tag);
}
}
/**
* Determine the base type of array types
* @return base type
* @throws IllegalStateException if {@code isArray} is false.
*/
public Type<?> getBaseType() {
if (!isArray()) {
throw new IllegalStateException("Not an array: " + this);
}
return fromTag(tag, false);
}
@Override
public String toString() {
return isArray()
? "[]" + PropertyType.nameFromValue(getBaseType().tag)
: PropertyType.nameFromValue(tag);
}
@Override
public int hashCode() {
return Objects.hashCode(tag, array);
}
@Override
public boolean equals(Object other) {
return this == other;
}
}
| oak-core/src/main/java/org/apache/jackrabbit/oak/api/Type.java | package org.apache.jackrabbit.oak.api;
import java.math.BigDecimal;
import javax.jcr.PropertyType;
import com.google.common.base.Objects;
/**
* Instances of this class map Java types to {@link PropertyType property types}.
* Passing an instance of this class to {@link PropertyState#getValue(Type)} determines
* the return type of that method.
* @param <T>
*/
public final class Type<T> {
/** Map {@code String} to {@link PropertyType#STRING} */
public static final Type<String> STRING = create(PropertyType.STRING, false);
/** Map {@code Blob} to {@link PropertyType#BINARY} */
public static final Type<Blob> BINARY = create(PropertyType.BINARY, false);
/** Map {@code Long} to {@link PropertyType#LONG} */
public static final Type<Long> LONG = create(PropertyType.LONG, false);
/** Map {@code Double} to {@link PropertyType#DOUBLE} */
public static final Type<Double> DOUBLE = create(PropertyType.DOUBLE, false);
/** Map {@code String} to {@link PropertyType#DATE} */
public static final Type<String> DATE = create(PropertyType.DATE, false);
/** Map {@code Boolean} to {@link PropertyType#BOOLEAN} */
public static final Type<Boolean> BOOLEAN = create(PropertyType.BOOLEAN, false);
/** Map {@code String} to {@link PropertyType#STRING} */
public static final Type<String> NAME = create(PropertyType.NAME, false);
/** Map {@code String} to {@link PropertyType#PATH} */
public static final Type<String> PATH = create(PropertyType.PATH, false);
/** Map {@code String} to {@link PropertyType#REFERENCE} */
public static final Type<String> REFERENCE = create(PropertyType.REFERENCE, false);
/** Map {@code String} to {@link PropertyType#WEAKREFERENCE} */
public static final Type<String> WEAKREFERENCE = create(PropertyType.WEAKREFERENCE, false);
/** Map {@code String} to {@link PropertyType#URI} */
public static final Type<String> URI = create(PropertyType.URI, false);
/** Map {@code BigDecimal} to {@link PropertyType#DECIMAL} */
public static final Type<BigDecimal> DECIMAL = create(PropertyType.DECIMAL, false);
/** Map {@code Iterable<String>} to array of {@link PropertyType#STRING} */
public static final Type<Iterable<String>> STRINGS = create(PropertyType.STRING, true);
/** Map {@code Iterable<Blob} to array of {@link PropertyType#BINARY} */
public static final Type<Iterable<Blob>> BINARIES = create(PropertyType.BINARY, true);
/** Map {@code Iterable<Long>} to array of {@link PropertyType#LONG} */
public static final Type<Iterable<Long>> LONGS = create(PropertyType.LONG, true);
/** Map {@code Iterable<Double>} to array of {@link PropertyType#DOUBLE} */
public static final Type<Iterable<Double>> DOUBLES = create(PropertyType.DOUBLE, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#DATE} */
public static final Type<Iterable<String>> DATES = create(PropertyType.DATE, true);
/** Map {@code Iterable<Boolean>} to array of {@link PropertyType#BOOLEAN} */
public static final Type<Iterable<Boolean>> BOOLEANS = create(PropertyType.BOOLEAN, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#NAME} */
public static final Type<Iterable<String>> NAMES = create(PropertyType.NAME, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#PATH} */
public static final Type<Iterable<String>> PATHS = create(PropertyType.PATH, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#REFERENCE} */
public static final Type<Iterable<String>> REFERENCES = create(PropertyType.REFERENCE, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#WEAKREFERENCE} */
public static final Type<Iterable<String>> WEAKREFERENCES = create(PropertyType.WEAKREFERENCE, true);
/** Map {@code Iterable<String>} to array of {@link PropertyType#URI} */
public static final Type<Iterable<String>> URIS = create(PropertyType.URI, true);
/** Map {@code Iterable<BigDecimal>} to array of {@link PropertyType#DECIMAL} */
public static final Type<Iterable<BigDecimal>> DECIMALS = create(PropertyType.DECIMAL, true);
private final int tag;
private final boolean array;
private Type(int tag, boolean array){
this.tag = tag;
this.array = array;
}
private static <T> Type<T> create(int tag, boolean array) {
return new Type<T>(tag, array);
}
/**
* Corresponding type tag as defined in {@link PropertyType}.
* @return type tag
*/
public int tag() {
return tag;
}
/**
* Determine whether this is an array type
* @return {@code true} if and only if this is an array type
*/
public boolean isArray() {
return array;
}
/**
* Corresponding {@code Type} for a given type tag and array flag.
* @param tag type tag as defined in {@link PropertyType}.
* @param array whether this is an array or not
* @return {@code Type} instance
* @throws IllegalArgumentException if tag is not valid as per definition in {@link PropertyType}.
*/
public static Type<?> fromTag(int tag, boolean array) {
switch (tag) {
case PropertyType.STRING: return array ? STRINGS : STRING;
case PropertyType.BINARY: return array ? BINARY : BINARIES;
case PropertyType.LONG: return array ? LONG : LONGS;
case PropertyType.DOUBLE: return array ? DOUBLE : DOUBLES;
case PropertyType.DATE: return array ? DATE: DATES;
case PropertyType.BOOLEAN: return array ? BOOLEAN: BOOLEANS;
case PropertyType.NAME: return array ? NAME : NAMES;
case PropertyType.PATH: return array ? PATH: PATHS;
case PropertyType.REFERENCE: return array ? REFERENCE : REFERENCES;
case PropertyType.WEAKREFERENCE: return array ? WEAKREFERENCE : WEAKREFERENCES;
case PropertyType.URI: return array ? URI: URIS;
case PropertyType.DECIMAL: return array ? DECIMAL : DECIMALS;
default: throw new IllegalArgumentException("Invalid type tag: " + tag);
}
}
/**
* Determine the base type of array types
* @return base type
* @throws IllegalStateException if {@code isArray} is false.
*/
public Type<?> getBaseType() {
if (!isArray()) {
throw new IllegalStateException("Not an array: " + this);
}
return fromTag(tag, false);
}
@Override
public String toString() {
return isArray()
? "[]" + PropertyType.nameFromValue(getBaseType().tag)
: PropertyType.nameFromValue(tag);
}
@Override
public int hashCode() {
return Objects.hashCode(tag, array);
}
@Override
public boolean equals(Object other) {
return this == other;
}
}
| OAK-350: Unify PropertyState and CoreValue
- fix: Type.fromTag returns array types instead of base types
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1394088 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/main/java/org/apache/jackrabbit/oak/api/Type.java | OAK-350: Unify PropertyState and CoreValue - fix: Type.fromTag returns array types instead of base types | <ide><path>ak-core/src/main/java/org/apache/jackrabbit/oak/api/Type.java
<ide> public static Type<?> fromTag(int tag, boolean array) {
<ide> switch (tag) {
<ide> case PropertyType.STRING: return array ? STRINGS : STRING;
<del> case PropertyType.BINARY: return array ? BINARY : BINARIES;
<del> case PropertyType.LONG: return array ? LONG : LONGS;
<del> case PropertyType.DOUBLE: return array ? DOUBLE : DOUBLES;
<del> case PropertyType.DATE: return array ? DATE: DATES;
<del> case PropertyType.BOOLEAN: return array ? BOOLEAN: BOOLEANS;
<del> case PropertyType.NAME: return array ? NAME : NAMES;
<del> case PropertyType.PATH: return array ? PATH: PATHS;
<del> case PropertyType.REFERENCE: return array ? REFERENCE : REFERENCES;
<del> case PropertyType.WEAKREFERENCE: return array ? WEAKREFERENCE : WEAKREFERENCES;
<del> case PropertyType.URI: return array ? URI: URIS;
<del> case PropertyType.DECIMAL: return array ? DECIMAL : DECIMALS;
<add> case PropertyType.BINARY: return array ? BINARIES : BINARY;
<add> case PropertyType.LONG: return array ? LONGS : LONG;
<add> case PropertyType.DOUBLE: return array ? DOUBLES : DOUBLE;
<add> case PropertyType.DATE: return array ? DATES: DATE;
<add> case PropertyType.BOOLEAN: return array ? BOOLEANS: BOOLEAN;
<add> case PropertyType.NAME: return array ? NAMES : NAME;
<add> case PropertyType.PATH: return array ? PATHS: PATH;
<add> case PropertyType.REFERENCE: return array ? REFERENCES : REFERENCE;
<add> case PropertyType.WEAKREFERENCE: return array ? WEAKREFERENCES : WEAKREFERENCE;
<add> case PropertyType.URI: return array ? URIS: URI;
<add> case PropertyType.DECIMAL: return array ? DECIMALS : DECIMAL;
<ide> default: throw new IllegalArgumentException("Invalid type tag: " + tag);
<ide> }
<ide> } |
|
JavaScript | mit | 53f4c4ef0ec20649c6624cc51a30113e74aa2e0d | 0 | espadrine/sc,espadrine/sc | /* camp.js: server-side Ajax handler that wraps around Node.js.
* Copyright © 2011 Thaddee Tyl, Jan Keromnes. All rights reserved.
* Code covered by the LGPL license. */
"use strict";
var Plate = require ('./plate');
var EventEmitter = require ('events').EventEmitter,
http = require('http'),
https = require('https'),
p = require('path'),
fs = require('fs'),
url = require('url'),
qs = require('querystring');
var mime = require('./mime.json'),
binaries = [
'pdf', 'ps', 'odt', 'ods', 'odp', 'xls', 'doc', 'ppt', 'dvi', 'ttf',
'swf', 'rar', 'zip', 'tar', 'gz', 'ogg', 'mp3', 'mpeg', 'wav', 'wma',
'gif', 'jpg', 'jpeg', 'png', 'svg', 'tiff', 'ico', 'mp4', 'ogv', 'mov',
'webm', 'wmv'
];
// We'll need to parse the query (either POST or GET) as a literal.
function parsequery (query, strquery) {
var items = strquery.split('&');
for (var item in items) {
// Each element of key=value is then again split along `=`.
var elems = items[item].split('=');
try {
query[decodeURIComponent(elems[0])] =
JSON.parse(decodeURIComponent(elems[1]));
} catch (e) {
console.log ('query:', JSON.stringify(query), e.toString());
}
}
return query;
}
// Ask is a model of the client's request / response environment.
function Ask (server, req, res) {
this.server = server;
this.req = req;
this.res = res;
try {
this.uri = url.parse(decodeURI(req.url), true);
} catch (e) { // Using `escape` should not kill the server.
this.uri = url.parse(unescape(req.url), true);
}
this.path = this.uri.pathname;
this.query = this.uri.query;
}
// Set the mime type of the response.
Ask.prototype.mime = function (type) {
this.res.setHeader('Content-Type', type);
}
// Camp class is classy.
//
// Camp has a router function that returns the stack of functions to call, one
// after the other, in order to process the request.
function Camp() {
http.Server.call(this);
this.stack = [];
for (var i = 0; i < defaultRoute.length; i++)
this.stack.push(defaultRoute[i](this));
this.on('request', listener.bind(this));
}
Camp.prototype = new http.Server();
function SecureCamp(opts) {
https.Server.call(this, opts);
this.stack = [];
for (var i = 0; i < defaultRoute.length; i++)
this.stack.push(defaultRoute[i](this));
this.on('request', listener.bind(this));
}
// The following `requestCert` thing seems required by node.
SecureCamp.prototype = new https.Server({requestCert:null});
// Insert a listener after a listener named `listn`.
Camp.prototype.insertListener = SecureCamp.prototype.insertListener =
function addListenerBefore(listn, type, listener) {
// this._events is an EventEmitter thing, a list of functions.
if (this._events && this._events[type] && Array.isArray(this._events[type])) {
var index = 0;
for (var i = 0; i < this._events[type].length; i++) {
if (this._events[type][i].name === listn) {
index = i;
break;
}
}
// Insertion algorithm from <http://jsperf.com/insert-to-an-array>.
var l = this._events[type],
a = l.slice(0, index);
a.push(listener);
this._events[type] = a.concat(l.slice(index));
} else {
this.on(type, listener);
}
return this;
}
// Default request listener.
function listener (req, res) {
var ask = new Ask(this, req, res);
bubble(ask, 0);
}
// The bubble goes through each layer of the stack until it reaches the surface.
// The surface is a Server Error, btw.
function bubble (ask, layer) {
ask.server.stack[layer](ask, function next() {
if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1);
else {
ask.res.statusCode = 500;
ask.res.end('500\n');
}
});
}
// The default routing function:
//
// - if the request is of the form /$socket.io, it runs the socket.io unit.
// - if the request is of the form /$..., it runs the ajax / eventSource unit.
// - if the request is a registered template, it runs the template unit.
// - if the request isn't a registered route, it runs the static unit.
// - else, it runs the notfound unit.
var defaultRoute = [socketUnit, ajaxUnit, eventSourceUnit,
routeUnit, staticUnit, notfoundUnit];
// Socket.io unit.
function socketUnit (server) {
var io = server.io = require('socket.io').listen(server);
// Client-side: <script src="/$socket.io/socket.io.js"></script>
function ioConf() { io.set('resource', '/$socket.io'); }
io.configure('development', ioConf);
io.configure('production', ioConf);
return function socketLayer (ask, next) {
// Socket.io doesn't care about anything but /$socket.io now.
if (ask.path.slice(1, 11) !== '$socket.io') next();
};
}
// Ajax unit.
function ajaxUnit (server) {
var ajax = server.ajax = new EventEmitter();
return function ajaxLayer (ask, next) {
if (ask.path[1] !== '$') return next();
var action = ask.path.slice(2),
res = ask.res;
if (ajax.listeners(action).length <= 0) return next();
res.setHeader('Content-Type', mime.json);
// Handler for when we get a data request.
var gotrequest = function (chunk) {
if (chunk !== undefined) parsequery(ask.query, chunk.toString());
// Launch the defined action.
ajax.emit(action, ask.query, function ajaxEnd (data) {
res.end(JSON.stringify(data || {}));
}, ask);
};
if (ask.req.method === 'POST') ask.req.on ('data', gotrequest);
else gotrequest();
};
}
// EventSource unit.
//
// Note: great inspiration was taken from Remy Sharp's code.
function eventSourceUnit (server) {
var sources = {};
function Source () {
this.conn = [];
this.history = [];
this.lastMsgId = 0;
}
Source.prototype.removeConn = function(res) {
var i = this.conn.indexOf(res);
if (i !== -1) {
this.conn.splice(i, 1);
}
};
Source.prototype.sendSSE = function (res, id, event, message) {
var data = '';
if (event !== null) {
data += 'event:' + event + '\n';
}
// Blank id resets the id counter.
if (id !== null) {
data += 'id:' + id + '\n';
} else {
data += 'id\n';
}
if (message) {
data += 'data:' + message.split('\n').join('\ndata') + '\n';
}
data += '\n';
res.write(data);
if (res.hasOwnProperty('xhr')) {
clearTimeout(res.xhr);
var self = this;
res.xhr = setTimeout(function () {
res.end();
self.removeConn(res);
}, 250);
}
};
Source.prototype.emit = function (event, msg) {
this.lastMsgId++;
this.history.push({
id: this.lastMsgId,
event: event,
msg: msg
});
for (var i = 0; i < this.conn.length; i++) {
this.sendSSE(this.conn[i], this.lastMsgId, event, msg);
}
}
Source.prototype.send = function (msg) {
this.emit(null, JSON.stringify(msg));
}
function eventSource (channel) {
return sources[channel] = new Source();
}
server.eventSource = eventSource;
return function eventSourceLayer (ask, next) {
if (ask.path[1] !== '$') return next();
var action = ask.path.slice(2),
res = ask.res,
source = sources[action];
if (!source || ask.req.headers.accept !== 'text/event-stream')
return next(); // Don't bother if the client cannot handle it.
// Remy Sharp's Polyfill support.
if (ask.req.headers['x-requested-with'] == 'XMLHttpRequest') {
res.xhr = null;
}
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
if (ask.req.headers['last-event-id']) {
var id = parseInt(ask.req.headers['last-event-id']);
for (var i = 0; i < source.history.length; i++)
if (source.history[i].id > id)
source.sendSSE(res, source.history[i].id,
source.history[i].event, source.history[i].msg);
} else res.write('id\n\n'); // Reset id.
source.conn.push(res);
// Every 15s, send a comment (avoids proxy dropping HTTP connection).
var to = setInterval(function () {res.write(':\n');}, 15000);
// This can only end in blood.
ask.req.on('close', function () {
source.removeConn(res);
clearInterval(to);
});
};
}
// Static unit.
function staticUnit (server) {
var documentRoot = server.documentRoot = process.cwd() + '/web';
return function staticLayer (ask, next) {
// We use `documentRoot` as the root wherein we seek files.
var realpath = p.join(documentRoot, ask.path);
fs.stat(realpath, function(err, stats) {
if (err) return next();
ask.mime(mime[p.extname(ask.path).slice(1)] || 'text/plain');
if (stats.isDirectory()) {
realpath = p.join(realpath, 'index.html');
ask.mime(mime['html']);
}
// Connect the output of the file to the network!
fs.createReadStream(realpath).pipe(ask.res);
});
};
}
// Template unit.
function routeUnit (server) {
var templates = [];
function route (paths, literalCall) {
templates.push([RegExp(paths).source, literalCall]);
}
server.route = route;
return function routeLayer (ask, next) {
var platepaths;
if ((platepaths = templates.filter (function(key) {
return RegExp(key[0]).test (ask.path);
})).length > 0) {
catchpath(ask, platepaths);
} else {
next();
}
};
}
// Not Fount unit — in fact, mostly a copy&paste of the route unit.
function notfoundUnit (server) {
var notfoundTemplates = [];
function notfound (paths, literalCall) {
notfoundTemplates.push([RegExp(paths).source, literalCall]);
}
server.notfound = notfound;
return function notfoundLayer (ask) {
var platepaths;
ask.res.statusCode = 404;
if ((platepaths = notfoundTemplates.filter (function(key) {
return RegExp(key[0]).test (ask.path);
})).length > 0) {
catchpath(ask, platepaths);
} else {
ask.res.end('404\n');
}
};
}
// Route *and* not found units — see what I did there?
function catchpath (ask, platepaths) {
var res = ask.res;
if (platepaths.length > 1) {
console.error ('More than one template path match', path + ':');
platepaths.forEach (function (path) {console.error ('-',path);});
}
var pathmatch = ask.path.match (RegExp (platepaths[0][0]));
// Template parameters (JSON-serializable).
var params = platepaths[0][1](ask.query, pathmatch, function end (params) {
if (!ask.res.getHeader('Content-Type')) // Allow overriding.
ask.mime(mime[p.extname(pathmatch[0]).slice(1)] || 'text/plain');
var templatePath = p.join(ask.server.documentRoot, pathmatch[0]),
reader = fs.createReadStream(templatePath);
if (!(params && Object.keys(params).length)) {
// No data was given. Same behaviour as static.
reader.pipe(ask.res);
} else {
Plate.format(reader, ask.res, params);
}
}, ask);
}
// Internal start function.
//
function createServer () { return new Camp(); }
function createSecureServer (opts) { return new SecureCamp(opts); }
function startServer (settings) {
var server;
// Are we running https?
if (settings.secure) { // Yep
server = new SecureCamp ({
key: fs.readFileSync(settings.security.key),
cert: fs.readFileSync(settings.security.cert),
ca: settings.security.ca.map(function(file) {
try {
var ca = fs.readFileSync(file);
return ca;
} catch (e) { console.error('CA file not found:', file); }
})
}).listen(settings.port);
} else { // Nope
server = new Camp().listen(settings.port);
}
return server;
}
// Each camp instance creates an HTTP / HTTPS server automatically.
//
function start (options) {
// Settings.
//
// By settings I mean data that was set when starting the server, and that is
// not meant to be changed thereafter.
var settings = {
port: 80,
security: {}
};
options = options || {};
for (var setting in options) {
settings[setting] = options[setting];
}
// Populate security values with the corresponding files.
if (options.secure) {
settings.security.key = options.key || 'https.key';
settings.security.cert = options.cert || 'https.crt';
settings.security.ca = options.ca || [];
}
settings.port = settings.port || (settings.secure ? 443 : 80);
return startServer(settings);
};
exports.start = start;
exports.createServer = createServer;
exports.createSecureServer = createSecureServer;
exports.Camp;
exports.SecureCamp;
exports.socketUnit;
exports.ajaxUnit;
exports.eventSourceUnit;
exports.routeUnit;
exports.staticUnit;
exports.notfoundUnit;
exports.Plate = Plate;
exports.mime = mime;
exports.binaries = binaries;
| lib/camp.js | /* camp.js: server-side Ajax handler that wraps around Node.js.
* Copyright © 2011 Thaddee Tyl, Jan Keromnes. All rights reserved.
* Code covered by the LGPL license. */
"use strict";
var Plate = require ('./plate');
var EventEmitter = require ('events').EventEmitter,
http = require('http'),
https = require('https'),
p = require('path'),
fs = require('fs'),
url = require('url'),
qs = require('querystring');
var mime = require('./mime.json'),
binaries = [
'pdf', 'ps', 'odt', 'ods', 'odp', 'xls', 'doc', 'ppt', 'dvi', 'ttf',
'swf', 'rar', 'zip', 'tar', 'gz', 'ogg', 'mp3', 'mpeg', 'wav', 'wma',
'gif', 'jpg', 'jpeg', 'png', 'svg', 'tiff', 'ico', 'mp4', 'ogv', 'mov',
'webm', 'wmv'
];
// We'll need to parse the query (either POST or GET) as a literal.
function parsequery (query, strquery) {
var items = strquery.split('&');
for (var item in items) {
// Each element of key=value is then again split along `=`.
var elems = items[item].split('=');
try {
query[decodeURIComponent(elems[0])] =
JSON.parse(decodeURIComponent(elems[1]));
} catch (e) {
console.log ('query:', JSON.stringify(query), e.toString());
}
}
return query;
}
// Ask is a model of the client's request / response environment.
function Ask (server, req, res) {
this.server = server;
this.req = req;
this.res = res;
try {
this.uri = url.parse(decodeURI(req.url), true);
} catch (e) { // Using `escape` should not kill the server.
this.uri = url.parse(unescape(req.url), true);
}
this.path = this.uri.pathname;
this.query = this.uri.query;
}
// Set the mime type of the response.
Ask.prototype.mime = function (type) {
this.res.setHeader('Content-Type', type);
}
// Camp class is classy.
//
// Camp has a router function that returns the stack of functions to call, one
// after the other, in order to process the request.
function Camp() {
http.Server.call(this);
this.stack = [];
for (var i = 0; i < defaultRoute.length; i++)
this.stack.push(defaultRoute[i](this));
this.on('request', listener.bind(this));
}
Camp.prototype = new http.Server();
function SecureCamp(opts) {
https.Server.call(this, opts);
this.stack = [];
for (var i = 0; i < defaultRoute.length; i++)
this.stack.push(defaultRoute[i](this));
this.on('request', listener.bind(this));
}
// The following `requestCert` thing seems required by node.
SecureCamp.prototype = new https.Server({requestCert:null});
// Insert a listener after a listener named `listn`.
Camp.prototype.insertListener = SecureCamp.prototype.insertListener =
function addListenerBefore(listn, type, listener) {
// this._events is an EventEmitter thing, a list of functions.
if (this._events && this._events[type] && Array.isArray(this._events[type])) {
var index = 0;
for (var i = 0; i < this._events[type].length; i++) {
if (this._events[type][i].name === listn) {
index = i;
break;
}
}
// Insertion algorithm from <http://jsperf.com/insert-to-an-array>.
var l = this._events[type],
a = l.slice(0, index);
a.push(listener);
this._events[type] = a.concat(l.slice(index));
} else {
this.on(type, listener);
}
return this;
}
// Default request listener.
function listener (req, res) {
var ask = new Ask(this, req, res);
bubble(ask, 0);
}
// The bubble goes through each layer of the stack until it reaches the surface.
// The surface is a Server Error, btw.
function bubble (ask, layer) {
ask.server.stack[layer](ask, function next() {
if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1);
else {
ask.res.statusCode = 500;
ask.res.end('500\n');
}
});
}
// The default routing function:
//
// - if the request is of the form /$socket.io, it runs the socket.io unit.
// - if the request is of the form /$..., it runs the ajax / eventSource unit.
// - if the request is a registered template, it runs the template unit.
// - if the request isn't a registered route, it runs the static unit.
// - else, it runs the notfound unit.
var defaultRoute = [socketUnit, ajaxUnit, eventSourceUnit,
routeUnit, staticUnit, notfoundUnit];
// Socket.io unit.
function socketUnit (server) {
var io = server.io = require('socket.io').listen(server);
// Client-side: <script src="/$socket.io/socket.io.js"></script>
function ioConf() { io.set('resource', '/$socket.io'); }
io.configure('development', ioConf);
io.configure('production', ioConf);
return function socketLayer (ask, next) {
// Socket.io doesn't care about anything but /$socket.io now.
if (ask.path.slice(1, 11) !== '$socket.io') next();
};
}
// Ajax unit.
function ajaxUnit (server) {
var ajax = server.ajax = new EventEmitter();
return function ajaxLayer (ask, next) {
if (ask.path[1] !== '$') return next();
var action = ask.path.slice(2),
res = ask.res;
if (ajax.listeners(action).length <= 0) return next();
res.setHeader('Content-Type', mime.json);
// Handler for when we get a data request.
var gotrequest = function (chunk) {
if (chunk !== undefined) parsequery(ask.query, chunk.toString());
// Launch the defined action.
ajax.emit(action, ask.query, function ajaxEnd (data) {
res.end(JSON.stringify(data || {}));
}, ask);
};
if (ask.req.method === 'POST') ask.req.on ('data', gotrequest);
else gotrequest();
};
}
// EventSource unit.
//
// Note: great inspiration was taken from Remy Sharp's code.
function eventSourceUnit (server) {
var sources = {};
function Source () {
this.conn = [];
this.history = [];
this.lastMsgId = 0;
}
Source.prototype.removeConn = function(res) {
var i = this.conn.indexOf(res);
if (i !== -1) {
this.conn.splice(i, 1);
}
};
Source.prototype.sendSSE = function (res, id, event, message) {
var data = '';
if (event !== null) {
data += 'event:' + event + '\n';
}
// Blank id resets the id counter.
if (id !== null) {
data += 'id:' + id + '\n';
} else {
data += 'id\n';
}
if (message) {
data += 'data:' + message.split('\n').join('\ndata') + '\n';
}
data += '\n';
res.write(data);
if (res.hasOwnProperty('xhr')) {
clearTimeout(res.xhr);
var self = this;
res.xhr = setTimeout(function () {
res.end();
self.removeConn(res);
}, 250);
}
};
Source.prototype.emit = function (event, msg) {
this.lastMsgId++;
this.history.push({
id: this.lastMsgId,
event: event,
msg: msg
});
for (var i = 0; i < this.conn.length; i++) {
this.sendSSE(this.conn[i], this.lastMsgId, event, msg);
}
}
Source.prototype.send = function (msg) {
this.emit(null, JSON.stringify(msg));
}
function eventSource (channel) {
return sources[channel] = new Source();
}
server.eventSource = eventSource;
return function eventSourceLayer (ask, next) {
if (ask.path[1] !== '$') return next();
var action = ask.path.slice(2),
res = ask.res,
source = sources[action];
if (!source || ask.req.headers.accept !== 'text/event-stream')
return next(); // Don't bother if the client cannot handle it.
// Remy Sharp's Polyfill support.
if (ask.req.headers['x-requested-with'] == 'XMLHttpRequest') {
res.xhr = null;
}
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
if (ask.req.headers['last-event-id']) {
var id = parseInt(ask.req.headers['last-event-id']);
for (var i = 0; i < source.history.length; i++)
if (source.history[i].id >= id)
source.sendSSE(res, source.history[i].id,
source.history[i].event, source.history[i].msg);
} else res.write('id\n\n'); // Reset id.
source.conn.push(res);
// Every 15s, send a comment (avoids proxy dropping HTTP connection).
var to = setInterval(function () {res.write(':\n');}, 15000);
// This can only end in blood.
ask.req.on('close', function () {
source.removeConn(res);
clearInterval(to);
});
};
}
// Static unit.
function staticUnit (server) {
var documentRoot = server.documentRoot = process.cwd() + '/web';
return function staticLayer (ask, next) {
// We use `documentRoot` as the root wherein we seek files.
var realpath = p.join(documentRoot, ask.path);
fs.stat(realpath, function(err, stats) {
if (err) return next();
ask.mime(mime[p.extname(ask.path).slice(1)] || 'text/plain');
if (stats.isDirectory()) {
realpath = p.join(realpath, 'index.html');
ask.mime(mime['html']);
}
// Connect the output of the file to the network!
fs.createReadStream(realpath).pipe(ask.res);
});
};
}
// Template unit.
function routeUnit (server) {
var templates = [];
function route (paths, literalCall) {
templates.push([RegExp(paths).source, literalCall]);
}
server.route = route;
return function routeLayer (ask, next) {
var platepaths;
if ((platepaths = templates.filter (function(key) {
return RegExp(key[0]).test (ask.path);
})).length > 0) {
catchpath(ask, platepaths);
} else {
next();
}
};
}
// Not Fount unit — in fact, mostly a copy&paste of the route unit.
function notfoundUnit (server) {
var notfoundTemplates = [];
function notfound (paths, literalCall) {
notfoundTemplates.push([RegExp(paths).source, literalCall]);
}
server.notfound = notfound;
return function notfoundLayer (ask) {
var platepaths;
ask.res.statusCode = 404;
if ((platepaths = notfoundTemplates.filter (function(key) {
return RegExp(key[0]).test (ask.path);
})).length > 0) {
catchpath(ask, platepaths);
} else {
ask.res.end('404\n');
}
};
}
// Route *and* not found units — see what I did there?
function catchpath (ask, platepaths) {
var res = ask.res;
if (platepaths.length > 1) {
console.error ('More than one template path match', path + ':');
platepaths.forEach (function (path) {console.error ('-',path);});
}
var pathmatch = ask.path.match (RegExp (platepaths[0][0]));
// Template parameters (JSON-serializable).
var params = platepaths[0][1](ask.query, pathmatch, function end (params) {
if (!ask.res.getHeader('Content-Type')) // Allow overriding.
ask.mime(mime[p.extname(pathmatch[0]).slice(1)] || 'text/plain');
var templatePath = p.join(ask.server.documentRoot, pathmatch[0]),
reader = fs.createReadStream(templatePath);
if (!(params && Object.keys(params).length)) {
// No data was given. Same behaviour as static.
reader.pipe(ask.res);
} else {
Plate.format(reader, ask.res, params);
}
}, ask);
}
// Internal start function.
//
function createServer () { return new Camp(); }
function createSecureServer (opts) { return new SecureCamp(opts); }
function startServer (settings) {
var server;
// Are we running https?
if (settings.secure) { // Yep
server = new SecureCamp ({
key: fs.readFileSync(settings.security.key),
cert: fs.readFileSync(settings.security.cert),
ca: settings.security.ca.map(function(file) {
try {
var ca = fs.readFileSync(file);
return ca;
} catch (e) { console.error('CA file not found:', file); }
})
}).listen(settings.port);
} else { // Nope
server = new Camp().listen(settings.port);
}
return server;
}
// Each camp instance creates an HTTP / HTTPS server automatically.
//
function start (options) {
// Settings.
//
// By settings I mean data that was set when starting the server, and that is
// not meant to be changed thereafter.
var settings = {
port: 80,
security: {}
};
options = options || {};
for (var setting in options) {
settings[setting] = options[setting];
}
// Populate security values with the corresponding files.
if (options.secure) {
settings.security.key = options.key || 'https.key';
settings.security.cert = options.cert || 'https.crt';
settings.security.ca = options.ca || [];
}
settings.port = settings.port || (settings.secure ? 443 : 80);
return startServer(settings);
};
exports.start = start;
exports.createServer = createServer;
exports.createSecureServer = createSecureServer;
exports.Camp;
exports.SecureCamp;
exports.socketUnit;
exports.ajaxUnit;
exports.eventSourceUnit;
exports.routeUnit;
exports.staticUnit;
exports.notfoundUnit;
exports.Plate = Plate;
exports.mime = mime;
exports.binaries = binaries;
| EventSource fix for the polyfill.
The id management was seemingly wrong.
| lib/camp.js | EventSource fix for the polyfill. | <ide><path>ib/camp.js
<ide> if (ask.req.headers['last-event-id']) {
<ide> var id = parseInt(ask.req.headers['last-event-id']);
<ide> for (var i = 0; i < source.history.length; i++)
<del> if (source.history[i].id >= id)
<add> if (source.history[i].id > id)
<ide> source.sendSSE(res, source.history[i].id,
<ide> source.history[i].event, source.history[i].msg);
<ide> } else res.write('id\n\n'); // Reset id. |
|
Java | agpl-3.0 | 51b7b91c8a84939a4ea2b4e685e7bc9cc74e9ee0 | 0 | rdkgit/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github | //
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc. All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information contact:
// OpenNMS Licensing <[email protected]>
// http://www.opennms.org/
// http://www.opennms.com/
//
package org.opennms.netmgt.model;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.core.style.ToStringCreator;
@Entity
@Table(name="notifications")
public class OnmsNotification {
private static final long serialVersionUID = -1162549324168290004L;
/** identifier field */
private Integer m_notifyId;
/** persistent field */
private String m_textMsg;
/** nullable persistent field */
private String m_subject;
/** nullable persistent field */
private String m_numericMsg;
/** nullable persistent field */
private Date m_pageTime;
/** nullable persistent field */
private Date m_respondTime;
/** nullable persistent field */
private String m_answeredBy;
/** nullable persistent field */
private OnmsServiceType m_serviceType;
/** nullable persistent field */
private String m_queueId;
/** persistent field */
private OnmsEvent m_event;
/** persistent field */
private OnmsNode m_node;
/** persistent field */
private Set<OnmsUserNotification> m_usersNotified = new HashSet<OnmsUserNotification>();
private String m_ipAddress;
/**
* persistent field representing the name of the configured notification from
* notifications.xml
*/
private String m_notifConfigName;
/** full constructor */
public OnmsNotification(Integer notifyId, String textMsg, String subject, String numericMsg,
Date pageTime, Date respondTime, String answeredBy, String ipAddress, OnmsServiceType serviceType,
String queueId, OnmsEvent event, OnmsNode node, Set<OnmsUserNotification> usersNotified, String notifConfigName) {
m_notifyId = notifyId;
m_textMsg = textMsg;
m_subject = subject;
m_numericMsg = numericMsg;
m_pageTime = pageTime;
m_respondTime = respondTime;
m_answeredBy = answeredBy;
m_ipAddress = ipAddress;
m_serviceType = serviceType;
m_queueId = queueId;
m_event = event;
m_node = node;
m_usersNotified = usersNotified;
m_notifConfigName = notifConfigName;
}
/** default constructor */
public OnmsNotification() {
}
/** minimal constructor */
public OnmsNotification(Integer notifyId, String textMsg, OnmsEvent event, OnmsNode node, Set<OnmsUserNotification> usersNotified) {
m_notifyId = notifyId;
m_textMsg = textMsg;
m_event = event;
m_node = node;
m_usersNotified = usersNotified;
}
@Id
@SequenceGenerator(name="notifySequence", sequenceName="notifyNxtId")
@GeneratedValue(generator="notifySequence")
public Integer getNotifyId() {
return m_notifyId;
}
public void setNotifyId(Integer notifyid) {
m_notifyId = notifyid;
}
@Column(name="textMsg", length=4000, nullable=false)
public String getTextMsg() {
return m_textMsg;
}
public void setTextMsg(String textmsg) {
m_textMsg = textmsg;
}
@Column(name="subject", length=256)
public String getSubject() {
return m_subject;
}
public void setSubject(String subject) {
m_subject = subject;
}
@Column(name="numericMsg", length=256)
public String getNumericMsg() {
return m_numericMsg;
}
public void setNumericMsg(String numericmsg) {
m_numericMsg = numericmsg;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="pageTime")
public Date getPageTime() {
return m_pageTime;
}
public void setPageTime(Date pagetime) {
m_pageTime = pagetime;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="respondTime")
public Date getRespondTime() {
return m_respondTime;
}
public void setRespondTime(Date respondtime) {
m_respondTime = respondtime;
}
@Column(name="answeredBy", length=256)
public String getAnsweredBy() {
return m_answeredBy;
}
public void setAnsweredBy(String answeredby) {
m_answeredBy = answeredby;
}
@Column(name="interfaceId", length=16)
public String getIpAddress() {
return m_ipAddress;
}
public void setIpAddress(String ipAddress) {
m_ipAddress = ipAddress;
}
@ManyToOne
@JoinColumn(name="serviceId")
public OnmsServiceType getServiceType() {
return m_serviceType;
}
public void setServiceType(OnmsServiceType serviceType) {
m_serviceType = serviceType;
}
@Column(name="queueId", length=256)
public String getQueueId() {
return m_queueId;
}
public void setQueueId(String queueid) {
m_queueId = queueid;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="eventId", nullable=false)
public OnmsEvent getEvent() {
return m_event;
}
public void setEvent(OnmsEvent event) {
m_event = event;
}
@ManyToOne
@JoinColumn(name="nodeId", nullable=false)
public OnmsNode getNode() {
return m_node;
}
public void setNode(OnmsNode node) {
m_node = node;
}
/**
* @hibernate.set
* lazy="true"
* inverse="true"
* cascade="none"
* @hibernate.key
* column="notifyid"
* @hibernate.one-to-many
* class="org.opennms.netmgt.model.OnmsUserNotification"
*
* old XDoclet1 Tags
* hibernate.collection-key
* column="notifyid"
* hibernate.collection-one-to-many
* class="org.opennms.netmgt.model.OnmsUserNotification"
*
*/
@OneToMany(mappedBy="notification", fetch=FetchType.LAZY)
public Set<OnmsUserNotification> getUsersNotified() {
return m_usersNotified;
}
public void setUsersNotified(Set<OnmsUserNotification> usersnotifieds) {
m_usersNotified = usersnotifieds;
}
public String toString() {
return new ToStringCreator(this)
.append("notifyid", getNotifyId())
.toString();
}
public String getNotifConfigName() {
return m_notifConfigName;
}
@Column(name="notifConfigName", length=63 )
public void setNotifConfigName(String notifConfigName) {
m_notifConfigName = notifConfigName;
}
}
| opennms-model/src/main/java/org/opennms/netmgt/model/OnmsNotification.java | //
// This file is part of the OpenNMS(R) Application.
//
// OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc. All rights reserved.
// OpenNMS(R) is a derivative work, containing both original code, included code and modified
// code that was published under the GNU General Public License. Copyrights for modified
// and included code are below.
//
// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
//
// Original code base Copyright (C) 1999-2001 Oculan Corp. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information contact:
// OpenNMS Licensing <[email protected]>
// http://www.opennms.org/
// http://www.opennms.com/
//
package org.opennms.netmgt.model;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.springframework.core.style.ToStringCreator;
@Entity
@Table(name="notifications")
public class OnmsNotification {
private static final long serialVersionUID = -1162549324168290004L;
/** identifier field */
private Integer m_notifyId;
/** persistent field */
private String m_textMsg;
/** nullable persistent field */
private String m_subject;
/** nullable persistent field */
private String m_numericMsg;
/** nullable persistent field */
private Date m_pageTime;
/** nullable persistent field */
private Date m_respondTime;
/** nullable persistent field */
private String m_answeredBy;
/** nullable persistent field */
private OnmsServiceType m_serviceType;
/** nullable persistent field */
private String m_queueId;
/** persistent field */
private OnmsEvent m_event;
/** persistent field */
private OnmsNode m_node;
/** persistent field */
private Set<OnmsUserNotification> m_usersNotified = new HashSet<OnmsUserNotification>();
private String m_ipAddress;
/** full constructor */
public OnmsNotification(Integer notifyId, String textMsg, String subject, String numericMsg, Date pageTime, Date respondTime, String answeredBy, String ipAddress, OnmsServiceType serviceType, String queueId, OnmsEvent event, OnmsNode node, Set<OnmsUserNotification> usersNotified) {
m_notifyId = notifyId;
m_textMsg = textMsg;
m_subject = subject;
m_numericMsg = numericMsg;
m_pageTime = pageTime;
m_respondTime = respondTime;
m_answeredBy = answeredBy;
m_ipAddress = ipAddress;
m_serviceType = serviceType;
m_queueId = queueId;
m_event = event;
m_node = node;
m_usersNotified = usersNotified;
}
/** default constructor */
public OnmsNotification() {
}
/** minimal constructor */
public OnmsNotification(Integer notifyId, String textMsg, OnmsEvent event, OnmsNode node, Set<OnmsUserNotification> usersNotified) {
m_notifyId = notifyId;
m_textMsg = textMsg;
m_event = event;
m_node = node;
m_usersNotified = usersNotified;
}
@Id
@SequenceGenerator(name="notifySequence", sequenceName="notifyNxtId")
@GeneratedValue(generator="notifySequence")
public Integer getNotifyId() {
return m_notifyId;
}
public void setNotifyId(Integer notifyid) {
m_notifyId = notifyid;
}
@Column(name="textMsg", length=4000, nullable=false)
public String getTextMsg() {
return m_textMsg;
}
public void setTextMsg(String textmsg) {
m_textMsg = textmsg;
}
@Column(name="subject", length=256)
public String getSubject() {
return m_subject;
}
public void setSubject(String subject) {
m_subject = subject;
}
@Column(name="numericMsg", length=256)
public String getNumericMsg() {
return m_numericMsg;
}
public void setNumericMsg(String numericmsg) {
m_numericMsg = numericmsg;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="pageTime")
public Date getPageTime() {
return m_pageTime;
}
public void setPageTime(Date pagetime) {
m_pageTime = pagetime;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="respondTime")
public Date getRespondTime() {
return m_respondTime;
}
public void setRespondTime(Date respondtime) {
m_respondTime = respondtime;
}
@Column(name="answeredBy", length=256)
public String getAnsweredBy() {
return m_answeredBy;
}
public void setAnsweredBy(String answeredby) {
m_answeredBy = answeredby;
}
@Column(name="interfaceId", length=16)
public String getIpAddress() {
return m_ipAddress;
}
public void setIpAddress(String ipAddress) {
m_ipAddress = ipAddress;
}
@ManyToOne
@JoinColumn(name="serviceId")
public OnmsServiceType getServiceType() {
return m_serviceType;
}
public void setServiceType(OnmsServiceType serviceType) {
m_serviceType = serviceType;
}
@Column(name="queueId", length=256)
public String getQueueId() {
return m_queueId;
}
public void setQueueId(String queueid) {
m_queueId = queueid;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="eventId", nullable=false)
public OnmsEvent getEvent() {
return m_event;
}
public void setEvent(OnmsEvent event) {
m_event = event;
}
@ManyToOne
@JoinColumn(name="nodeId", nullable=false)
public OnmsNode getNode() {
return m_node;
}
public void setNode(OnmsNode node) {
m_node = node;
}
/**
* @hibernate.set
* lazy="true"
* inverse="true"
* cascade="none"
* @hibernate.key
* column="notifyid"
* @hibernate.one-to-many
* class="org.opennms.netmgt.model.OnmsUserNotification"
*
* old XDoclet1 Tags
* hibernate.collection-key
* column="notifyid"
* hibernate.collection-one-to-many
* class="org.opennms.netmgt.model.OnmsUserNotification"
*
*/
@OneToMany(mappedBy="notification", fetch=FetchType.LAZY)
public Set<OnmsUserNotification> getUsersNotified() {
return m_usersNotified;
}
public void setUsersNotified(Set<OnmsUserNotification> usersnotifieds) {
m_usersNotified = usersnotifieds;
}
public String toString() {
return new ToStringCreator(this)
.append("notifyid", getNotifyId())
.toString();
}
}
| Make event trouble ticket column available to notifications. For auto resolving notifications, make
recreate all the original notification paramters configured in notifications.xml not just the few
found in the tables.
| opennms-model/src/main/java/org/opennms/netmgt/model/OnmsNotification.java | Make event trouble ticket column available to notifications. For auto resolving notifications, make recreate all the original notification paramters configured in notifications.xml not just the few found in the tables. | <ide><path>pennms-model/src/main/java/org/opennms/netmgt/model/OnmsNotification.java
<ide> //
<ide> package org.opennms.netmgt.model;
<ide>
<del>import java.io.Serializable;
<ide> import java.util.Date;
<ide> import java.util.HashSet;
<ide> import java.util.Set;
<ide> import javax.persistence.Table;
<ide> import javax.persistence.Temporal;
<ide> import javax.persistence.TemporalType;
<del>import javax.persistence.Transient;
<ide>
<ide> import org.springframework.core.style.ToStringCreator;
<ide>
<ide> private Set<OnmsUserNotification> m_usersNotified = new HashSet<OnmsUserNotification>();
<ide>
<ide> private String m_ipAddress;
<add>
<add> /**
<add> * persistent field representing the name of the configured notification from
<add> * notifications.xml
<add> */
<add> private String m_notifConfigName;
<ide>
<ide> /** full constructor */
<del> public OnmsNotification(Integer notifyId, String textMsg, String subject, String numericMsg, Date pageTime, Date respondTime, String answeredBy, String ipAddress, OnmsServiceType serviceType, String queueId, OnmsEvent event, OnmsNode node, Set<OnmsUserNotification> usersNotified) {
<add> public OnmsNotification(Integer notifyId, String textMsg, String subject, String numericMsg,
<add> Date pageTime, Date respondTime, String answeredBy, String ipAddress, OnmsServiceType serviceType,
<add> String queueId, OnmsEvent event, OnmsNode node, Set<OnmsUserNotification> usersNotified, String notifConfigName) {
<ide> m_notifyId = notifyId;
<ide> m_textMsg = textMsg;
<ide> m_subject = subject;
<ide> m_event = event;
<ide> m_node = node;
<ide> m_usersNotified = usersNotified;
<add> m_notifConfigName = notifConfigName;
<ide> }
<ide>
<ide> /** default constructor */
<ide> .toString();
<ide> }
<ide>
<add> public String getNotifConfigName() {
<add> return m_notifConfigName;
<add> }
<add>
<add> @Column(name="notifConfigName", length=63 )
<add> public void setNotifConfigName(String notifConfigName) {
<add> m_notifConfigName = notifConfigName;
<add> }
<add>
<ide> } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.