From 5ff8e00b794ff2f7559c8762d2d8d695a863b602 Mon Sep 17 00:00:00 2001 From: "weilin.zhu" Date: Thu, 6 Jul 2023 16:27:52 +0800 Subject: [PATCH 01/14] =?UTF-8?q?=E4=B8=AD=E5=9B=BD=E8=88=B9=E8=88=B6?= =?UTF-8?q?=E5=B7=A5=E4=B8=9A=E5=87=AD=E8=AF=81=E6=8E=A5=E5=8F=A3=E5=BC=80?= =?UTF-8?q?=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cssc/formmode/PushNcModeExpand.java | 147 ++++++ .../schedule/cron/PushEmployeeCronJob.java | 106 +++++ .../schedule/cron/PushModeDataCronJob.java | 88 ++++ .../schedule/sqlmapper/PushDataSqlMapper.java | 119 +++++ .../cssc/schedule/util/PushModeDataUtil.java | 144 ++++++ .../voucher/action/VoucherPushAction.java | 227 ++++++++++ .../voucher/sqlmapper/VoucherSqlMapper.java | 120 +++++ .../voucher/util/InterfaceLoggerDao.java | 80 ++++ .../voucher/util/VoucherConstants.java | 94 ++++ .../workflow/voucher/util/VoucherUtil.java | 367 +++++++++++++++ .../java/weaver/zwl/common/ToolUtilNew.java | 426 ++++++++++++++++++ 11 files changed, 1918 insertions(+) create mode 100644 src/main/java/weaver/cssc/formmode/PushNcModeExpand.java create mode 100644 src/main/java/weaver/cssc/schedule/cron/PushEmployeeCronJob.java create mode 100644 src/main/java/weaver/cssc/schedule/cron/PushModeDataCronJob.java create mode 100644 src/main/java/weaver/cssc/schedule/sqlmapper/PushDataSqlMapper.java create mode 100644 src/main/java/weaver/cssc/schedule/util/PushModeDataUtil.java create mode 100644 src/main/java/weaver/cssc/workflow/voucher/action/VoucherPushAction.java create mode 100644 src/main/java/weaver/cssc/workflow/voucher/sqlmapper/VoucherSqlMapper.java create mode 100644 src/main/java/weaver/cssc/workflow/voucher/util/InterfaceLoggerDao.java create mode 100644 src/main/java/weaver/cssc/workflow/voucher/util/VoucherConstants.java create mode 100644 src/main/java/weaver/cssc/workflow/voucher/util/VoucherUtil.java create mode 100644 src/main/java/weaver/zwl/common/ToolUtilNew.java diff --git a/src/main/java/weaver/cssc/formmode/PushNcModeExpand.java b/src/main/java/weaver/cssc/formmode/PushNcModeExpand.java new file mode 100644 index 0000000..63bf5d4 --- /dev/null +++ b/src/main/java/weaver/cssc/formmode/PushNcModeExpand.java @@ -0,0 +1,147 @@ +package weaver.cssc.formmode; + +import aiyh.utils.Util; +import aiyh.utils.httpUtil.HttpArgsType; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import cn.hutool.json.JSONUtil; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import weaver.cssc.schedule.util.PushModeDataUtil; +import weaver.cssc.workflow.voucher.util.VoucherConstants; +import weaver.formmode.customjavacode.AbstractModeExpandJavaCodeNew; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.zwl.common.ToolUtilNew; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 中国船舶工业 + * 建模数据推送NC 页面扩展 + * @author bleach + * @Date 2023-06-19 + */ +public class PushNcModeExpand extends AbstractModeExpandJavaCodeNew { + + /** + * 日志操作类 + */ + private final Logger logger = Util.getLogger(); + + /** + * 执行模块扩展动作 + * @param param 参数集合 + * param包含(但不限于)以下数据 + * user 当前用户 + * importtype 导入方式(仅在批量导入的接口动作会传输) 1 追加,2覆盖,3更新,获取方式(int)param.get("importtype") + * 导入链接中拼接的特殊参数(仅在批量导入的接口动作会传输),比如a=1,可通过param.get("a")获取参数值 + * 页面链接拼接的参数,比如b=2,可以通过param.get("b")来获取参数 + * @return 返回扩展操作结果 + */ + @Override + public Map doModeExpand(Map param) { + logger.info("-----------PushNcModeExpand Begin ------"); + + Map result = new HashMap<>(); + try { + User user = (User)param.get("user"); + int billId = -1;//数据id + int modeId = -1;//模块id + + RequestInfo requestInfo = (RequestInfo)param.get("RequestInfo"); + if(requestInfo != null) { + billId = Util.getIntValue(requestInfo.getRequestid()); + modeId = Util.getIntValue(requestInfo.getWorkflowid()); + + logger.info("modeId:[" + modeId + "],billId:[" + billId + "]"); + + if (billId > 0 && modeId > 0) { + //------请在下面编写业务逻辑代码------ + PushModeDataUtil dataUtil = new PushModeDataUtil(); + + //获取当前模块对应配置 + Map configMap = dataUtil.getConfigurationByModeId(modeId); + + logger.info("配置信息:[" + JSONUtil.toJsonPrettyStr(dataUtil) + "]"); + + //获取标识字段ID + int flagFieldId = Util.getIntValue(configMap.get("flagField").toString(),0); + //外键字段 + int foreignKeyId = Util.getIntValue(configMap.get("foreignKeyField").toString(),0); + + if(flagFieldId > 0){ + String flagFieldName = ToolUtilNew.getFieldNameByFieldIdStatic(flagFieldId); + + String foreignKeyName = ""; + if(foreignKeyId > 0){ + foreignKeyName = ToolUtilNew.getFieldNameByFieldIdStatic(foreignKeyId); + } + + //获取该模块对应的表名称 + String billTableName = (String) configMap.get("tableName"); + + //接口请求地址 + String requestURL = (String) configMap.get("requestURL"); + + if(StringUtils.isNotBlank(requestURL)){ + Map dataMap = dataUtil.getModeDataByKeyId(billTableName,flagFieldName,billId); + + logger.info("当前数据信息:[" + JSONUtil.toJsonPrettyStr(dataMap) + "]"); + + if(!dataMap.isEmpty()){ + List> fieldList = (List>) configMap.get("fieldList"); + + JSONObject jsonObject = dataUtil.generateJSONObject(fieldList,dataMap); + + HttpUtils httpUtils = new HttpUtils(); + + Map headerMap = new HashMap<>(); + headerMap.put("Content-Type", HttpArgsType.APPLICATION_JSON); + + ResponeVo responeVo = httpUtils.apiPostObject(requestURL,jsonObject,headerMap); + + if(responeVo.getCode() == VoucherConstants.REQUEST_SUCCESS_CODE){ + //接口返回信息转成Map对象 + Map resultMap = responeVo.getResponseMap(); + + int code = Util.getIntValue(Util.null2String(resultMap.get("code")),-1); + + boolean writeStatus; + if(code == 0){//成功 + String foreignKeyValue = (String) resultMap.get("pk"); + + writeStatus = dataUtil.writeBackStatus(true, billTableName, flagFieldName, foreignKeyName, foreignKeyValue, billId); + } else { + writeStatus = dataUtil.writeBackStatus(false,billTableName,flagFieldName,foreignKeyName,"",billId); + } + + logger.info("接口调用结果回写表单结果:[" + writeStatus + "]"); + } else { + logger.info("接口请求失败,失败状态码:[" + responeVo.getCode() + "]"); + } + } else { + logger.info("当前记录:[" + billId + "]不满足条件!"); + } + } + } else { + logger.info("推送标识字段未配置!"); + } + } + } + result.put("flag", "true"); + } catch (Exception e) { + logger.info(Util.getErrString(e)); + result.put("errmsg","自定义出错信息"); + result.put("flag", "false"); + } + + logger.info("-----------PushNcModeExpand End ------"); + return result; + } + + +} diff --git a/src/main/java/weaver/cssc/schedule/cron/PushEmployeeCronJob.java b/src/main/java/weaver/cssc/schedule/cron/PushEmployeeCronJob.java new file mode 100644 index 0000000..f248972 --- /dev/null +++ b/src/main/java/weaver/cssc/schedule/cron/PushEmployeeCronJob.java @@ -0,0 +1,106 @@ +package weaver.cssc.schedule.cron; + +import aiyh.utils.Util; +import aiyh.utils.httpUtil.HttpArgsType; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import weaver.cssc.schedule.sqlmapper.PushDataSqlMapper; +import weaver.cssc.workflow.voucher.util.VoucherConstants; +import weaver.general.TimeUtil; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.zwl.common.ToolUtilNew; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 中国船舶工业 + * 人员数据推送NC 计划任务类 + * @author bleach + * @Date 2023-06-25 + */ +public class PushEmployeeCronJob extends BaseCronJob { + + /** + * 日志操作 + */ + private final Logger logger = Util.getLogger(); + + /** + * SQL接口 + */ + private final PushDataSqlMapper sqlMapper = Util.getMapper(PushDataSqlMapper.class); + /** + * 实现父类 + * 具体的业务实现 + */ + @Override + public void execute() { + //获取上一次同步时间戳 + String lastSyncTs = ToolUtilNew.getStaticSystemParamValue("LastEmployeeSyncTimeStamp"); + + if(StringUtils.isBlank(lastSyncTs)){ + lastSyncTs = "2000-01-01 00:00:01"; + } + + //获取接口地址 + String pushEmployeeRequestURL = ToolUtilNew.getStaticSystemParamValue("EmployeePushRequestURL"); + + if(StringUtils.isBlank(pushEmployeeRequestURL)){ + logger.error("人员推送接口地址配置不存在!配置参数标识:[EmployeePushRequestURL]"); + } + + //获取当前库中需要推送的人员信息 + String selectSqL = "select id as code,lastName as name,certificateNum as id from hrmresource h where status in (0,1,2,3) and created >= '" + lastSyncTs + "' or modified >= '" + lastSyncTs + "'"; + + List> employeeList = sqlMapper.getEmployeeInfo(selectSqL); + + //发送Http请求工具类 + HttpUtils httpUtils = new HttpUtils(); + + if(employeeList != null && employeeList.size() > 0){//遍历结果集 + for(Map employeeMap : employeeList){ + + int keyId = (int) employeeMap.get("code"); + + Map header = new HashMap<>(); + header.put("Content-Type", HttpArgsType.APPLICATION_JSON); + + try { + ResponeVo responeVo = httpUtils.apiPostObject(pushEmployeeRequestURL,employeeMap,header); + + if(responeVo.getCode() == VoucherConstants.REQUEST_SUCCESS_CODE){ + Map resultMap = responeVo.getResponseMap(); + + if(!resultMap.isEmpty()){ + int code = (int) resultMap.get("code"); + + if(code == 1){ + String pk = (String) resultMap.get("pk"); + + sqlMapper.writeBackKeyToEmployee(pk,keyId); + } + } + } else { + //人员接口推送失败 + logger.error("人员接口推送失败,失败状态码:[" + responeVo.getCode() + "]"); + return; + } + } catch (IOException e) { + logger.info(Util.getErrString(e)); + throw new RuntimeException(e); + } + } + } + + //获取当前时间戳 + String currentTs = TimeUtil.getCurrentTimeString(); + + //更新时间戳至配置表中 + sqlMapper.updateTimeStampToConfig(currentTs); + } +} diff --git a/src/main/java/weaver/cssc/schedule/cron/PushModeDataCronJob.java b/src/main/java/weaver/cssc/schedule/cron/PushModeDataCronJob.java new file mode 100644 index 0000000..ca8c5a0 --- /dev/null +++ b/src/main/java/weaver/cssc/schedule/cron/PushModeDataCronJob.java @@ -0,0 +1,88 @@ +package weaver.cssc.schedule.cron; + +import aiyh.utils.Util; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; +import weaver.conn.constant.DBConstant; +import weaver.cssc.schedule.sqlmapper.PushDataSqlMapper; +import weaver.cssc.schedule.util.PushModeDataUtil; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.zwl.common.ToolUtilNew; + +import java.util.List; +import java.util.Map; + +/** + * 中国船舶工业 + * 建模数据推送NC 计划任务类 + * @author bleach + * @Date 2023-06-19 + */ +public class PushModeDataCronJob extends BaseCronJob { + + /** + * 当前类日志 + */ + private final Logger logger = Util.getLogger(); + + /** + * 配置数据ID + */ + private String configId; + + /** + * 推送数据操作数据接口 + */ + private final PushDataSqlMapper sqlMapper = Util.getMapper(PushDataSqlMapper.class); + + /** + * 实现父类方法 + */ + @Override + public void execute() { + logger.info("-------------- PushModeDataCronJob BEGIN ---------------"); + + logger.info("configId:[" + configId + "]"); + + PushModeDataUtil dataUtil = new PushModeDataUtil(); + + //配置集合 + Map configMap = dataUtil.getConfigurationByKeyId(configId); + + if(configMap != null && configMap.size() > 0){ + //模块表名称 + String modeTable = Util.null2String(configMap.get("tableName")); + //获取标识字段 + int flagField = (int) configMap.get("flagField"); + + if(flagField > 0){ + //获取标识字段名称 + String flagFieldName = Util.null2String(ToolUtilNew.getFieldNameByFieldIdStatic(flagField)); + + if(StringUtils.isNotBlank(flagFieldName) && StringUtils.isNotBlank(modeTable)){ + //查询表中已数据集 + String selectSQL = "select * from " + modeTable + " where " + flagFieldName + " is null or " + flagFieldName + " in (0,2)"; + + //待推送数据集合 + List> dataList = sqlMapper.getTodoPushModeDataList(selectSQL); + + + } + } + } + + logger.info("-------------- PushModeDataCronJob END ---------------"); + } + + + + + public String getConfigId() { + return configId; + } + + public void setConfigId(String configId) { + this.configId = configId; + } +} diff --git a/src/main/java/weaver/cssc/schedule/sqlmapper/PushDataSqlMapper.java b/src/main/java/weaver/cssc/schedule/sqlmapper/PushDataSqlMapper.java new file mode 100644 index 0000000..1561c97 --- /dev/null +++ b/src/main/java/weaver/cssc/schedule/sqlmapper/PushDataSqlMapper.java @@ -0,0 +1,119 @@ +package weaver.cssc.schedule.sqlmapper; + +import aiyh.utils.annotation.recordset.*; + +import java.util.List; +import java.util.Map; + +/** + * 中国船舶工业 + * + * 建模数据推送NC生成SQL操作接口 + */ +@SqlMapper +public interface PushDataSqlMapper { + /** + * 获取建模数据推送NC配置 + * @param keyId 配置数据ID + * @return 配置信息集合 + */ + @CaseConversion(value = false) + @Select("select wb.tableName,u.* from uf_modeToNc u inner join modeInfo m on u.modeId = m.id \n" + + "inner join workflow_bill wb on m.formid = wb.id where u.id = #{keyId}") + Map getPushDataConfiguration(@ParamMapper("keyId") String keyId); + + /** + * 根据模块ID获取其对应的表单名称 + * @param modeId 模块ID + * @return 表单名称 + */ + @Select("select wb.tableName from modeInfo m inner join workflow_bill wb on m.formid = wb.id where m.id = #{modeId}") + String getTableNameByModeId(@ParamMapper("modeId") int modeId); + + /** + * 获取建模数据推送NC配置 + * @param modeId 模块ID + * @return 配置信息集合 + */ + @CaseConversion(value = false) + @Select("select wb.tableName,u.* from uf_modeToNc u inner join modeInfo m on u.modeId = m.id \n" + + "inner join workflow_bill wb on m.formid = wb.id where u.modeId = #{modeId}") + Map getPushDataConfigurationByModeId(@ParamMapper("modeId") int modeId); + + /** + * 获取建模数据推送NC配置明细 + * @param mainId 配置主表主键ID + * @return 配置信息集合 + */ + @CaseConversion(value = false) + @Select("select dt.*,wb.fieldName from uf_modeToNc_dt1 dt left join workflow_billfield wb on dt.mField = wb.id where mainId = #{mainId}") + List> getPushDataDetailConfiguration(@ParamMapper("mainId") int mainId); + + + /** + * 查询某条待推送数据的详细信息 + * @param sql 自定义SQL + * @return 待推送数据集合 + */ + @CaseConversion(value = false) + @Select(custom = true) + Map getTodoPushModeDataInfo(@SqlString String sql); + + /** + * 查询待推送的数据 + * @param sql 自定义SQL + * @return 待推送数据集合 + */ + @CaseConversion(value = false) + @Select(custom = true) + List> getTodoPushModeDataList(@SqlString String sql); + + + /** + * 回写成功状态至模块数据 + * @param billTable 模块表名称 + * @param flagFieldName 标识字段名称 + * @param foreignKeyName 外键字段名称 + * @param foreignKeyValue 外键字段值 + * @param keyId 数据ID + * @return 回写结果 + */ + @Update("update $t{billTable} set $t{flagFieldName} = 1,$t{foreignKeyName}=#{foreignKeyValue} where id = #{keyId}") + boolean writeBackSuccess(@ParamMapper("billTable") String billTable,@ParamMapper("flagFieldName") String flagFieldName,@ParamMapper("foreignKeyName") String foreignKeyName,@ParamMapper("foreignKeyValue") String foreignKeyValue,@ParamMapper("keyId") int keyId); + + + /** + * 回写失败状态至模块数据 + * @param billTable 模块表名称 + * @param flagFieldName 标识字段名称 + * @param keyId 数据ID + * @return 回写结果 + */ + @Update("update $t{billTable} set $t{flagFieldName} = 2 where id = #{keyId}") + boolean writeBackFailure(@ParamMapper("billTable") String billTable,@ParamMapper("flagFieldName") String flagFieldName,@ParamMapper("keyId") int keyId); + + + /** + * 查询人员信息 + * @param sql 查询信息SQL + * @return 返回满足条件的人员信息 + */ + @CaseConversion(value = false) + @Select(custom = true) + List> getEmployeeInfo(@SqlString String sql); + + /** + * 外键值更新至人员表自定义字段5中 + * @param pk 外键值 + * @param keyId 人员ID + */ + @Update("update hrmresource set textField5 = #{pk} where id = #{keyId}") + void writeBackKeyToEmployee(@ParamMapper("pk") String pk,@ParamMapper("keyId") int keyId); + + /** + * 更新时间戳至系统配置表中 + * @param timeStamp 时间戳 + */ + @Update("update uf_systemConfig set paramValue = #{timeStamp} where uuid = 'LastEmployeeSyncTimeStamp'") + void updateTimeStampToConfig(@ParamMapper("timeStamp") String timeStamp); +} diff --git a/src/main/java/weaver/cssc/schedule/util/PushModeDataUtil.java b/src/main/java/weaver/cssc/schedule/util/PushModeDataUtil.java new file mode 100644 index 0000000..279df99 --- /dev/null +++ b/src/main/java/weaver/cssc/schedule/util/PushModeDataUtil.java @@ -0,0 +1,144 @@ +package weaver.cssc.schedule.util; + +import aiyh.utils.Util; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import weaver.cssc.schedule.sqlmapper.PushDataSqlMapper; +import weaver.general.TimeUtil; +import weaver.zwl.common.ToolUtilNew; + +import java.util.List; +import java.util.Map; + +/** + * 中国船舶工业 + * 建模数据推送NC工具类 + * @author bleach + * @Date 2023-06-19 + */ +public class PushModeDataUtil { + + /** + * 数据库操作接口 + */ + private final PushDataSqlMapper sqlMapper = Util.getMapper(PushDataSqlMapper.class); + + + /** + * 获取某个模块对应的配置 + * @param keyId 配置ID + * @return 配置集合 + */ + public Map getConfigurationByKeyId(String keyId){ + Map configMap = sqlMapper.getPushDataConfiguration(keyId); + + if(configMap != null && configMap.size() > 0){ + int mainKeyId = (int) configMap.get("id"); + + List> fieldList = sqlMapper.getPushDataDetailConfiguration(mainKeyId); + + configMap.put("fieldList",fieldList); + } + + return configMap; + } + + /** + * 获取某个模块对应的配置 + * @param modeId 模块ID + * @return 配置集合 + */ + public Map getConfigurationByModeId(int modeId){ + Map configMap = sqlMapper.getPushDataConfigurationByModeId(modeId); + + if(configMap != null && configMap.size() > 0){ + int mainKeyId = (int) configMap.get("id"); + + List> fieldList = sqlMapper.getPushDataDetailConfiguration(mainKeyId); + + configMap.put("fieldList",fieldList); + } + + return configMap; + } + + + /** + * 根据配置生成要发送的JSON对象 + * @param fieldList 字段配置集合 + * @param dataMap 表单数据 + * @return 生成的JSON对象 + */ + public JSONObject generateJSONObject(List> fieldList,Map dataMap){ + JSONObject jsonObject = new JSONObject(); + + for(Map fieldMap : fieldList){ + //JSON节点名称 + String nodeName = Util.null2String(fieldMap.get("nodeName")); + //建模字段名称 + String fieldName = Util.null2String(fieldMap.get("fieldName")); + //转换规则 + int changeRule = (int) fieldMap.get("changeRule"); + //自定义规则 + String cusSQL = Util.null2String(fieldMap.get("cusSQL")); + + //字段值 + String fieldValue = ""; + if(StringUtils.isNotBlank(fieldName) && dataMap.containsKey(fieldName)){ + fieldValue = Util.null2String(dataMap.get(fieldName)); + } + + //数据ID 系统日期 系统日期时间 固定值 自定义规则 + switch (changeRule){ + case 0 ://不转换 + break; + case 1 ://数据ID + fieldValue = Util.null2String(dataMap.get("id")); + break; + case 2 ://系统日期 + fieldValue = TimeUtil.getCurrentDateString(); + break; + case 3 ://系统日期时间 + fieldValue = TimeUtil.getCurrentTimeString(); + break; + case 4 ://固定值 + fieldValue = cusSQL; + break; + case 5 ://自定义SQL + fieldValue = ToolUtilNew.getStaticValueByChangeRule(cusSQL,fieldValue); + break; + } + + jsonObject.put(nodeName,fieldValue); + } + + return jsonObject; + } + + /** + * 根据模块ID获取其对应的表单数据信息 + * @param keyId 模块数据ID + * @return 表单名称 + */ + public Map getModeDataByKeyId(String modeTableName,String flagFieldName,int keyId){ + //查询表中已数据集 + String selectSQL = "select * from " + modeTableName + " where id = " + keyId + " and (" + flagFieldName + " is null or " + flagFieldName + " in (0,2))"; + return sqlMapper.getTodoPushModeDataInfo(selectSQL); + } + + /** + * 回写接口调用状态至模块中 + * @param isSuccess 是否成功 + * @param billTableName 模块表单名称 + * @param flagFieldName 标识字段名称 + * @param keyId 数据ID + * @return 更新成功与否 + */ + public boolean writeBackStatus(boolean isSuccess,String billTableName,String flagFieldName,String foreignKeyName,String foreignKeyValue,int keyId){ + if(isSuccess){ + return sqlMapper.writeBackSuccess(billTableName,flagFieldName,foreignKeyName,foreignKeyValue,keyId); + } else { + return sqlMapper.writeBackFailure(billTableName,flagFieldName,keyId); + } + } +} diff --git a/src/main/java/weaver/cssc/workflow/voucher/action/VoucherPushAction.java b/src/main/java/weaver/cssc/workflow/voucher/action/VoucherPushAction.java new file mode 100644 index 0000000..3f7f944 --- /dev/null +++ b/src/main/java/weaver/cssc/workflow/voucher/action/VoucherPushAction.java @@ -0,0 +1,227 @@ +package weaver.cssc.workflow.voucher.action; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.httpUtil.HttpArgsType; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import weaver.conn.RecordSet; +import weaver.conn.RecordSetTrans; +import weaver.cssc.workflow.voucher.sqlmapper.VoucherSqlMapper; +import weaver.cssc.workflow.voucher.util.InterfaceLoggerDao; +import weaver.cssc.workflow.voucher.util.VoucherConstants; +import weaver.cssc.workflow.voucher.util.VoucherUtil; +import weaver.general.TimeUtil; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.zwl.common.ToolUtilNew; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +/** + * 中国船舶工业 + * 流程数据推送NC生成凭证Action + * @author bleach + * @Date 2023-06-19 + */ +public class VoucherPushAction extends SafeCusBaseAction { + + /** + * 日志操作类 + */ + private final Logger logger = Util.getLogger(); + + /** + * 自定义参数 + */ + private String cusParamValue = ""; + + /** + * 操作数据接口 + */ + private final VoucherSqlMapper sqlMapper = Util.getMapper(VoucherSqlMapper.class); + + /** + * 流程提交方法执行Action + * 具体的业务实现 + * @param requestId 流程请求ID + * @param billTable 流程表单名称 + * @param workflowId 流程类型ID + * @param user 当前用户 + * @param requestInfo 流程请求信息 + */ + @SuppressWarnings("unchecked") + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + logger.info("---------------- VoucherPushAction Begin -------------"); + + InterfaceLoggerDao interfaceLoggerDao = new InterfaceLoggerDao(); + + interfaceLoggerDao.setWorkflowId(workflowId); + interfaceLoggerDao.setSourceRequestId(requestId); + interfaceLoggerDao.setOperateDateTime(TimeUtil.getCurrentTimeString()); + + logger.info("workflowId:[" + workflowId + "],requestId:[" + requestId + "],billTable:[" + billTable + "]"); + VoucherUtil voucherUtil = new VoucherUtil(); + + Map configMap = voucherUtil.getConfigurationByWorkflowId(String.valueOf(workflowId),cusParamValue); + + if(configMap != null && configMap.size() > 0){ + //获取数据条件 + String dataCondition = (String) configMap.get("dataCondition"); + + RecordSet rs ; + + if(StringUtils.isNotBlank(dataCondition)){ + dataCondition = ToolUtilNew.staticToDBC(dataCondition); + + rs = sqlMapper.getWorkflowMainInfoAndCusWhere(billTable,requestId,dataCondition); + } else { + rs = sqlMapper.getWorkflowMainInfo(billTable,requestId); + } + + int mainId = -1; + if(rs.next()){ + mainId = Util.getIntValue(rs.getString("id"),-1); + } + + if(mainId > -1){ + //流程请求标题 + String requestName = ""; + //流程请求编号 + String requestMark = ""; + + //获取流程基础信息 + RecordSetTrans rsts = requestInfo.getRsTrans(); + + if(rsts == null){ + rsts = new RecordSetTrans(); + } + + try { + if(rsts.executeQuery("select * from workflow_requestBase where requestId = ?",requestId)){ + if(rsts.next()){ + requestName = Util.null2String(rsts.getString("requestName")); + requestMark = Util.null2String(rsts.getString("requestMark")); + } + } + } catch (Exception e) { + Util.actionFailException(requestInfo.getRequestManager(),"获取流程基本信息异常,异常信息:[" + e.getMessage() + "]!"); + throw new RuntimeException(e); + } + + interfaceLoggerDao.setRequestNo(requestMark); + interfaceLoggerDao.setOperator(user.getUID()); + + List> fieldList = (List>) configMap.get("fieldList"); + List> detailList = (List>) configMap.get("detailList"); + + voucherUtil.setDetailList(detailList); + voucherUtil.setFieldList(fieldList); + + //流程基础信息集合[流程请求ID,流程请求标题,流程请求编号,流程表单名称,主表数据ID] + String[] baseArray = new String[]{requestId,requestName,requestMark,billTable,String.valueOf(mainId)}; + + //根据配置生成JSON对象 + JSONObject jsonObject = voucherUtil.recursionGenerateJSONObject(baseArray,rs,null, 0,"",0,0); + + logger.info("生成JSON字符串为:[" + jsonObject.toJSONString() + "]"); + + interfaceLoggerDao.setRequestBody(jsonObject.toJSONString()); + + //NC凭证接口地址 + String voucherRequestURL = ToolUtilNew.getStaticSystemParamValue("NC_VoucherRequestURL"); + + if(StringUtils.isNotBlank(voucherRequestURL)){ + HttpUtils httpUtils = new HttpUtils(); + + try { + Map headerMap = new HashMap<>(); + headerMap.put("Content-Type", HttpArgsType.APPLICATION_JSON); + + ResponeVo responeVo = httpUtils.apiPostObject(voucherRequestURL,jsonObject,headerMap); + + if(responeVo.getCode() == VoucherConstants.REQUEST_SUCCESS_CODE){ + //获取返回信息 + String result = responeVo.getEntityString(); + + interfaceLoggerDao.setResponseBody(result); + + JSONObject resultObj = JSONObject.parseObject(result); + + if(resultObj.containsKey("code")){ + int code = resultObj.getIntValue("code"); + + if(code == 0){ + String pk = resultObj.getString("pk"); + + String backFieldName = (String) configMap.get("backFieldName"); + if(StringUtils.isNotBlank(backFieldName)){ + sqlMapper.backVoucherNoToBill(billTable,backFieldName,pk,requestId); + } + + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_SUCCESS); + interfaceLoggerDao.setDealMessage("接口调用成功!"); + } else { + String message = resultObj.getString("msg"); + + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); + interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,失败状态码:[" + message + "]!"); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + //接口调用失败 + Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口失败,失败状态码:[" + message + "]!"); + } + } else { + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); + interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,接口返回信息为空!"); + } + } else { + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); + interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,失败状态码:[" + responeVo.getCode() + "]!"); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口失败,失败状态码:[" + responeVo.getCode() + "]!"); + } + } catch (IOException e) { + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); + interfaceLoggerDao.setDealMessage("调用NC凭证接口异常,异常信息:" + e.getMessage()); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + logger.error(Util.getErrString(e)); + Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口异常!"); + //throw new RuntimeException(e); + } + } else { + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_NO_DEAL); + interfaceLoggerDao.setDealMessage("NC凭证接口地址未配置!"); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + Util.actionFailException(requestInfo.getRequestManager(),"NC凭证接口地址未配置!"); + } + } else { + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_NO_DEAL); + interfaceLoggerDao.setDealMessage("当前流程不满足自定义条件:[" + dataCondition + "]"); + logger.info("当前流程不满足自定义条件:[" + dataCondition + "]"); + } + } else { + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_NO_DEAL); + interfaceLoggerDao.setDealMessage("该流程自定义参数值[" + cusParamValue + "]对应的配置不存在!"); + logger.info("该流程自定义参数值[" + cusParamValue + "]对应的配置不存在!"); + } + + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + logger.info("---------------- VoucherPushAction End -------------"); + } + + public String getCusParamValue() { + return cusParamValue; + } + + public void setCusParamValue(String cusParamValue) { + this.cusParamValue = cusParamValue; + } +} diff --git a/src/main/java/weaver/cssc/workflow/voucher/sqlmapper/VoucherSqlMapper.java b/src/main/java/weaver/cssc/workflow/voucher/sqlmapper/VoucherSqlMapper.java new file mode 100644 index 0000000..110989d --- /dev/null +++ b/src/main/java/weaver/cssc/workflow/voucher/sqlmapper/VoucherSqlMapper.java @@ -0,0 +1,120 @@ +package weaver.cssc.workflow.voucher.sqlmapper; + +import aiyh.utils.annotation.recordset.*; +import weaver.conn.RecordSet; +import weaver.cssc.workflow.voucher.util.InterfaceLoggerDao; + +import java.util.List; +import java.util.Map; + +/** + * 中国船舶工业 + * 流程数据推送NC生成凭证 SQL操作接口 + */ +@SqlMapper +public interface VoucherSqlMapper { + + /** + * 根据类型类型ID获取其对应的配置信息 + * @param allWorkflowId 流程类型ID + * @return 返回数据集 + */ + @CaseConversion(value = false) + @Select("select * from uf_wfDataToNCVoucher where wfId in ($t{allWorkflowId})") + Map getConfigurationByWorkflowId(@ParamMapper("allWorkflowId") String allWorkflowId); + + /** + * 根据类型类型ID获取其对应的配置信息 + * @param allWorkflowId 流程类型ID + * @param cusParamValue 自定义参数值 + * @return 返回数据集 + */ + @CaseConversion(value = false) + @Select("select * from uf_wfDataToNCVoucher where wfId in ($t{allWorkflowId}) and cusParamValue = #{cusParamValue}") + Map getConfigurationByWorkflowIdAndParam( @ParamMapper("allWorkflowId") String allWorkflowId,@ParamMapper("cusParamValue") String cusParamValue); + + /** + * 获取配置明细表1的信息集合 + * @param mainId 主表主键ID + * @return 明细表1数据集 + */ + @CaseConversion(value = false) + @Select("select dt.* from uf_wfDataToNCVoucher_dt1 dt where dt.mainId = #{mainId}") + List> getFirstDetailConfiguration(@ParamMapper("mainId") int mainId); + + + /** + * 获取配置明细表2的信息集合 + * @param mainId 主表主键ID + * @return 明细表2数据集 + */ + @CaseConversion(value = false) + @Select("select dt.*,wb.fieldName,wb.viewType,wb.detailTable from uf_wfDataToNCVoucher_dt2 dt left join workflow_billField wb on dt.wfFieldId = wb.id where dt.mainId = #{mainId}") + List> getSecondDetailConfiguration( @ParamMapper("mainId") int mainId); + + + /** + * 获取流程主表信息 + * @param billTable 表单名称 + * @param requestId 流程请求ID + * @return 主表数据集 + */ + @CaseConversion(value = false) + @Select("select * from $t{billTable} where requestId = #{requestId}") + RecordSet getWorkflowMainInfo(@ParamMapper("billTable") String billTable, @ParamMapper("requestId") String requestId); + + + /** + * 获取流程主表信息 + * @param billTable 表单名称 + * @param requestId 流程请求ID + * @param sqlWhere 自定义条件 + * @return 主表数据集 + */ + @CaseConversion(value = false) + @Select("select * from $t{billTable} where requestId = #{requestId} and $t{sqlWhere}") + RecordSet getWorkflowMainInfoAndCusWhere( @ParamMapper("billTable") String billTable,@ParamMapper("requestId") String requestId,@ParamMapper("sqlWhere") String sqlWhere); + + /** + * 获取流程明细表信息 + * @param detailBillTable 明细表单名称 + * @param mainId 流程请求ID + * @return 主表数据集 + */ + @CaseConversion(value = false) + @Select("select * from $t{detailBillTable} where mainId = #{mainId}") + RecordSet getWorkflowDetailInfo(@ParamMapper("detailBillTable") String detailBillTable, @ParamMapper("mainId") String mainId); + + /** + * 获取流程明细表信息 + * @param detailBillTable 明细表单名称 + * @param mainId 流程请求ID + * @param sqlWhere 自定义条件 + * @return 主表数据集 + */ + @CaseConversion(value = false) + @Select("select * from $t{detailBillTable} where mainId = #{mainId} and $t{sqlWhere}") + RecordSet getWorkflowDetailInfoAndCusWhere(@ParamMapper("detailBillTable") String detailBillTable, @ParamMapper("mainId") String mainId,@ParamMapper("sqlWhere") String sqlWhere); + + /** + * U8凭证号回写流程主表字段 + * + * @param billTable 表单名称 + * @param backFieldName 回写字段名称 + * @param backFieldValue 回写的凭证号 + * @param requestId 流程请求ID + */ + @CaseConversion(value = false) + @Update("update $t{billTable} set $t{backFieldName} = #{backFieldValue} where requestId = #{requestId}") + void backVoucherNoToBill(@ParamMapper("billTable") String billTable,@ParamMapper("backFieldName") String backFieldName,@ParamMapper("backFieldValue") String backFieldValue,@ParamMapper("requestId") String requestId); + + + /** + * 写入接口日志 + * @param loggerDao 接口日志实体类 + */ + @Update("update uf_interfaceLog set sourceRequestId = #{sourceRequestId},requestNo = #{requestNo},workflowId = #{workflowId}," + + "operator = #{operator},operateDateTime = #{operateDateTime},dealStatus = #{dealStatus},dealMessage = #{dealMessage}," + + "requestBody = #{requestBody},responseBody = #{responseBody},interfaceType = #{interfaceType} where id = #{newDataId}") + boolean insertInterfaceLog(InterfaceLoggerDao loggerDao); +} diff --git a/src/main/java/weaver/cssc/workflow/voucher/util/InterfaceLoggerDao.java b/src/main/java/weaver/cssc/workflow/voucher/util/InterfaceLoggerDao.java new file mode 100644 index 0000000..d557703 --- /dev/null +++ b/src/main/java/weaver/cssc/workflow/voucher/util/InterfaceLoggerDao.java @@ -0,0 +1,80 @@ +package weaver.cssc.workflow.voucher.util; + +import aiyh.utils.Util; +import lombok.Data; +import weaver.cssc.workflow.voucher.sqlmapper.VoucherSqlMapper; + +/** + * 中国船舶工业 + * 接口日志实体类 + */ +@Data +public class InterfaceLoggerDao { + + /** + * 新的记录ID + */ + private int newDataId; + + /** + * 流程请求ID + */ + private String sourceRequestId; + + /** + * 流程请求编号 + */ + private String requestNo; + + /** + * 流程类型ID + */ + private int workflowId; + + /** + * 接口类型 + */ + private int interfaceType; + + /** + * 当前操作者ID + */ + private int operator; + + /** + * 操作日期时间 + */ + private String operateDateTime; + + /** + * 处理状态 + */ + private int dealStatus; + + /** + * 处理消息 + */ + private String dealMessage; + + /** + * 请求报文 + */ + private String requestBody; + + /** + * 响应报文 + */ + private String responseBody; + + + /** + * 接口日志写入操作 + * @param loggerDao 日志类文件 + * @return 返回日志写入结果 + */ + public boolean insertInterfaceLog(InterfaceLoggerDao loggerDao){ + VoucherSqlMapper sqlMapper = Util.getMapper(VoucherSqlMapper.class); + + return sqlMapper.insertInterfaceLog(loggerDao); + } +} diff --git a/src/main/java/weaver/cssc/workflow/voucher/util/VoucherConstants.java b/src/main/java/weaver/cssc/workflow/voucher/util/VoucherConstants.java new file mode 100644 index 0000000..d81db1b --- /dev/null +++ b/src/main/java/weaver/cssc/workflow/voucher/util/VoucherConstants.java @@ -0,0 +1,94 @@ +package weaver.cssc.workflow.voucher.util; + +/** + * 中国船舶工业 + * 流程数据推送NC生成凭证 常量类 + * + * @author bleach + * @Date 2023-06-19 + */ +public class VoucherConstants { + + /** + * JSON 节点类型 - 普通文本 + */ + public final static int JSON_NODE_TYPE_COMMON_TEXT = 0; + + + /** + * JSON 节点类型 - 数组文本 + */ + public final static int JSON_NODE_TYPE_ARRAY_TEXT = 1; + + + /** + * JSON 节点类型 - 普通对象 + */ + public final static int JSON_NODE_TYPE_COMMON_OBJECT = 2; + + + /** + * JSON 节点类型 - 数组对象 + */ + public final static int JSON_NODE_TYPE_ARRAY_OBJECT = 3; + + /** + * 凭证分录借贷方向 - 非凭证分录 + */ + public final static String VOUCHER_ENTRY_NO_VOUCHER = "0"; + + + /** + * 凭证分录借贷方向 - 普通借方 + */ + public final static String VOUCHER_ENTRY_COMMON_DEBIT = "1"; + + + /** + * 凭证分录借贷方向 - 税额借方 + */ + public final static String VOUCHER_ENTRY_TAX_DEBIT = "2"; + + /** + * 凭证分录借贷方向 - 普通贷方 + */ + public final static String VOUCHER_ENTRY_COMMON_CREDIT = "3"; + + /** + * 凭证分录借贷方向 - 冲销贷方 + */ + public final static String VOUCHER_ENTRY_WRITE_OFF_CREDIT = "4"; + + + /** + * 字段特殊属性 - 普通字段 + */ + public final static int FIELD_SPECIAL_COMMON = 0; + + + /** + * 字段特殊属性 - 金额字段 + */ + public final static int FIELD_SPECIAL_AMOUNT = 1; + + /** + * 接口请求 成功状态码 + */ + public final static int REQUEST_SUCCESS_CODE = 200; + + /** + * 处理状态 - 未处理 + */ + public final static int DEAL_STATUS_NO_DEAL = 0; + + /** + * 处理状态 - 处理成功 + */ + public final static int DEAL_STATUS_SUCCESS = 1; + + /** + * 处理状态 - 处理失败 + */ + public final static int DEAL_STATUS_FAILURE = 2; + +} diff --git a/src/main/java/weaver/cssc/workflow/voucher/util/VoucherUtil.java b/src/main/java/weaver/cssc/workflow/voucher/util/VoucherUtil.java new file mode 100644 index 0000000..ee6bd83 --- /dev/null +++ b/src/main/java/weaver/cssc/workflow/voucher/util/VoucherUtil.java @@ -0,0 +1,367 @@ +package weaver.cssc.workflow.voucher.util; + +import aiyh.utils.Util; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import weaver.conn.RecordSet; +import weaver.cssc.workflow.voucher.sqlmapper.VoucherSqlMapper; +import weaver.general.TimeUtil; +import weaver.workflow.workflow.WorkflowVersion; +import weaver.zwl.common.ToolUtilNew; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * 中国船舶工业 + * 流程数据推送NC生成凭证工具类 + * + * @author bleach + * @Date 2023-06-19 + */ +public class VoucherUtil { + + /** + * 数组与流程映射关系配置集合 + */ + private List> detailList = new ArrayList<>(); + + + /** + * 字段配置集合 + */ + private List> fieldList = new ArrayList<>(); + + + private final VoucherSqlMapper sqlMapper = Util.getMapper(VoucherSqlMapper.class); + + + /** + * 递归生成JSON对象 + * @param baseArray 流程基础信息【流程请求ID、流程请求标题、流程请求编号、流程主表名称、流程主表主键ID值】 + * @param rs 流程主表数据集 + * @param rs_detail 流程明细表某一行数据集 + * @param voucherDirection 节点方向 + * @param parentNode 父节点名称 + * @param dtIndex 明细表序列 + * @param rowNum 明细表序号 + * @return JSON对象 + */ + public JSONObject recursionGenerateJSONObject(String[] baseArray,RecordSet rs,RecordSet rs_detail,int voucherDirection,String parentNode,int dtIndex,int rowNum){ + JSONObject jsonObject = new JSONObject(); + + if(fieldList != null && fieldList.size() > 0){ + for(Map fieldMap : fieldList){ + //节点名称 + String _nodeName = (String) fieldMap.get("nodeName"); + //父节点名称 + String _parentNode = (String) fieldMap.get("parentNode"); + + if(!_parentNode.equals(parentNode)){//若当前字段配置与传入的父节点名称不一致直接跳过 + continue; + } + + //字段所属 0-主表 1-明细表 + int _viewType = Util.getIntValue(Util.null2String(fieldMap.get("viewType")),0); + //获取明细表表名称 + String _detailTable = (String) fieldMap.get("detailTable"); + + + if(_viewType == 1 && StringUtils.isNotBlank(_detailTable)){//明细记录 + int _dtIndex = Util.getIntValue(_detailTable.substring(_detailTable.indexOf("_dt") + 3),-1); + + if(_dtIndex != dtIndex){ + continue; + } + } + + String _voucherDirection = (String) fieldMap.get("voucherDirection"); + + if(voucherDirection > 0 && !_voucherDirection.contains(String.valueOf(voucherDirection))) {//说明为会计分录 ,且当前字段的所属分录与传入的分录不一致 + continue; + } + + + //节点类型 + int _nodeType = (int) fieldMap.get("nodeType"); + + switch (_nodeType){ + case VoucherConstants.JSON_NODE_TYPE_COMMON_TEXT : + String fieldValue = getFieldValue(baseArray,fieldMap,rs,rs_detail,rowNum); + + int specialAttr = (int) fieldMap.get("specialAttr"); + + if(VoucherConstants.FIELD_SPECIAL_AMOUNT == specialAttr){ + double amount = Util.getDoubleValue(fieldValue,0.0); + + if(amount == 0.0){ + return null; + } + } + + jsonObject.put(_nodeName,fieldValue); + break; + case VoucherConstants.JSON_NODE_TYPE_ARRAY_TEXT : + String arrayFieldValue = getFieldValue(baseArray,fieldMap,rs,rs_detail,rowNum); + + JSONArray fieldArray = new JSONArray(); + + String[] fieldVal = Util.TokenizerString2(arrayFieldValue,","); + + fieldArray.addAll(Arrays.asList(fieldVal)); + + jsonObject.put(_nodeName,fieldArray); + + break; + case VoucherConstants.JSON_NODE_TYPE_COMMON_OBJECT : + JSONObject _detailObj = recursionGenerateJSONObject(baseArray,rs,rs_detail,voucherDirection,_nodeName,dtIndex,rowNum); + jsonObject.put(_nodeName,_detailObj); + break; + case VoucherConstants.JSON_NODE_TYPE_ARRAY_OBJECT: + //获取该数组对应的明细映射配置 + if(detailList != null && detailList.size() > 0){ + JSONArray itemArray = new JSONArray(); + + int _rowNum = 0; + for(Map detailMap :detailList){ + //对象/数组节点名称 + String _arrayNode = (String) detailMap.get("arrayNode"); + + if(!_arrayNode.equals(_nodeName)){ + continue; + } + + //是否凭证分录 + int _isVoucher = (int) detailMap.get("isVoucher"); + + //明细序列 + int _dtIndex = (int) detailMap.get("dtIndex"); + + //借贷方向 + String _dtItemDirection = (String) detailMap.get("dtItemDirection"); + if(_dtIndex > 0){//明细表 + + //明细条件 + String _dtCondition = (String) detailMap.get("dtCondition"); + + String detailBillTable = baseArray[3] + "_dt" + _dtIndex; + + RecordSet _rs_detail; + + if(StringUtils.isNotBlank(_dtCondition)){ + _dtCondition = ToolUtilNew.staticToDBC(_dtCondition); + + _rs_detail = sqlMapper.getWorkflowDetailInfoAndCusWhere(detailBillTable,baseArray[4],_dtCondition); + } else { + _rs_detail = sqlMapper.getWorkflowDetailInfo(detailBillTable,baseArray[4]); + } + + while(_rs_detail.next()){ + if(_isVoucher == 0){//非凭证分录 + JSONObject detailObj = recursionGenerateJSONObject(baseArray,rs,_rs_detail,Util.getIntValue(VoucherConstants.VOUCHER_ENTRY_NO_VOUCHER,0),_nodeName,_dtIndex,_rowNum++); + + itemArray.add(detailObj); + } else { + for(int k = 1; k <= 4;k++){ + if(_dtItemDirection.contains(String.valueOf(k))) { + JSONObject detailObj = recursionGenerateJSONObject(baseArray,rs,_rs_detail,k,_nodeName,_dtIndex,_rowNum++); + + if(detailObj != null && detailObj.size() > 0){ + itemArray.add(detailObj); + } + } + } + } + } + + } else {//主表 + if(_isVoucher == 1){ + for(int k = 1; k <= 4;k++){ + if(_dtItemDirection.contains(String.valueOf(k))) { + JSONObject detailObj = recursionGenerateJSONObject(baseArray,rs,null,k,_nodeName,_dtIndex,_rowNum++); + + if(detailObj != null && detailObj.size() > 0){ + itemArray.add(detailObj); + } + } + } + /* + //判断是否存在借方 + if(_dtItemDirection.contains(VoucherConstants.VOUCHER_ENTRY_COMMON_DEBIT)){ + JSONObject detailObj = recursionGenerateJSONObject(baseArray,rs,null,Util.getIntValue(VoucherConstants.VOUCHER_ENTRY_COMMON_DEBIT,0),_nodeName,_dtIndex,rowNum++); + + if(detailObj != null && detailObj.size() > 0){ + itemArray.add(detailObj); + } + } + + //税额借方 + if(_dtItemDirection.contains(VoucherConstants.VOUCHER_ENTRY_TAX_DEBIT)){ + JSONObject detailObj = recursionGenerateJSONObject(baseArray,rs,null,Util.getIntValue(VoucherConstants.VOUCHER_ENTRY_TAX_DEBIT,0),_nodeName,_dtIndex,rowNum++); + + if(detailObj != null && detailObj.size() > 0){ + itemArray.add(detailObj); + } + } + + //普通贷方 + if(_dtItemDirection.contains(VoucherConstants.VOUCHER_ENTRY_COMMON_CREDIT)){ + JSONObject detailObj = recursionGenerateJSONObject(baseArray,rs,null,Util.getIntValue(VoucherConstants.VOUCHER_ENTRY_COMMON_CREDIT,0),_nodeName,_dtIndex,rowNum++); + + if(detailObj != null && detailObj.size() > 0){ + itemArray.add(detailObj); + } + } + + //冲销贷方 + if(_dtItemDirection.contains(VoucherConstants.VOUCHER_ENTRY_WRITE_OFF_CREDIT)){ + JSONObject detailObj = recursionGenerateJSONObject(baseArray,rs,null,Util.getIntValue(VoucherConstants.VOUCHER_ENTRY_WRITE_OFF_CREDIT,0),_nodeName,_dtIndex,rowNum++); + + if(detailObj != null && detailObj.size() > 0){ + itemArray.add(detailObj); + } + } + */ + + } else { + JSONObject detailObj = recursionGenerateJSONObject(baseArray,rs,null,Util.getIntValue(VoucherConstants.VOUCHER_ENTRY_NO_VOUCHER,0),_nodeName,_dtIndex,_rowNum++); + + itemArray.add(detailObj); + } + } + } + + jsonObject.put(_nodeName,itemArray); + } + break; + } + } + } + + return jsonObject; + } + + /** + * 根据字段转换规则,获取其最终值 + * @param baseArray 流程基础信息数组 + * @param fieldMap 字段配置映射 + * @param rs 主表数据集 + * @param rs_detail 明细表数据集 + * @param rowNum 明细行号 + * @return 最终值 + */ + private String getFieldValue(String[] baseArray,Map fieldMap,RecordSet rs,RecordSet rs_detail,int rowNum){ + String fieldValue = ""; + + //System.out.println("字段配置:[" + JSONObject.toJSONString(fieldMap) + "]"); + //字段名称 + String fieldName = Util.null2String(fieldMap.get("fieldName")); + //字段所属 + int viewType = Util.getIntValue(Util.null2String(fieldMap.get("viewType")),0); + //转换规则 + int changeRule = Util.getIntValue(Util.null2String(fieldMap.get("changeRule")),0); + //自定义转换 + String cusSQL = (String) fieldMap.get("cusSQL"); + + if(!"".equals(fieldName)){ + if(viewType == 0){ + fieldValue = Util.null2String(rs.getString(fieldName)); + } else if (viewType == 1 && rs_detail != null) { + fieldValue = Util.null2String(rs_detail.getString(fieldName)); + } + } + + switch (changeRule){ + case 0 : //不转换 + break; + case 1 : //流程请求ID + fieldValue = baseArray[0]; + break; + case 2 : //流程请求标题 + fieldValue = baseArray[1]; + break; + case 3 : //流程请求编号 + fieldValue = baseArray[2]; + break; + case 4 : //系统日期 + fieldValue = TimeUtil.getCurrentDateString(); + break; + case 5 : //系统时间 + fieldValue = TimeUtil.getCurrentTimeString(); + break; + case 6 : //固定值 + fieldValue = cusSQL; + break; + case 7 : //明细序列 + fieldValue = String.valueOf(rowNum); + break; + case 8 : //自定义转换 + int detailKey = -1; + + if(cusSQL.contains("{?dt.id}") && rs_detail != null){ + detailKey = Util.getIntValue(rs_detail.getString("id"),0); + } + + fieldValue = ToolUtilNew.getStaticValueByChangeRule(cusSQL,fieldValue,baseArray[0],detailKey); + break; + } + + //System.out.println("fieldValue:" + fieldValue); + return fieldValue; + } + + /** + * 根据流程类型获取其对应的配置信息集合 + * @param workflowId 流程类型ID + * @param cusParamValue 自定义参数值 + * @return 配置信息集合 + */ + public Map getConfigurationByWorkflowId(String workflowId,String cusParamValue){ + Map configMap ; + + //获取该流程类型对应的所有版本ID + String allWfIds = WorkflowVersion.getAllVersionStringByWFIDs(workflowId); + + if(StringUtils.isNotBlank(cusParamValue)){ + configMap = sqlMapper.getConfigurationByWorkflowIdAndParam(allWfIds,cusParamValue); + } else { + configMap = sqlMapper.getConfigurationByWorkflowId(allWfIds); + } + + + if(configMap != null && configMap.size() > 0){ + int mainId = (int) configMap.get("id"); + + //获取明细表1配置集合 + List> detailList = sqlMapper.getFirstDetailConfiguration(mainId); + + List> fieldList = sqlMapper.getSecondDetailConfiguration(mainId); + + + configMap.put("detailList",detailList); + configMap.put("fieldList",fieldList); + } + + return configMap; + } + + + public List> getDetailList() { + return detailList; + } + + public void setDetailList(List> detailList) { + this.detailList = detailList; + } + + public List> getFieldList() { + return fieldList; + } + + public void setFieldList(List> fieldList) { + this.fieldList = fieldList; + } +} diff --git a/src/main/java/weaver/zwl/common/ToolUtilNew.java b/src/main/java/weaver/zwl/common/ToolUtilNew.java new file mode 100644 index 0000000..6b74c17 --- /dev/null +++ b/src/main/java/weaver/zwl/common/ToolUtilNew.java @@ -0,0 +1,426 @@ +package weaver.zwl.common; + +import com.google.common.base.Strings; +import com.weaver.general.TimeUtil; +import org.apache.log4j.*; +import org.h2.util.StringUtils; +import weaver.conn.ConnStatementDataSource; +import weaver.conn.RecordSet; +import weaver.formmode.data.ModeDataIdUpdate; +import weaver.formmode.setup.ModeRightInfo; +import weaver.general.Util; + +import java.io.File; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +/** + * 工具类加强版 + */ +@SuppressWarnings("ALL") +public class ToolUtilNew extends ToolUtil{ + /** + * 建模数据权限处理类 + */ + public static final ModeRightInfo MODE_RIGHT_INFO = new ModeRightInfo(); + /** + * 建模新数据ID获取类 + */ + public static final ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance(); + /** + * 建模新创建的数据,默认用户为系统管理员 + */ + public static final int modeDataDefaultUserId = 1; + /** + * 日志操作类 + */ + private static volatile Logger log = null; + /** + * 其他自定义日志集合 + */ + private static final Map otherLog = new HashMap<>(8); + + /** + * 获取日志对象 + * 若不存在则动态注入值log4j中 + * @return 日志对象 + */ + @SuppressWarnings("deprecation") + public static Logger getLogger() { + if (log == null) { + synchronized (ToolUtilNew.class) { + if (log == null) { + DailyRollingFileAppender appender = new DailyRollingFileAppender(); + log = Logger.getLogger("ayh_cus"); + appender.setName("ayh_cus"); + appender.setEncoding("UTF-8"); + appender.setDatePattern("'_'yyyyMMdd'.log'"); + appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + "util_cus" + File.separator + "cus.log"); + appender.setThreshold(Priority.DEBUG); + appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); + appender.setAppend(true); + appender.activateOptions(); + log.addAppender(appender); + log.setLevel(Level.INFO); + } + } + } + return log; + } + + /** + * 获取日志类,若不存在则动态注入值log4j中 + * @param name 日志名称 + * @return 日志对象 + */ + public static Logger getLogger(String name) { + + if (otherLog.containsKey(name)) { + return otherLog.get(name); + } + if (!otherLog.containsKey(name)) { + synchronized (ToolUtilNew.otherLog) { + if (otherLog.containsKey(name)) { + return otherLog.get(name); + } + DailyRollingFileAppender appender = new DailyRollingFileAppender(); + Logger cusLog = Logger.getLogger("cus_" + name); + appender.setName("cus_" + name); + appender.setEncoding("UTF-8"); + appender.setDatePattern("'_'yyyyMMdd'.log'"); + appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + name + File.separator + "cus.log"); + appender.setThreshold(Priority.DEBUG); + appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); + appender.setAppend(true); + appender.activateOptions(); + cusLog.addAppender(appender); + cusLog.setLevel(Level.INFO); + otherLog.put(name, cusLog); + return cusLog; + } + } + return null; + } + + /** + * 获取建模模块ID通过表名 + * + * @param tableName 表名 + * @return 模块ID + */ + public static int getModeIdByTableName(String tableName) { + int modeId = 0; + String querySql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = ?)"; + RecordSet recordSet = new RecordSet(); + recordSet.executeQuery(querySql, tableName); + if (recordSet.next()) { + modeId = Util.getIntValue(recordSet.getString("id"),0); + } + return modeId; + } + + /** + * 获取建模表数据ID + * + * @param tableName 表名 + * @param formModeId 模块ID + * @return 数据ID + */ + public static int getModeDataNewId(String tableName, int formModeId) { + return getModeDataNewId(tableName, formModeId,modeDataDefaultUserId); + } + + /** + * 获取建模表数据ID + * + * @param tableName 表名 + * @param formModeId 模块ID + * @param userId 用户ID + * @return 数据ID + */ + public static int getModeDataNewId(String tableName, int formModeId, int userId) { + return mdu.getModeDataNewId(tableName, formModeId, userId, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString()); + } + + + /** + * 建模表数据权限重构 + * + * @param formId 表单ID + * @param id 数据ID + * @param userId 用户ID + */ + public static void rebuildModeDataShare(Integer formId, Integer id) { + rebuildModeDataShare(formId, id,modeDataDefaultUserId); + } + + /** + * 建模表数据权限重构 + * + * @param formId 表单ID + * @param id 数据ID + * @param userId 用户ID + */ + public static void rebuildModeDataShare(Integer formId, Integer id,Integer userId) { + MODE_RIGHT_INFO.rebuildModeDataShareByEdit(userId, formId, id); + } + + /** + * 获取配置表中与某个字符串相似的所有配置信息集合 + * @param likestr 模糊查询字符串 + * @return 配置集合 + */ + public static Map getSystemParamList(String likestr){ + return getSystemParamList(likestr,"uf_systemConfig"); + } + + /** + * 获取配置表中的参数值 + * @param uuid 参数标识 + * @return 参数值 + */ + public static String getStaticSystemParamValue(String uuid){ + return getStaticSystemParamValue(uuid,"uf_systemConfig"); + } + + /** + * 获取配置表中的参数值 + * @param uuid 参数标识 + * @param configTable 参数表名称 + * @return 参数值 + */ + public static String getStaticSystemParamValue(String uuid,String configTable){ + String querySQL = "select paramValue from " + configTable + " where uuid = ?"; + + RecordSet rs = new RecordSet(); + + if(rs.executeQuery(querySQL,uuid) && rs.next()){ + return Util.null2String(rs.getString(1)); + } + + return ""; + } + + /** + * 获取配置表中与某个字符串相似的所有配置信息集合 + * @param likestr 模糊查询字符串 + * @param configTable 配置表 + * @return 配置集合 + */ + public static Map getSystemParamList(String likestr,String configTable){ + Map param_map = new HashMap(); + + String select_sql = "select uuid,paramValue from " + configTable; + + RecordSet rs = new RecordSet(); + + if(!"".equals(likestr)){ + select_sql += " where uuid like '%" + likestr + "%'"; + } + + if(rs.execute(select_sql)){ + while(rs.next()){ + String uuid = Util.null2String(rs.getString(1)); + String paramvalue = Util.null2String(rs.getString(2)); + + param_map.put(uuid, paramvalue); + } + } + return param_map; + } + + /** + * 根据字段ID获取其对应的字段名称 + * @param fieldId 字段ID + * @return 字段名称 + */ + public static String getFieldNameBySingleFieldId(int fieldId){ + String fieldname = ""; + + if(fieldId != 0){ + String querySql = "select fieldname from workflow_billfield where id=?"; + + RecordSet rs = new RecordSet(); + + if(rs.executeQuery(querySql,fieldId)){ + while(rs.next()){ + fieldname = Util.null2String(rs.getString(1)); + } + } + } + return fieldname; + } + + /** + * 获取某个流程某个附件/文档字段对应的文档目录 + * @param workflowId 流程类型ID + * @param docField 文档/附件字段 + * @param tableName 表单名称 + * @return 文档目录ID + */ + public static String getDocCategorysByTable(String workflowId, String docField, String tableName) { + String formId = ""; + RecordSet rs = new RecordSet(); + if(rs.executeQuery("select formid from workflow_base where id = ?", workflowId)){ + if(rs.next()){ + formId = Util.null2String(rs.getString(1)); + } + } + String query = "select doccategory from workflow_fileupload where fieldid in (select id from workflow_billfield where fieldname = ? and billid = ? and (detailtable = ? or detailtable is null))"; + if (!Strings.isNullOrEmpty(tableName) && tableName.contains("_dt")) { + query = "select doccategory from workflow_fileupload where fieldid in (select id from workflow_billfield where fieldname = ? and billid = ? and detailtable = ?)"; + } + + String docCategorys = ""; + + if(rs.executeQuery(query, docField, formId, tableName)){ + if(rs.next()){ + docCategorys = Util.null2String(rs.getString(1)); + } + } + if (StringUtils.isNullOrEmpty(docCategorys)) { + query = "select doccategory from workflow_base where id = ?"; + rs.executeQuery(query, workflowId); + rs.next(); + docCategorys = Util.null2String(rs.getString(1)); + } + + if (StringUtils.isNullOrEmpty(docCategorys)) { + docCategorys = ",,1"; + } + + return docCategorys; + } + + /** + * 根据字段ID获取其对应的字段名称 + * @param fieldId 字段ID + * @return 字段名称 + */ + public static String getFieldNameByFieldIdStatic(int fieldId){ + String fieldname = ""; + + if(fieldId > 0){ + String select_sql = "select fieldname from workflow_billfield where id = ?"; + + RecordSet rs = new RecordSet(); + + if(rs.executeQuery(select_sql,fieldId)){ + while(rs.next()){ + fieldname = Util.null2String(rs.getString(1)); + } + } + } + + return fieldname; + } + + + + /** + * 用数据库值,根据规则转换,获取其最终结果 + * @param cus_sql 自定义转换的SQL + * @param value 参数值 + * @return 配置值 + */ + public static String getStaticValueByChangeRule(String cus_sql,String value){ + return getStaticValueByChangeRule(cus_sql,value,""); + } + + /** + * 用数据库值,根据规则转换,获取其最终结果 + * @param cus_sql 自定义转换的SQL + * @param value 参数值 + * @param requestid 流程请求ID + * @return 返回最终值 + */ + public static String getStaticValueByChangeRule(String cus_sql,String value,String requestid){ + + return getStaticValueByChangeRule(cus_sql,value,requestid,0); + } + + /** + * 用数据库值,根据规则转换,获取其最终结果 + * @param cus_sql 自定义转换的SQL + * @param value 参数值 + * @param requestid 流程请求ID + * @param detailKeyvalue 明细表主键值 + * @return 返回最终值 + */ + public static String getStaticValueByChangeRule(String cus_sql,String value,String requestid,int detailKeyvalue){ + return getStaticValueByChangeRule(cus_sql,value,requestid,detailKeyvalue,null); + } + + /** + * 用数据库值,根据规则转换,获取其最终结果 + * @param cusSQL 自定义转换的SQL + * @param value 参数值 + * @param requestid 流程请求ID + * @param detailKeyvalue 明细表主键值 + * @pram datasourceid 外部数据源ID + * @return 返回最终值 + */ + public static String getStaticValueByChangeRule(String cusSQL,String value,String requestid,int detailKeyvalue,String datasourceid){ + String endValue = ""; + + cusSQL = cusSQL.replace(" ", " "); + + cusSQL = cusSQL.replace("{?dt.id}", String.valueOf(detailKeyvalue)); + + //参数进行替换 + String sqlString = cusSQL.replace("{?requestid}", requestid); + + sqlString = sqlString.replace("?", value); + + sqlString = staticToDBC(sqlString); + try { + if(datasourceid != null && !"".equals(datasourceid)){ + ConnStatementDataSource csds = new ConnStatementDataSource(datasourceid); + + csds.setStatementSql(sqlString); + + csds.executeQuery(); + + if(csds.next()){ + endValue = Util.null2String(csds.getString(1)); + } + + csds.close(); + }else{ + RecordSet rs = new RecordSet(); + if(rs.executeQuery(sqlString)){ + rs.next(); + endValue = Util.null2String(rs.getString(1)); + } + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return endValue; + } + + /** + * 全角转半角 + * @param input 原字符串 + * @return 转换后的字符串 + */ + public static String staticToDBC(String input) { + char c[] = input.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (c[i] == '\u3000') { + c[i] = ' '; + } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { + c[i] = (char) (c[i] - 65248); + } + } + String returnString = new String(c); + return returnString; + } + +} From fe9ae6520902490e99be7a669d899486db433cda Mon Sep 17 00:00:00 2001 From: "weilin.zhu" Date: Thu, 6 Jul 2023 16:54:19 +0800 Subject: [PATCH 02/14] =?UTF-8?q?=E4=B8=AD=E5=9B=BD=E8=88=B9=E8=88=B6?= =?UTF-8?q?=E5=B7=A5=E4=B8=9A=E5=87=AD=E8=AF=81=E6=8E=A5=E5=8F=A3=E5=BC=80?= =?UTF-8?q?=E5=8F=91(=E6=B7=BB=E5=8A=A0=E6=97=A5=E5=BF=97=E6=9D=83?= =?UTF-8?q?=E9=99=90=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cssc/workflow/voucher/util/InterfaceLoggerDao.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/weaver/cssc/workflow/voucher/util/InterfaceLoggerDao.java b/src/main/java/weaver/cssc/workflow/voucher/util/InterfaceLoggerDao.java index d557703..76e1b11 100644 --- a/src/main/java/weaver/cssc/workflow/voucher/util/InterfaceLoggerDao.java +++ b/src/main/java/weaver/cssc/workflow/voucher/util/InterfaceLoggerDao.java @@ -70,11 +70,12 @@ public class InterfaceLoggerDao { /** * 接口日志写入操作 * @param loggerDao 日志类文件 - * @return 返回日志写入结果 */ - public boolean insertInterfaceLog(InterfaceLoggerDao loggerDao){ + public void insertInterfaceLog(InterfaceLoggerDao loggerDao){ VoucherSqlMapper sqlMapper = Util.getMapper(VoucherSqlMapper.class); - return sqlMapper.insertInterfaceLog(loggerDao); + if(sqlMapper.insertInterfaceLog(loggerDao)){ + Util.rebuildModeDataShare(1,"uf_interfaceLog",loggerDao.getNewDataId()); + } } } From 9e9ed8f0948cb870c6044a3b1dba7276de0e965f Mon Sep 17 00:00:00 2001 From: "youhong.ai" Date: Fri, 7 Jul 2023 16:28:43 +0800 Subject: [PATCH 03/14] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=89=93=E5=8C=85?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E8=B7=9F=E8=B7=AF=E5=BE=84=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=BF=85=E9=A1=BB=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- javascript/common/dev.js | 29 ++++ javascript/common/脚本.js | 6 +- .../youhong.ai/pcn/workflow_code_block.js | 159 ++++++++++++++++++ .../controller/ExamBtnControlController.java | 58 ++++++- .../mapper/ExamBtnControlMapper.java | 22 +++ .../service/ExamBtnControlService.java | 139 ++++++++++++++- .../impl/CompressDocPictureImpl.java | 33 +++- src/test/java/BuilderPackageEcology.java | 2 +- .../java/builderpackage/AutoPackageJar.java | 2 +- .../java/builderpackage/FileTreeBuilder.java | 15 +- 10 files changed, 440 insertions(+), 25 deletions(-) diff --git a/javascript/common/dev.js b/javascript/common/dev.js index 666912e..173e0ad 100644 --- a/javascript/common/dev.js +++ b/javascript/common/dev.js @@ -1,3 +1,6 @@ + + + const ecodeSDK = {} ecodeSDK.setCom = (id, name, Com) => { } @@ -44,6 +47,32 @@ const WfForm = { */ forceRenderField(field) { + }, + // 说明:手动触发一次字段涉及的所有联动,包括字段联动、SQL联动、日期时间计算、字段赋值、公式、行列规则、显示属性联动、选择框联动、bindPropertyChange事件绑定等 + // + // 场景:触发出的子流程打开默认不执行字段联动、归档节点查看表单不执行联动,可通过此接口实现 + // + // triggerFieldAllLinkage:function(fieldMark) + triggerFieldAllLinkage(s) { +//表单打开强制执行某字段的联动 +// jQuery(document).ready(function(){ +// WfForm.triggerFieldAllLinkage("field110"); //执行字段涉及的所有联动 +// }); + }, + // 5.2 删除明细表指定行/全部行 + // delDetailRow: function(detailMark, rowIndexMark) + // + // 说明:此方法会清空明细已选情况,删除时没有提示”是否删除”的确认框 + // + // 参数说明 + // + // 参数 参数类型 必须 说明 + // detailMark String 是 明细表标示,明细1就是detail_1,以此递增类推 + // rowIndexMark String 是 需要删除的行标示,删除全部行:all,删除部分行:”1,2,3” + delDetailRow(tableName, all) { + WfForm.delDetailRow("detail_1", "all"); //删除明细1所有行 + WfForm.delDetailRow("detail_1", "3,6"); //删除明细1行标为3,6的行 + } } WfForm.OPER_SAVE = '保存' diff --git a/javascript/common/脚本.js b/javascript/common/脚本.js index dffd9ee..435b629 100644 --- a/javascript/common/脚本.js +++ b/javascript/common/脚本.js @@ -23,7 +23,7 @@ wf.changeFieldValue("100003720000000611", {value: "外出技术支持"}); wf.changeFieldValue("100003720000008715", {value: '2'}); wf.changeFieldValue("877132351682273302", {value: '1'}); - let workflowTitleObj = document.querySelector('input[weid="3rdcst_oxa9w7_i8bbvp_vc1wev_kc1m3l_r1vh81_snhw9p_3r9w93_g28s4n_abfe5k_a9abii"'); + let workflowTitleObj = document.querySelector('input[weid="3rdcst_oxa9w7_i8bbvp_vc1wev_kc1m3l_r1vh81_snhw9p_3r9w93_g28s4n_abfe5k_a9abii"]'); let workflowTitle = workflowTitleObj.value; workflowTitleObj.value = workflowTitle.substring(0, workflowTitle.length - 5) + formattedMonth + "-" + formattedDay; const container = document.getElementById("widget_100003720000000664"); @@ -62,7 +62,9 @@ wf.changeFieldValue("100003720000000611", {value: "外出技术支持"}); wf.changeFieldValue("100003720000008715", {value: '4'}); wf.changeFieldValue("877132351682273302", {value: '1'}); - let workflowTitleObj = document.querySelector('input[weid="3rdcst_oxa9w7_i8bbvp_vc1wev_kc1m3l_r1vh81_snhw9p_3r9w93_g28s4n_abfe5k_a9abii"'); + let workflowTitleObj = document.querySelector('input[weid="3rdcst_oxa9w7_i8bbvp_vc1wev_kc1m3l_r1vh81_snhw9p_3r9w93_g28s4n_abfe5k_a9abii"]'); let workflowTitle = workflowTitleObj.value; workflowTitleObj.value = workflowTitle.substring(0, workflowTitle.length - 5) + formattedMonth + "-" + formattedDay; + window.open("/sp/workflow/flowpage/fullCreate/100003460000000746?workflowId=100003460000000746&isCreate=1", "_blank"); + document.querySelector("button[weid='3rdcst_oxa9w7_i8bbvp_vc1wev_kc1m3l_r1vh81_t03ihg@0_xomsa1@0']").click(); })() \ No newline at end of file diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 114d081..8d9c82c 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -1,4 +1,7 @@ /* ******************* 保时捷target setting流程提交控制 start ******************* */ +import React from "react"; +import ReactDOM from "react-dom" + window.workflowCus = Object.assign(window.workflowCus ? window.workflowCus : {}, { /** * @author youhong.ai @@ -999,3 +1002,159 @@ $(() => { }) /* ******************* youhong.ai 限制考试按钮点击 end ******************* */ + + +/* ******************* youhong.ai 随机抽取题库考题 start ******************* */ + +$(() => { + const config = { + table: '', + // 使用范围字段 + scopeOfUse: '', + // 类型明细表 + typeDetail: { + // 明细表名 + tableName: "", + // 类型字段 + typeField: '', + // 类型数量 + typeNumber: '', + // 类型数量字段 + typeTotalNumber: '' + }, + targetDetail: { + tableName: '', + testQuestionField: '' + } + } + + + /** + * 获取考题分类总数 + * @param scopeOfUse 大分类:管理员 与 普通员工 + */ + function getTestPaperTypeNumber(scopeOfUse) { + Utils.api({ + url: `/api/aiyh/exam-btn/control/count?scopeOfUse=${scopeOfUse}&groupField=${config.typeDetail.typeField}&scopeOfUseField=${config.scopeOfUse}&table=${config.table}` + }).then(res => { + if (res && res.code === 200) { + let typeNumber = res.data + // 监听类型变化 + WfForm.bindDetailFieldChangeEvent(WfForm.convertFieldNameToId(config.typeDetail.typeField, + config.typeDetail.tableName), (id, rowIndex, value) => { + let totalNumber = typeNumber[value] + // 更新总数字段 + WfForm.changeFieldValue(WfForm.convertFieldNameToId(config.typeDetail.typeTotalNumber, + config.typeDetail.tableName) + "_" + rowIndex, { + value: totalNumber + }) + }) + } + }) + } + + /** + * 获取试题类型和数量 + * @param scopeOfUse 使用范围 + */ + function getTestPaper(scopeOfUse) { + getTestPaperTypeNumber(scopeOfUse) + } + + /** + * 生成随机试题 + */ + function extractTestQuestions() { + let detailAllRowIndexStr = WfForm.getDetailAllRowIndexStr(config.typeDetail.tableName); + let rowArr = detailAllRowIndexStr.split(","); + let typeNumberObj = {} + rowArr.forEach(item => { + let type = WfForm.getFieldValue(WfForm.convertFieldNameToId(config.typeDetail.typeField, config.typeDetail.tableName) + "_" + item); + let number = WfForm.getFieldValue(WfForm.convertFieldNameToId(config.typeDetail.typeNumber, config.typeDetail.tableName) + "_" + item); + if (number <= 0) { + return + } + typeNumberObj[type] = number + }) + let params = { + scopeOfUse: WfForm.getFieldValue(config.scopeOfUse), + groupField: config.typeDetail.typeField, + scopeOfUseField: config.scopeOfUse, + table: config.table, + questNumberMap: typeNumberObj + } + console.log('请求参数', params) + Utils.api({ + url: "/api/aiyh/exam-btn/control/random-test-questions", + data: JSON.stringify(params), + }).then(res => { + if (res && res.code == 200) { + let testQuestions = res.data + let n = 0; + WfForm.delDetailRow(config.targetDetail.tableName, "all"); + testQuestions.forEach(item => { + let fieldMark = WfForm.convertFieldNameToId(config.targetDetail.testQuestionField, config.targetDetail.tableName) + WfForm.addDetailRow(config.targetDetail.tableName, { + [fieldMark]: { + value: item.id, + specialobj: [{ + id: item.id, + name: item.name + }] + } + }) + WfForm.triggerFieldAllLinkage(fieldMark + "_" + n++) + }) + } + }) + } + + + function runJs() { + // 监听分类数量发生变化 + WfForm.bindFieldChangeEvent(WfForm.convertFieldNameToId(config.typeDetail.typeNumber, config.typeDetail.tableName), + (id, rowIndex, value) => { + if (value == '') { + return + } + let total = WfForm.getFieldValue(WfForm.convertFieldNameToId(config.typeDetail.typeTotalNumber, config.typeDetail.tableName) + "_" + rowIndex); + if (value > total) { + WfForm.showConfirm("抽题数不能大于总题数!", function () { + WfForm.changeFieldValue(WfForm.convertFieldNameToId(config.typeDetail.typeNumber, config.typeDetail.tableName) + "_" + rowIndex, { + value: "" + }) + }); + } + }) + // 监听主表使用范围 + WfForm.bindFieldChangeEvent(WfForm.convertFieldNameToId(config.scopeOfUse), (obj, id, value) => { + if (value == '') { + return + } + getTestPaper(value) + }) + // 渲染生成抽取试题按钮 + const generateBtnNode = document.querySelector("#cus_generate_test_questions>span") + const {Button} = antd + ReactDOM.render(React.createElement(Button, { + type: "primary", + children: "抽取试题", + onClick: () => { + extractTestQuestions() + } + }), generateBtnNode) + $("#cus_generate_test_questions button").css({ + margin: "3px auto" + }) + $("#cus_generate_test_questions span").css("color", "#FFF") + } + + + runJs() +}) + + +/* ******************* youhong.ai 随机抽取题库考题 end ******************* */ + + + diff --git a/src/main/java/com/api/youhong/ai/pcn/examcontrol/controller/ExamBtnControlController.java b/src/main/java/com/api/youhong/ai/pcn/examcontrol/controller/ExamBtnControlController.java index d13221f..ac45180 100644 --- a/src/main/java/com/api/youhong/ai/pcn/examcontrol/controller/ExamBtnControlController.java +++ b/src/main/java/com/api/youhong/ai/pcn/examcontrol/controller/ExamBtnControlController.java @@ -10,10 +10,7 @@ import weaver.hrm.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import java.util.Map; @@ -32,6 +29,14 @@ public class ExamBtnControlController { private final ExamBtnControlService service = new ExamBtnControlService(); + /** + *

判断文档是否已读

+ * + * @param request 请求体 + * @param response 响应体 + * @param params 请求参数 + * @return 是否已读 + */ @Path("/is-read") @POST @Produces(MediaType.APPLICATION_JSON) @@ -46,4 +51,49 @@ public class ExamBtnControlController { return ApiResult.error("system error!"); } } + + + /** + *

获取对应使用范围的考题的考题类型对应的总考题数

+ * + * @param scopeOfUse 使用范围 + * @param groupField 分组字段 + * @param scopeOfUseField 使用范围字段 + * @param table 表 + * @return 考题数量 + */ + @Path("/count") + @GET + @Produces(MediaType.APPLICATION_JSON) + public String getTestQuestionCount(@QueryParam("scopeOfUse") String scopeOfUse, + @QueryParam("groupField") String groupField, + @QueryParam("scopeOfUseField") String scopeOfUseField, + @QueryParam("table") String table) { + try { + return ApiResult.success(service.getTestQuestionCount(scopeOfUse, groupField, scopeOfUseField, table)); + } catch (Exception e) { + log.error("is read doc error!\n" + Util.getErrString(e)); + return ApiResult.error("system error!"); + } + } + + /** + *

获取随机数量的考题

+ * + * @param params 请求参数 + * @return 随机考题合集 + */ + + @Path("/random-test-questions") + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public String randomTestQuestions(@RequestBody Map params) { + try { + return ApiResult.success(service.randomTestQuestions(params)); + } catch (Exception e) { + log.error("is read doc error!\n" + Util.getErrString(e)); + return ApiResult.error("system error!"); + } + } } diff --git a/src/main/java/com/api/youhong/ai/pcn/examcontrol/mapper/ExamBtnControlMapper.java b/src/main/java/com/api/youhong/ai/pcn/examcontrol/mapper/ExamBtnControlMapper.java index 5911dd7..21f62f2 100644 --- a/src/main/java/com/api/youhong/ai/pcn/examcontrol/mapper/ExamBtnControlMapper.java +++ b/src/main/java/com/api/youhong/ai/pcn/examcontrol/mapper/ExamBtnControlMapper.java @@ -42,4 +42,26 @@ public interface ExamBtnControlMapper { @Select("select id from docreadtag where userid = #{userId} and docid in ($t{docIds})") List selectReadTag(@ParamMapper("userId") int userId, @ParamMapper("docIds") String docIds); + + /** + *

查询角色成员信息

+ * + * @param roleId 角色id + * @return 角色成员 + */ + @Select("select resourceid from hrmrolemembers where roleid = #{roleId}") + List selectRoleMembers(String roleId); + + /** + *

查询对应使用范围的考题信息

+ * + * @param scopeOfUse 使用范围 + * @param scopeOfUseField 使用范围字段 + * @param table 表 + * @return 对应的使用范围的考题集合 + */ + @Select("select * from $t{table} where $t{scopeOfUseField} = #{scopeOfUse}") + List> selectTestQuestions(@ParamMapper("scopeOfUse") String scopeOfUse, + @ParamMapper("scopeOfUseField") String scopeOfUseField, + @ParamMapper("table") String table); } diff --git a/src/main/java/com/api/youhong/ai/pcn/examcontrol/service/ExamBtnControlService.java b/src/main/java/com/api/youhong/ai/pcn/examcontrol/service/ExamBtnControlService.java index 96e2bea..7ebff6f 100644 --- a/src/main/java/com/api/youhong/ai/pcn/examcontrol/service/ExamBtnControlService.java +++ b/src/main/java/com/api/youhong/ai/pcn/examcontrol/service/ExamBtnControlService.java @@ -7,13 +7,14 @@ import aiyh.utils.tool.cn.hutool.core.collection.CollectionUtil; import aiyh.utils.tool.cn.hutool.core.util.StrUtil; import com.api.youhong.ai.pcn.examcontrol.mapper.ExamBtnControlMapper; import org.apache.log4j.Logger; +import org.jetbrains.annotations.NotNull; import weaver.hrm.User; -import java.util.List; -import java.util.Map; +import java.util.*; +import java.util.stream.Collectors; /** - *

+ *

考题培训相关的service

* *

create: 2023/7/5 16:39

* @@ -26,6 +27,13 @@ public class ExamBtnControlService { private final ExamBtnControlMapper mapper = Util.getMapper(ExamBtnControlMapper.class); + /** + *

是否已读文档

+ * + * @param user 当前用户 + * @param params 请求参数 + * @return 是否已读 + */ public boolean isReadDoc(User user, Map params) { // 系统管理员可以直接考试 @@ -36,26 +44,151 @@ public class ExamBtnControlService { if (CollectionUtil.isEmpty(params)) { return false; } + // 获取角色id,当前角色所对应的所有人员不需要判断是否已读文档 + String roleId = Util.null2String(params.get("roleId")); + if (StrUtil.isNotBlank(roleId)) { + List roleMembers = mapper.selectRoleMembers(roleId); + if (CollectionUtil.isNotEmpty(roleMembers) && roleMembers.contains(user.getUID() + "")) { + return true; + } + } // 获取表名称 String tableName = Util.null2String(params.get("tableName")); String docIdField = Util.null2String(params.get("docIdField")); + // 获取条件 Map conditions = (Map) params.get("conditions"); if (CollectionUtil.isEmpty(conditions)) { return false; } + // 构建sql where条件 String where = MapperBuilderSql.builderWhereAnd(conditions, "where", true); if (StrUtil.isBlank(where)) { log.error("没有生成where条件!"); return false; } + // 查询满足条件的所有文档的docId List docIdList = mapper.selectDocIds(tableName, docIdField, where, conditions); if (CollectionUtil.isEmpty(docIdList)) { throw new CustomerException("没有查询到对应的文件ID信息,请检查sql!"); } + // 查询这些文档中哪些是当前用户已读的文档 List readIdList = mapper.selectReadTag(user.getUID(), Util.join(docIdList, ",")); if (CollectionUtil.isEmpty(readIdList)) { return false; } + // 如果已读文档长度等于待查验文档id的长度则表示全部已读 return readIdList.size() == docIdList.size(); } + + /** + *

获取考题数量

+ * + * @param scopeOfUse 考题使用范围 + * @param groupField 考题分组字段 + * @param scopeOfUseField 考试使用范围字段 + * @param table 表名称 + * @return 考题分组对应的数量 + */ + public Map getTestQuestionCount(String scopeOfUse, String groupField, + String scopeOfUseField, String table) { + // 查询考题 + Map>> collect = getTestQuestions(scopeOfUse, groupField, scopeOfUseField, table); + Map result = new HashMap<>(8); + // 考题分组统计数量 + for (Map.Entry>> entry : collect.entrySet()) { + String key = entry.getKey(); + result.put(Util.null2String(key), entry.getValue().size()); + } + return result; + } + + /** + *

获取使用范围内的所有考题信息

+ * + * @param scopeOfUse 使用范围 + * @param groupField 分组字段 + * @param scopeOfUseField 考题使用范围字段 + * @param table 表名称 + * @return 返回考题分组后信息 + */ + @NotNull + private Map>> getTestQuestions(String scopeOfUse, String groupField, String scopeOfUseField, String table) { + List> testQuestionList = mapper.selectTestQuestions(scopeOfUse, scopeOfUseField, table); + if (CollectionUtil.isEmpty(testQuestionList)) { + throw new CustomerException("没有查询到对应的题库试题"); + } + // 对考题进行分组 + return testQuestionList.stream() + .collect(Collectors.groupingBy(value -> Util.null2String(value.get(groupField)))); + } + + + /** + *

随机抽取题库试题

+ * + * @param params 请求参数 + * @return 随机试题 + */ + + public List> randomTestQuestions(Map params) { + // 获取请求参数 + String scopeOfUse = Util.null2String(params.get("scopeOfUse")); + String groupField = Util.null2String(params.get("groupField")); + String scopeOfUseField = Util.null2String(params.get("scopeOfUseField")); + String table = Util.null2String(params.get("table")); + // 获取每个分组对应的题目数量对应关系 + Map questNumberMap = (Map) params.get("questNumberMap"); + // 查询所有考题分组后信息 + Map>> testQuestionList = getTestQuestions(scopeOfUse, groupField, scopeOfUseField, table); + List> result = new ArrayList<>(); + // 循环考题对应数量获取随机考题 + for (Map.Entry entry : questNumberMap.entrySet()) { + String key = entry.getKey(); + List> maps = testQuestionList.get(key); + // 随机获取其中的n道题 + int n = Integer.parseInt(Util.null2String(questNumberMap.get(key))); + List> randomElements = pickRandomElements(maps, n); + result.addAll(randomElements); + } + return result; + } + + /** + *

随机在数组中抽取指定数量的元素

+ * + * @param list 源数组 + * @param n 指定数量 + * @return 随机元素 + */ + public List> pickRandomElements(List> list, int n) { + // 创建一个新的列表用于存储选定的元素 + List> selectedElements = new ArrayList<>(); + + // 创建一个随机数生成器 + Random random = new Random(); + + // 检查传入的列表是否为空或元素数量小于 n + if (list == null || list.isEmpty() || n <= 0 || n > list.size()) { + // 返回空列表,表示无法选择任何元素 + return selectedElements; + } + + // 从原始列表中随机选择 n 个元素 + for (int i = 0; i < n; i++) { + // 生成一个随机索引 + int randomIndex = random.nextInt(list.size()); + + // 根据随机索引获取对应的元素 + Map selectedElement = list.get(randomIndex); + + // 将选定的元素添加到结果列表中 + selectedElements.add(selectedElement); + + // 从原始列表中移除已选定的元素,避免重复选择 + list.remove(randomIndex); + } + + // 返回选定的元素列表 + return selectedElements; + } } diff --git a/src/main/java/com/customization/youhong/taibao/compresspicture/impl/CompressDocPictureImpl.java b/src/main/java/com/customization/youhong/taibao/compresspicture/impl/CompressDocPictureImpl.java index bfe25dd..60895f9 100644 --- a/src/main/java/com/customization/youhong/taibao/compresspicture/impl/CompressDocPictureImpl.java +++ b/src/main/java/com/customization/youhong/taibao/compresspicture/impl/CompressDocPictureImpl.java @@ -4,6 +4,7 @@ import aiyh.utils.Util; import aiyh.utils.entity.DocImageInfo; import aiyh.utils.tool.cn.hutool.core.collection.CollectionUtil; import aiyh.utils.tool.cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSON; import com.api.doc.detail.util.DocDownloadCheckUtil; import com.customization.youhong.taibao.compresspicture.mapper.CompressDocPictureMapper; import com.customization.youhong.taibao.compresspicture.util.CompressPictureUtil; @@ -42,41 +43,55 @@ public class CompressDocPictureImpl { */ @WeaReplaceAfter(value = "/api/doc/save/save", order = 1) public String after(WeaAfterReplaceParam weaAfterReplaceParam) { - if (Objects.isNull(mapper)) { - mapper = Util.getMapper(CompressDocPictureMapper.class); - } - if (Objects.isNull(log)) { - log = Util.getLogger(); - } + String data = weaAfterReplaceParam.getData(); try { + // 初始化全局参数 + if (Objects.isNull(mapper)) { + mapper = Util.getMapper(CompressDocPictureMapper.class); + } + if (Objects.isNull(log)) { + log = Util.getLogger(); + } + // 获取请求参数 Map paramMap = weaAfterReplaceParam.getParamMap(); - String doccontent = Util.null2String(paramMap.get("doccontent")); - if (StrUtil.isBlank(doccontent)) { + String docContent = Util.null2String(paramMap.get("doccontent")); + if (StrUtil.isBlank(docContent)) { return data; } - List imgSrcList = CompressPictureUtil.parseImageSrc(doccontent); + // 获取其中的图片链接 + List imgSrcList = CompressPictureUtil.parseImageSrc(docContent); if (CollectionUtil.isEmpty(imgSrcList)) { return data; } + log.info("获取到的图片数据列表:" + JSON.toJSONString(imgSrcList)); + // 循环处理 for (String imgSrc : imgSrcList) { + // 获取加密的imgId String imageFileIdEncrypt = CompressPictureUtil.extractFileId(imgSrc); String imageFileId = DocDownloadCheckUtil.DncodeFileid(imageFileIdEncrypt); + // 查询附件信息 DocImageInfo docImageInfo = Util.selectImageInfoByImageId(imageFileId); if (StrUtil.isNotBlank(docImageInfo.getMiniImgPath())) { continue; } + // 获取文件流 InputStream inputStreamById = ImageFileManager.getInputStreamById(Integer.parseInt(imageFileId)); + // 压缩文件 InputStream quality = CompressPictureUtil.compressImage(inputStreamById, docImageInfo.getImageFileName(), Float.parseFloat(Util.getCusConfigValueNullOrEmpty("quality", "0.5"))); if (Objects.isNull(quality)) { + log.info("压缩文件失败!压缩文件名称: " + docImageInfo.getImageFileName()); + log.info("压缩文件信息:" + JSON.toJSONString(docImageInfo)); continue; } + // 生成压缩后的文件信息 int newImageFileId = Util.createFileByInputSteam(quality, docImageInfo.getImageFileName()); if (newImageFileId <= 0) { continue; } DocImageInfo newDocImageInfo = Util.selectImageInfoByImageId(Util.null2String(newImageFileId)); + log.info("压缩后文件信息:" + JSON.toJSONString(docImageInfo)); boolean flag = mapper.updateImageInfo(docImageInfo, newDocImageInfo); if (flag) { mapper.updateImageInfo(docImageInfo, newDocImageInfo); diff --git a/src/test/java/BuilderPackageEcology.java b/src/test/java/BuilderPackageEcology.java index e0f4b9c..82102f1 100644 --- a/src/test/java/BuilderPackageEcology.java +++ b/src/test/java/BuilderPackageEcology.java @@ -55,7 +55,7 @@ public class BuilderPackageEcology extends Application { try { FileCompressor.compressFiles(filePaths, outputFile.getAbsolutePath(), path -> { String rootPath = Util.class.getResource("/").getPath(); - rootPath = rootPath.split(File.separator + FileTreeBuilder.targetPath)[0] + File.separator + FileTreeBuilder.targetPath + "classes" + File.separator; + rootPath = rootPath.split(File.separator + FileTreeBuilder.targetPath)[0] + File.separator + FileTreeBuilder.targetPath + FileTreeBuilder.classPath; String replace = "/ecology/" + (isEcology ? "WEB-INF/classes/" : "classbean/"); if (path.endsWith(".jar")) { replace = "/ecology/WEB-INF/lib/"; diff --git a/src/test/java/builderpackage/AutoPackageJar.java b/src/test/java/builderpackage/AutoPackageJar.java index 4897ef2..be6d848 100644 --- a/src/test/java/builderpackage/AutoPackageJar.java +++ b/src/test/java/builderpackage/AutoPackageJar.java @@ -25,7 +25,7 @@ public class AutoPackageJar { public static void createJar(String targetPath) { String path = AutoPackageJar.class.getResource("").getPath(); - String finalPath = path.split(File.separator + targetPath)[0] + File.separator + targetPath + File.separator + "classes" + File.separator; + String finalPath = path.split(File.separator + targetPath)[0] + File.separator + targetPath + File.separator + FileTreeBuilder.classPath; createJar(finalPath + "aiyh", finalPath + "aiyh_utils.jar"); createJar(finalPath + "ebu7common", finalPath + "ebu7common.jar"); } diff --git a/src/test/java/builderpackage/FileTreeBuilder.java b/src/test/java/builderpackage/FileTreeBuilder.java index ee9dd68..6e5ad30 100644 --- a/src/test/java/builderpackage/FileTreeBuilder.java +++ b/src/test/java/builderpackage/FileTreeBuilder.java @@ -14,8 +14,11 @@ public class FileTreeBuilder { public static String targetPath; + public static String classPath; + public static FileInfo buildFileTree() { String directoryPath = "target"; + String classRootPath = ""; List blackList = new ArrayList<>(); Properties properties = new Properties(); @@ -35,16 +38,18 @@ public class FileTreeBuilder { } targetPath = directoryPath; } + classRootPath = properties.getProperty("classRootPath"); + classPath = classRootPath; List blacklistPrefixes = Arrays.asList( directoryPath + "generated-sources", directoryPath + "generated-test-sources", directoryPath + "test-classes", - directoryPath + "classes" + File.separator + "aiyh", - directoryPath + "classes" + File.separator + "ebu7common", - directoryPath + "classes" + File.separator + "ln", - directoryPath + "classes" + File.separator + "cus_getlog" + directoryPath + classRootPath + "aiyh", + directoryPath + classRootPath + "ebu7common", + directoryPath + classRootPath + "ln", + directoryPath + classRootPath + "cus_getlog" ); - AutoPackageJar.createJar(directoryPath); + AutoPackageJar.createJar(directoryPath, classRootPath); blackList.addAll(blacklistPrefixes); } catch (IOException e) { e.printStackTrace(); From 20b4eb3f750531c508b5e7b6de40981071a43cdf Mon Sep 17 00:00:00 2001 From: "youhong.ai" Date: Fri, 7 Jul 2023 16:34:20 +0800 Subject: [PATCH 04/14] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=89=93=E5=8C=85?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E8=B7=9F=E8=B7=AF=E5=BE=84=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E5=BF=85=E9=A1=BB=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/builderpackage/FileTreeBuilder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/builderpackage/FileTreeBuilder.java b/src/test/java/builderpackage/FileTreeBuilder.java index 6e5ad30..bbffa20 100644 --- a/src/test/java/builderpackage/FileTreeBuilder.java +++ b/src/test/java/builderpackage/FileTreeBuilder.java @@ -49,7 +49,7 @@ public class FileTreeBuilder { directoryPath + classRootPath + "ln", directoryPath + classRootPath + "cus_getlog" ); - AutoPackageJar.createJar(directoryPath, classRootPath); + AutoPackageJar.createJar(directoryPath); blackList.addAll(blacklistPrefixes); } catch (IOException e) { e.printStackTrace(); From 64ed73b319033e89f746b07db8d9978703fe588d Mon Sep 17 00:00:00 2001 From: "youhong.ai" Date: Fri, 7 Jul 2023 17:06:58 +0800 Subject: [PATCH 05/14] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=B3=A8=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/BuilderPackageEcology.java | 39 ++++++++++++++++++- .../java/builderpackage/FileTreeBuilder.java | 6 +++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/test/java/BuilderPackageEcology.java b/src/test/java/BuilderPackageEcology.java index 82102f1..eedc19f 100644 --- a/src/test/java/BuilderPackageEcology.java +++ b/src/test/java/BuilderPackageEcology.java @@ -1,4 +1,5 @@ import aiyh.utils.Util; +import aiyh.utils.tool.cn.hutool.core.util.StrUtil; import builderpackage.FileCompressor; import builderpackage.FileInfo; import builderpackage.FileTreeBuilder; @@ -27,6 +28,9 @@ public class BuilderPackageEcology extends Application { private TreeView treeView; private TreeItem rootItem; + private TextField packageNumberTextField; + private TextField functionNameTextField; + @Override public void start(Stage primaryStage) { primaryStage.setTitle("EBU7部开发一部自动打包工具"); @@ -37,10 +41,29 @@ public class BuilderPackageEcology extends Application { treeView = new TreeView<>(rootItem); treeView.setShowRoot(false); treeView.setCellFactory(treeViewParam -> new CheckBoxTreeCell()); + treeView.setPadding(new Insets(10)); BorderPane root = new BorderPane(); root.setCenter(treeView); + // 添加输入框 + HBox topBox = new HBox(10); + topBox.setPadding(new Insets(10)); + topBox.setAlignment(Pos.CENTER); + + // 创建包编号标签和输入框 + Label packageNumberLabel = new Label("包编号:"); + packageNumberTextField = new TextField(); + packageNumberTextField.setPromptText("请输入包编号"); + + // 创建功能名称标签和输入框 + Label functionNameLabel = new Label("功能名称:"); + functionNameTextField = new TextField(); + functionNameTextField.setPromptText("请输入功能名称"); + + topBox.getChildren().addAll(packageNumberLabel, packageNumberTextField, functionNameLabel, functionNameTextField); + root.setTop(topBox); + HBox buttonBox = new HBox(); buttonBox.setSpacing(10); buttonBox.setPadding(new Insets(10)); @@ -49,7 +72,13 @@ public class BuilderPackageEcology extends Application { Button button = new Button("生成升级包"); button.setOnAction(event -> { FileChooser fileChooser = new FileChooser(); - fileChooser.setInitialFileName("sh_ebu_dev_1_ecology.zip"); + String defaultName = FileTreeBuilder.zipDefaultName; + if (StrUtil.isBlank(defaultName)) { + defaultName = "sh_ebu_dev_1_ecology.zip"; + } + + fileChooser.setInitialFileName(defaultName); + // fileChooser.setInitialDirectory(); File outputFile = fileChooser.showSaveDialog(primaryStage); if (outputFile != null) { try { @@ -70,6 +99,12 @@ public class BuilderPackageEcology extends Application { updateTreeView(); showSuccessAlert("升级包制作成功!"); System.out.println("压缩包位置: " + outputFile.getPath()); + + // 输出包编号和功能名称的值 + String packageNumber = packageNumberTextField.getText(); + String functionName = functionNameTextField.getText(); + System.out.println("包编号: " + packageNumber); + System.out.println("功能名称: " + functionName); } catch (IOException e) { throw new RuntimeException(e); } @@ -87,9 +122,11 @@ public class BuilderPackageEcology extends Application { checkBoxBox.getChildren().add(checkBox); + buttonBox.getChildren().addAll(button, checkBoxBox); root.setBottom(buttonBox); + Scene scene = new Scene(root, 600, 400); scene.getStylesheets().add("style.css"); // 加载自定义的 CSS 文件 primaryStage.setScene(scene); diff --git a/src/test/java/builderpackage/FileTreeBuilder.java b/src/test/java/builderpackage/FileTreeBuilder.java index bbffa20..5b7e1a7 100644 --- a/src/test/java/builderpackage/FileTreeBuilder.java +++ b/src/test/java/builderpackage/FileTreeBuilder.java @@ -16,6 +16,10 @@ public class FileTreeBuilder { public static String classPath; + public static String zipDefaultName; + + public static String defaultDir; + public static FileInfo buildFileTree() { String directoryPath = "target"; String classRootPath = ""; @@ -40,6 +44,8 @@ public class FileTreeBuilder { } classRootPath = properties.getProperty("classRootPath"); classPath = classRootPath; + zipDefaultName = properties.getProperty("zipDefaultName"); + defaultDir = properties.getProperty("defaultDir"); List blacklistPrefixes = Arrays.asList( directoryPath + "generated-sources", directoryPath + "generated-test-sources", From c2f67e8c1f5b032ec3bc853588ec29f8071bb3a2 Mon Sep 17 00:00:00 2001 From: "youhong.ai" Date: Fri, 7 Jul 2023 17:28:32 +0800 Subject: [PATCH 06/14] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E6=89=93=E5=8C=85=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/BuilderPackageEcology.java | 53 +++++++++++++++---- .../java/builderpackage/FileTreeBuilder.java | 12 +++-- 2 files changed, 51 insertions(+), 14 deletions(-) diff --git a/src/test/java/BuilderPackageEcology.java b/src/test/java/BuilderPackageEcology.java index eedc19f..885e867 100644 --- a/src/test/java/BuilderPackageEcology.java +++ b/src/test/java/BuilderPackageEcology.java @@ -16,8 +16,8 @@ import javafx.stage.Stage; import java.io.File; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; +import java.text.SimpleDateFormat; +import java.util.*; public class BuilderPackageEcology extends Application { @@ -68,17 +68,33 @@ public class BuilderPackageEcology extends Application { buttonBox.setSpacing(10); buttonBox.setPadding(new Insets(10)); buttonBox.setAlignment(Pos.CENTER_RIGHT); - + Map param = new HashMap<>(8); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); + Date date = new Date(); + param.put("date", simpleDateFormat.format(date)); Button button = new Button("生成升级包"); button.setOnAction(event -> { + // 输出包编号和功能名称的值 + String packageNumber = packageNumberTextField.getText(); + String functionName = functionNameTextField.getText(); FileChooser fileChooser = new FileChooser(); String defaultName = FileTreeBuilder.zipDefaultName; if (StrUtil.isBlank(defaultName)) { defaultName = "sh_ebu_dev_1_ecology.zip"; } - + param.put("name", functionName); + param.put("no", packageNumber); + defaultName = replacePlaceholders(defaultName, param); + replacePlaceholders(defaultName, param); + String defaultDir = FileTreeBuilder.defaultDir; + if (StrUtil.isNotBlank(defaultDir)) { + try { + fileChooser.setInitialDirectory(new File(defaultDir)); + } catch (Exception ignore) { + System.out.println(defaultDir); + } + } fileChooser.setInitialFileName(defaultName); - // fileChooser.setInitialDirectory(); File outputFile = fileChooser.showSaveDialog(primaryStage); if (outputFile != null) { try { @@ -97,14 +113,11 @@ public class BuilderPackageEcology extends Application { }); clearSelections(); updateTreeView(); + packageNumberTextField.setText(""); + functionNameTextField.setText(""); showSuccessAlert("升级包制作成功!"); System.out.println("压缩包位置: " + outputFile.getPath()); - // 输出包编号和功能名称的值 - String packageNumber = packageNumberTextField.getText(); - String functionName = functionNameTextField.getText(); - System.out.println("包编号: " + packageNumber); - System.out.println("功能名称: " + functionName); } catch (IOException e) { throw new RuntimeException(e); } @@ -154,6 +167,7 @@ public class BuilderPackageEcology extends Application { } } filePaths.clear(); + } private void updateTreeView() { @@ -217,6 +231,25 @@ public class BuilderPackageEcology extends Application { alert.showAndWait(); } + public static String replacePlaceholders(String inputString, Map placeholderMap) { + StringBuilder outputString = new StringBuilder(inputString); + + for (Map.Entry entry : placeholderMap.entrySet()) { + String placeholder = "${" + entry.getKey() + "}"; + String value = entry.getValue(); + + // 检查占位符是否存在于字符串中 + if (outputString.indexOf(placeholder) != -1) { + // 使用 String 类的 replace 方法进行占位符的替换 + outputString.replace(outputString.indexOf(placeholder), + outputString.indexOf(placeholder) + placeholder.length(), + value); + } + } + + return outputString.toString(); + } + public static void main(String[] args) { launch(args); } diff --git a/src/test/java/builderpackage/FileTreeBuilder.java b/src/test/java/builderpackage/FileTreeBuilder.java index 5b7e1a7..436fe9b 100644 --- a/src/test/java/builderpackage/FileTreeBuilder.java +++ b/src/test/java/builderpackage/FileTreeBuilder.java @@ -1,10 +1,10 @@ package builderpackage; +import aiyh.utils.excention.CustomerException; import aiyh.utils.tool.cn.hutool.core.util.StrUtil; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; +import java.nio.charset.StandardCharsets; import java.util.*; public class FileTreeBuilder { @@ -27,7 +27,11 @@ public class FileTreeBuilder { Properties properties = new Properties(); try (InputStream inputStream = FileTreeBuilder.class.getClassLoader().getResourceAsStream("application.properties")) { - properties.load(inputStream); + if (inputStream == null) { + throw new CustomerException("测试包的resources中不存在application.properties!"); + } + BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); + properties.load(bf); // 通过键获取属性值 String value = properties.getProperty("packageBlackPaths"); if (StrUtil.isNotBlank(value)) { From 2883d901b8687f5f721dc839d86c2cfad9ee1d73 Mon Sep 17 00:00:00 2001 From: "youhong.ai" Date: Fri, 7 Jul 2023 17:47:35 +0800 Subject: [PATCH 07/14] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E6=89=93=E5=8C=85=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/test/java/builderpackage/FileTreeBuilder.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/test/java/builderpackage/FileTreeBuilder.java b/src/test/java/builderpackage/FileTreeBuilder.java index 436fe9b..1a58e48 100644 --- a/src/test/java/builderpackage/FileTreeBuilder.java +++ b/src/test/java/builderpackage/FileTreeBuilder.java @@ -69,6 +69,7 @@ public class FileTreeBuilder { System.out.println("Invalid directory path: " + directoryPath); return null; } + System.out.println(blackList); return buildFileTreeRecursively(root, blackList); } @@ -96,7 +97,7 @@ public class FileTreeBuilder { if (files != null) { for (File file : files) { if (file.isDirectory()) { - if (!isBlacklisted(file.getAbsolutePath(), blacklistPrefixes)) { + if (!isBlacklisted(file.getPath(), blacklistPrefixes)) { FileInfo child = buildFileTreeRecursively(file, blacklistPrefixes); fileInfo.addChild(child); } @@ -125,10 +126,11 @@ public class FileTreeBuilder { if (filePath.endsWith(".DS_Store") || filePath.endsWith(".DSStore")) { return true; } + System.out.println("黑名单过滤文件:" + filePath); for (String prefix : blacklistPrefixes) { - String path = FileTreeBuilder.class.getResource("").getPath(); - String prefixPath = path.substring(0, path.indexOf(File.separator + "target" + File.separator)) + File.separator; - if (filePath.startsWith(prefixPath + prefix)) { + // // String path = FileTreeBuilder.class.getResource("").getPath(); + // String prefixPath = path.substring(0, path.indexOf(File.separator + "target" + File.separator)) + File.separator; + if (filePath.startsWith(prefix)) { return true; } } From 5fe42011bc88934974989cafe042a5dca0ff4645 Mon Sep 17 00:00:00 2001 From: "weilin.zhu" Date: Fri, 7 Jul 2023 18:32:58 +0800 Subject: [PATCH 08/14] =?UTF-8?q?=E5=85=B4=E4=B8=9A=E8=AF=81=E5=88=B8?= =?UTF-8?q?=E7=BB=84=E7=BB=87=E6=9E=B6=E6=9E=84=E6=95=B0=E6=8D=AE=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E5=85=A5=E5=BB=BA=E6=A8=A1=E8=A1=A8=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=EF=BC=8C=E5=88=9D=E6=AC=A1=E6=8F=90=E4=BA=A4.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../voucher/action/VoucherPushAction.java | 282 +++++++++--------- .../xyzq/scheduled/entity/SyncConfigDao.java | 51 ++++ .../scheduled/entity/SyncConfigDetailDao.java | 34 +++ .../sqlmapper/OrganizationSyncSqlMapper.java | 83 ++++++ .../xyzq/scheduled/task/SyncOrgDataTask.java | 38 +++ .../xyzq/scheduled/util/ChangeRuleMethod.java | 151 ++++++++++ .../xyzq/scheduled/util/CusAsyncConvert.java | 17 ++ .../scheduled/util/OrganizationSyncUtil.java | 159 ++++++++++ .../zhu/xyzq/scheduled/util/RestApiUtil.java | 129 ++++++++ .../java/weaver/zwl/common/ToolUtilNew.java | 13 + 10 files changed, 820 insertions(+), 137 deletions(-) create mode 100644 src/main/java/weaver/weilin/zhu/xyzq/scheduled/entity/SyncConfigDao.java create mode 100644 src/main/java/weaver/weilin/zhu/xyzq/scheduled/entity/SyncConfigDetailDao.java create mode 100644 src/main/java/weaver/weilin/zhu/xyzq/scheduled/sqlmapper/OrganizationSyncSqlMapper.java create mode 100644 src/main/java/weaver/weilin/zhu/xyzq/scheduled/task/SyncOrgDataTask.java create mode 100644 src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/ChangeRuleMethod.java create mode 100644 src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/CusAsyncConvert.java create mode 100644 src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/OrganizationSyncUtil.java create mode 100644 src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/RestApiUtil.java diff --git a/src/main/java/weaver/cssc/workflow/voucher/action/VoucherPushAction.java b/src/main/java/weaver/cssc/workflow/voucher/action/VoucherPushAction.java index 3f7f944..777a4ac 100644 --- a/src/main/java/weaver/cssc/workflow/voucher/action/VoucherPushAction.java +++ b/src/main/java/weaver/cssc/workflow/voucher/action/VoucherPushAction.java @@ -29,7 +29,7 @@ import java.util.Map; * 中国船舶工业 * 流程数据推送NC生成凭证Action * @author bleach - * @Date 2023-06-19 + * @version 2023-06-19 */ public class VoucherPushAction extends SafeCusBaseAction { @@ -69,148 +69,156 @@ public class VoucherPushAction extends SafeCusBaseAction { interfaceLoggerDao.setOperateDateTime(TimeUtil.getCurrentTimeString()); logger.info("workflowId:[" + workflowId + "],requestId:[" + requestId + "],billTable:[" + billTable + "]"); + + //流程请求标题 + String requestName = ""; + //流程请求编号 + String requestMark = ""; + + //获取流程基础信息 + RecordSetTrans rsts = requestInfo.getRsTrans(); + + if(rsts == null){ + rsts = new RecordSetTrans(); + } + + try { + if(rsts.executeQuery("select * from workflow_requestBase where requestId = ?",requestId)){ + if(rsts.next()){ + requestName = Util.null2String(rsts.getString("requestName")); + requestMark = Util.null2String(rsts.getString("requestMark")); + } + } + } catch (Exception e) { + Util.actionFailException(requestInfo.getRequestManager(),"获取流程基本信息异常,异常信息:[" + e.getMessage() + "]!"); + throw new RuntimeException(e); + } + + interfaceLoggerDao.setRequestNo(requestMark); + interfaceLoggerDao.setOperator(user.getUID()); + VoucherUtil voucherUtil = new VoucherUtil(); Map configMap = voucherUtil.getConfigurationByWorkflowId(String.valueOf(workflowId),cusParamValue); - if(configMap != null && configMap.size() > 0){ - //获取数据条件 - String dataCondition = (String) configMap.get("dataCondition"); - - RecordSet rs ; - - if(StringUtils.isNotBlank(dataCondition)){ - dataCondition = ToolUtilNew.staticToDBC(dataCondition); - - rs = sqlMapper.getWorkflowMainInfoAndCusWhere(billTable,requestId,dataCondition); - } else { - rs = sqlMapper.getWorkflowMainInfo(billTable,requestId); - } - - int mainId = -1; - if(rs.next()){ - mainId = Util.getIntValue(rs.getString("id"),-1); - } - - if(mainId > -1){ - //流程请求标题 - String requestName = ""; - //流程请求编号 - String requestMark = ""; - - //获取流程基础信息 - RecordSetTrans rsts = requestInfo.getRsTrans(); - - if(rsts == null){ - rsts = new RecordSetTrans(); - } - - try { - if(rsts.executeQuery("select * from workflow_requestBase where requestId = ?",requestId)){ - if(rsts.next()){ - requestName = Util.null2String(rsts.getString("requestName")); - requestMark = Util.null2String(rsts.getString("requestMark")); - } - } - } catch (Exception e) { - Util.actionFailException(requestInfo.getRequestManager(),"获取流程基本信息异常,异常信息:[" + e.getMessage() + "]!"); - throw new RuntimeException(e); - } - - interfaceLoggerDao.setRequestNo(requestMark); - interfaceLoggerDao.setOperator(user.getUID()); - - List> fieldList = (List>) configMap.get("fieldList"); - List> detailList = (List>) configMap.get("detailList"); - - voucherUtil.setDetailList(detailList); - voucherUtil.setFieldList(fieldList); - - //流程基础信息集合[流程请求ID,流程请求标题,流程请求编号,流程表单名称,主表数据ID] - String[] baseArray = new String[]{requestId,requestName,requestMark,billTable,String.valueOf(mainId)}; - - //根据配置生成JSON对象 - JSONObject jsonObject = voucherUtil.recursionGenerateJSONObject(baseArray,rs,null, 0,"",0,0); - - logger.info("生成JSON字符串为:[" + jsonObject.toJSONString() + "]"); - - interfaceLoggerDao.setRequestBody(jsonObject.toJSONString()); - - //NC凭证接口地址 - String voucherRequestURL = ToolUtilNew.getStaticSystemParamValue("NC_VoucherRequestURL"); - - if(StringUtils.isNotBlank(voucherRequestURL)){ - HttpUtils httpUtils = new HttpUtils(); - - try { - Map headerMap = new HashMap<>(); - headerMap.put("Content-Type", HttpArgsType.APPLICATION_JSON); - - ResponeVo responeVo = httpUtils.apiPostObject(voucherRequestURL,jsonObject,headerMap); - - if(responeVo.getCode() == VoucherConstants.REQUEST_SUCCESS_CODE){ - //获取返回信息 - String result = responeVo.getEntityString(); - - interfaceLoggerDao.setResponseBody(result); - - JSONObject resultObj = JSONObject.parseObject(result); - - if(resultObj.containsKey("code")){ - int code = resultObj.getIntValue("code"); - - if(code == 0){ - String pk = resultObj.getString("pk"); - - String backFieldName = (String) configMap.get("backFieldName"); - if(StringUtils.isNotBlank(backFieldName)){ - sqlMapper.backVoucherNoToBill(billTable,backFieldName,pk,requestId); - } - - interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_SUCCESS); - interfaceLoggerDao.setDealMessage("接口调用成功!"); - } else { - String message = resultObj.getString("msg"); - - interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); - interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,失败状态码:[" + message + "]!"); - interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); - //接口调用失败 - Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口失败,失败状态码:[" + message + "]!"); - } - } else { - interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); - interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,接口返回信息为空!"); - } - } else { - interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); - interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,失败状态码:[" + responeVo.getCode() + "]!"); - interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); - Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口失败,失败状态码:[" + responeVo.getCode() + "]!"); - } - } catch (IOException e) { - interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); - interfaceLoggerDao.setDealMessage("调用NC凭证接口异常,异常信息:" + e.getMessage()); - interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); - logger.error(Util.getErrString(e)); - Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口异常!"); - //throw new RuntimeException(e); - } - } else { - interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_NO_DEAL); - interfaceLoggerDao.setDealMessage("NC凭证接口地址未配置!"); - interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); - Util.actionFailException(requestInfo.getRequestManager(),"NC凭证接口地址未配置!"); - } - } else { - interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_NO_DEAL); - interfaceLoggerDao.setDealMessage("当前流程不满足自定义条件:[" + dataCondition + "]"); - logger.info("当前流程不满足自定义条件:[" + dataCondition + "]"); - } - } else { + if(configMap == null || configMap.size() == 0){ interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_NO_DEAL); interfaceLoggerDao.setDealMessage("该流程自定义参数值[" + cusParamValue + "]对应的配置不存在!"); logger.info("该流程自定义参数值[" + cusParamValue + "]对应的配置不存在!"); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + + return ; + } + + //获取数据条件 + String dataCondition = (String) configMap.get("dataCondition"); + + RecordSet rs ; + + if(StringUtils.isNotBlank(dataCondition)){ + dataCondition = ToolUtilNew.staticToDBC(dataCondition); + + rs = sqlMapper.getWorkflowMainInfoAndCusWhere(billTable,requestId,dataCondition); + } else { + rs = sqlMapper.getWorkflowMainInfo(billTable,requestId); + } + + int mainId = -1; + if(rs.next()){ + mainId = Util.getIntValue(rs.getString("id"),-1); + } + + if(mainId <= 0){ + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_NO_DEAL); + interfaceLoggerDao.setDealMessage("当前流程不满足自定义条件:[" + dataCondition + "]"); + logger.info("当前流程不满足自定义条件:[" + dataCondition + "]"); + + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + + return ; + } + + List> fieldList = (List>) configMap.get("fieldList"); + List> detailList = (List>) configMap.get("detailList"); + + voucherUtil.setDetailList(detailList); + voucherUtil.setFieldList(fieldList); + + //流程基础信息集合[流程请求ID,流程请求标题,流程请求编号,流程表单名称,主表数据ID] + String[] baseArray = new String[]{requestId,requestName,requestMark,billTable,String.valueOf(mainId)}; + + //根据配置生成JSON对象 + JSONObject jsonObject = voucherUtil.recursionGenerateJSONObject(baseArray,rs,null, 0,"",0,0); + + logger.info("生成JSON字符串为:[" + jsonObject.toJSONString() + "]"); + + interfaceLoggerDao.setRequestBody(jsonObject.toJSONString()); + + //NC凭证接口地址 + String voucherRequestURL = ToolUtilNew.getStaticSystemParamValue("NC_VoucherRequestURL"); + + if(StringUtils.isBlank(voucherRequestURL)){ + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_NO_DEAL); + interfaceLoggerDao.setDealMessage("NC凭证接口地址未配置!"); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + Util.actionFailException(requestInfo.getRequestManager(),"NC凭证接口地址未配置!"); + } + + HttpUtils httpUtils = new HttpUtils(); + + try { + Map headerMap = new HashMap<>(); + headerMap.put("Content-Type", HttpArgsType.APPLICATION_JSON); + + ResponeVo responeVo = httpUtils.apiPostObject(voucherRequestURL,jsonObject,headerMap); + + if(responeVo.getCode() != VoucherConstants.REQUEST_SUCCESS_CODE){ + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); + interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,失败状态码:[" + responeVo.getCode() + "]!"); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口失败,失败状态码:[" + responeVo.getCode() + "]!"); + } + + //获取返回信息 + String result = responeVo.getEntityString(); + + interfaceLoggerDao.setResponseBody(result); + + JSONObject resultObj = JSONObject.parseObject(result); + + if(resultObj.containsKey("code")){ + int code = resultObj.getIntValue("code"); + + if(code == 0){ + String pk = resultObj.getString("pk"); + + String backFieldName = (String) configMap.get("backFieldName"); + if(StringUtils.isNotBlank(backFieldName)){ + sqlMapper.backVoucherNoToBill(billTable,backFieldName,pk,requestId); + } + + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_SUCCESS); + interfaceLoggerDao.setDealMessage("接口调用成功!"); + } else { + String message = resultObj.getString("msg"); + + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); + interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,失败状态码:[" + message + "]!"); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + //接口调用失败 + Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口失败,失败状态码:[" + message + "]!"); + } + } else { + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); + interfaceLoggerDao.setDealMessage("调用NC凭证接口失败,接口返回信息为空!"); + } + } catch (IOException e) { + interfaceLoggerDao.setDealStatus(VoucherConstants.DEAL_STATUS_FAILURE); + interfaceLoggerDao.setDealMessage("调用NC凭证接口异常,异常信息:" + e.getMessage()); + interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); + logger.error(Util.getErrString(e)); + Util.actionFailException(requestInfo.getRequestManager(),"调用NC凭证接口异常!"); + //throw new RuntimeException(e); } interfaceLoggerDao.insertInterfaceLog(interfaceLoggerDao); @@ -224,4 +232,4 @@ public class VoucherPushAction extends SafeCusBaseAction { public void setCusParamValue(String cusParamValue) { this.cusParamValue = cusParamValue; } -} +} \ No newline at end of file diff --git a/src/main/java/weaver/weilin/zhu/xyzq/scheduled/entity/SyncConfigDao.java b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/entity/SyncConfigDao.java new file mode 100644 index 0000000..cc17841 --- /dev/null +++ b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/entity/SyncConfigDao.java @@ -0,0 +1,51 @@ +package weaver.weilin.zhu.xyzq.scheduled.entity; + +import aiyh.utils.entity.FieldViewInfo; +import lombok.Data; + +import java.util.List; + +/** + * 兴业证券 + * 组织同步接口配置实体类 + * @author bleach + * @version 2023-07-07 + */ +@Data +public class SyncConfigDao { + /** + * 数据主键ID值 + */ + private int id; + + /** + * 同步至模块ID + */ + private int modeId; + + /** + * 数据类型 0-组织 1-人员 + */ + private int dataType; + + /** + * 建模外键字段 + */ + private FieldViewInfo foreignKeyField; + + /** + * 接口主键字段 + */ + private String keyNodeName; + + /** + * 上一次同步时间戳 + */ + private String lastSyncTs; + + /** + * 详细字段配置集合 + */ + List fieldDataList; + +} diff --git a/src/main/java/weaver/weilin/zhu/xyzq/scheduled/entity/SyncConfigDetailDao.java b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/entity/SyncConfigDetailDao.java new file mode 100644 index 0000000..0a8a8ba --- /dev/null +++ b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/entity/SyncConfigDetailDao.java @@ -0,0 +1,34 @@ +package weaver.weilin.zhu.xyzq.scheduled.entity; + +import aiyh.utils.entity.FieldViewInfo; +import lombok.Data; + +/** + * 兴业证券 + * 组织同步接口字段详细配置实体类 + * @author bleach + * @version 2023-07-07 + */ +@Data +public class SyncConfigDetailDao { + + /** + * 建模模块字段信息 + */ + private FieldViewInfo modeField; + + /** + * 接口字段名称 + */ + private String nodeName; + + /** + * 转换规则 0-不转换 1-系统日期 2-系统日期时间 3-固定值 4-自定义SQL 5-自定义接口 + */ + private int changeRule; + + /** + * 自定义规则 + */ + private String cusSQL; +} diff --git a/src/main/java/weaver/weilin/zhu/xyzq/scheduled/sqlmapper/OrganizationSyncSqlMapper.java b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/sqlmapper/OrganizationSyncSqlMapper.java new file mode 100644 index 0000000..b75d680 --- /dev/null +++ b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/sqlmapper/OrganizationSyncSqlMapper.java @@ -0,0 +1,83 @@ +package weaver.weilin.zhu.xyzq.scheduled.sqlmapper; + +import aiyh.utils.annotation.recordset.*; +import weaver.weilin.zhu.xyzq.scheduled.entity.SyncConfigDao; +import weaver.weilin.zhu.xyzq.scheduled.entity.SyncConfigDetailDao; + +import java.util.List; +import java.util.Map; + +/** + * 兴业证券 + * 组织同步数据库操作接口类 + * @author bleach + * @version 2023-07-07 + */ +@SqlMapper +public interface OrganizationSyncSqlMapper { + /** + * 根据配置的主键ID 获取对应的配置信息 + * @param keyId 配置主键ID值 + * @return 返回配置信息 + */ + @Select("select * from uf_orgSyncConfig where id = #{keyId}") + @CollectionMappings({ + @CollectionMapping( + property = "fieldDataList", + column = "id", + id = @Id(value = Integer.class, methodId = 1) + ) + }) + @Associations({ + @Association( + property = "foreignKeyField", + column = "foreignKeyField", + select = "weaver.common.util.CommonUtil.getFieldInfo", + id = @Id(Integer.class) + ) + }) + SyncConfigDao getConfigurationByKeyId(@ParamMapper("keyId") int keyId); + + /** + * 获取详细的字段配置信息 + * @param mainId 主表主键ID + * @return 详细字段配置集合 + */ + @Select("select * from uf_orgSyncConfig_dt1 where mainId = #{mainId}") + @Associations({ + @Association( + property = "modeField", + column = "modeField", + select = "weaver.common.util.CommonUtil.getFieldInfo", + id = @Id(Integer.class) + ) + }) + @CollectionMethod(value = 1,desc = "获取详细的字段配置信息") + List getConfigurationDetailByMainKeyId(@ParamMapper("mainId") int mainId); + + /** + * 获取当前模块中已存在记录集合 + * @param foreignKeyFieldName 外键字段名称 + * @param modeTable 模块表名称 + * @return 数据集合 + */ + @Select("select $t{foreignKeyFieldName},id from $t{modeTable}") + Map getModeExistData(@ParamMapper("foreignKeyFieldName") String foreignKeyFieldName,@ParamMapper("modeTable") String modeTable); + + /** + * 更新建模数据 + * @param updateSql 更新的SQL语句 + * @param params 参数集合 + * @return 执行结果 + */ + @Update(custom = true) + boolean updateModeData(@SqlString String updateSql, Map params); + + /** + * 删除插入失败的冗余数据 + * @param modeTable 删除的表名称 + * @param id 数据ID + */ + @Delete("delete from $t{modeTable} where id = #{id}") + void deleteRedundancyData(@ParamMapper("modeTable") String modeTable,@ParamMapper("id") int id); +} diff --git a/src/main/java/weaver/weilin/zhu/xyzq/scheduled/task/SyncOrgDataTask.java b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/task/SyncOrgDataTask.java new file mode 100644 index 0000000..a6e2c5a --- /dev/null +++ b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/task/SyncOrgDataTask.java @@ -0,0 +1,38 @@ +package weaver.weilin.zhu.xyzq.scheduled.task; + +import aiyh.utils.Util; +import org.apache.commons.lang3.StringUtils; +import weaver.interfaces.schedule.BaseCronJob; +import weaver.weilin.zhu.xyzq.scheduled.util.OrganizationSyncUtil; + +/** + * 兴业证券 + * 同步组织数据入建模表 计划任务入口 + * @author bleach + * @version 2023-07-07 + */ +public class SyncOrgDataTask extends BaseCronJob { + + /** + * 配置主键ID + */ + private String keyId ; + + @Override + public void execute() { + if(StringUtils.isNotBlank(keyId)){ + OrganizationSyncUtil syncUtil = new OrganizationSyncUtil(); + + syncUtil.syncData(Util.getIntValue(keyId,0)); + } + } + + + public String getKeyId() { + return keyId; + } + + public void setKeyId(String keyId) { + this.keyId = keyId; + } +} diff --git a/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/ChangeRuleMethod.java b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/ChangeRuleMethod.java new file mode 100644 index 0000000..b4e9c41 --- /dev/null +++ b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/ChangeRuleMethod.java @@ -0,0 +1,151 @@ +package weaver.weilin.zhu.xyzq.scheduled.util; + +import aiyh.utils.Util; +import aiyh.utils.annotation.MethodRuleNo; +import aiyh.utils.excention.CustomerException; +import com.google.common.base.Strings; +import org.apache.log4j.Logger; + +import weaver.general.TimeUtil; +import weaver.weilin.zhu.xyzq.scheduled.entity.SyncConfigDetailDao; +import weaver.zwl.common.ToolUtilNew; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiFunction; + +/** + * 自定义转换规则处理 + * @author bleach + * @version 2023-07-01 + */ +public class ChangeRuleMethod { + + /** + * 日志操作 + */ + private final Logger logger = Util.getLogger(); + + + public static final Map, Object>> VALUE_RULE_FUNCTION = new HashMap<>(); + + static { + Class valueRuleMethodClass = ChangeRuleMethod.class; + Method[] methods = valueRuleMethodClass.getMethods(); + for (Method method : methods) { + if (method.isAnnotationPresent(MethodRuleNo.class)) { + MethodRuleNo annotation = method.getAnnotation(MethodRuleNo.class); + int value = annotation.value();//规则标识 + VALUE_RULE_FUNCTION.put(value, (config, map) -> { + try { + ChangeRuleMethod valueRuleMethod = new ChangeRuleMethod(); + return method.invoke(valueRuleMethod, config, map); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + }); + } + } + } + + /** + * 不转换 + * @param dao 明细配置 + * @param map 接口数据集合 + * @return 返回转换后的值 + */ + @MethodRuleNo(value = 0, desc = "不转换") + public Object noChange(SyncConfigDetailDao dao,Map map) { + String fieldName = dao.getNodeName();//字段名称 + //根据字段名称,获取其对应的字段值 + if(map.containsKey(fieldName)){ + return Util.null2String(map.get(fieldName)); + } else { + return null; + } + } + + /** + * 系统日期 + * @param dao 明细配置 + * @param map 接口数据集合 + * @return 返回转换后的值 + */ + @MethodRuleNo(value = 1, desc = "系统日期") + public Object systemDate(SyncConfigDetailDao dao,Map map) { + return TimeUtil.getCurrentDateString(); + } + + /** + * 系统日期 + * @param dao 明细配置 + * @param map 接口数据集合 + * @return 返回转换后的值 + */ + @MethodRuleNo(value = 2, desc = "系统日期时间") + public Object systemDateTime(SyncConfigDetailDao dao,Map map) { + return TimeUtil.getCurrentTimeString(); + } + + /** + * 固定值 + * @param dao 明细配置 + * @param map 接口数据集合 + * @return 返回转换后的值 + */ + @MethodRuleNo(value = 3, desc = "固定值") + public Object fixValue(SyncConfigDetailDao dao,Map map) { + return Util.null2String(dao.getCusSQL()); + } + + /** + * 固定值 + * @param dao 明细配置 + * @param map 接口数据集合 + * @return 返回转换后的值 + */ + @MethodRuleNo(value = 4, desc = "自定义SQL") + public Object customizeSQL(SyncConfigDetailDao dao,Map map) { + String fieldName = dao.getNodeName();//字段名称 + + //字段值 + String fieldValue = ""; + + //根据字段名称,获取其对应的字段值 + if(map.containsKey(fieldName)) { + fieldValue = Util.null2String(map.get(fieldName)); + } + + fieldValue = ToolUtilNew.getStaticValueByChangeRule(dao.getCusSQL(),fieldValue); + + return fieldValue; + } + + /** + * 自定义转换接口 + * @param dao 明细配置 + * @param map 接口数据集合 + * @return 返回转换后的值 + */ + @MethodRuleNo(value = 5, desc = "自定义接口") + public Object getCusConvertInterface(SyncConfigDetailDao dao, Map map) { + String cusText = dao.getCusSQL(); + if(Strings.isNullOrEmpty(cusText)){ + return null; + } + try { + Class clazz = Class.forName(cusText); + if(!CusAsyncConvert.class.isAssignableFrom(clazz)){ + throw new CustomerException(cusText + " 接口不存在或者未实现 weaver.weilin.zhu.xyzq.scheduled.util.CusAsyncConvert类!"); + } + CusAsyncConvert o = (CusAsyncConvert) clazz.newInstance(); + Map pathParam = Util.parseCusInterfacePathParam(cusText); + return o.cusConvert(dao, map, pathParam); + }catch (Exception e){ + logger.error("getCusConvertInterface error! " + e.getMessage()); + return null; + } + } +} diff --git a/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/CusAsyncConvert.java b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/CusAsyncConvert.java new file mode 100644 index 0000000..2d40145 --- /dev/null +++ b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/CusAsyncConvert.java @@ -0,0 +1,17 @@ +package weaver.weilin.zhu.xyzq.scheduled.util; + +import aiyh.utils.Util; +import org.apache.log4j.Logger; +import weaver.weilin.zhu.xyzq.scheduled.entity.SyncConfigDetailDao; + +import java.util.Map; + +/** + *

自定义转换接口

+ * + * @author bleach + */ +public interface CusAsyncConvert { + Logger log = Util.getLogger(); + Object cusConvert(SyncConfigDetailDao dao, Map maps, Map pathParam); +} diff --git a/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/OrganizationSyncUtil.java b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/OrganizationSyncUtil.java new file mode 100644 index 0000000..274c1e8 --- /dev/null +++ b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/OrganizationSyncUtil.java @@ -0,0 +1,159 @@ +package weaver.weilin.zhu.xyzq.scheduled.util; + +import aiyh.utils.Util; +import aiyh.utils.entity.FieldViewInfo; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import weaver.general.TimeUtil; +import weaver.weilin.zhu.xyzq.scheduled.entity.SyncConfigDao; +import weaver.weilin.zhu.xyzq.scheduled.entity.SyncConfigDetailDao; +import weaver.weilin.zhu.xyzq.scheduled.sqlmapper.OrganizationSyncSqlMapper; +import weaver.zwl.common.ToolUtilNew; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * 兴业证券 + * 组织同步工具类 + * @author bleach + * @version 2023-07-07 + */ +public class OrganizationSyncUtil { + + /** + * 日志操作类 + */ + private final Logger logger = Util.getLogger(); + + /** + * 数据库操作接口 + */ + private final OrganizationSyncSqlMapper sqlMapper = Util.getMapper(OrganizationSyncSqlMapper.class); + + /** + * 执行同步操作 + * @param keyId 配置主键ID + */ + public synchronized void syncData(int keyId){ + SyncConfigDao syncConfigDao = sqlMapper.getConfigurationByKeyId(keyId); + + assert syncConfigDao != null; + + //同步至模块ID + int modeId = syncConfigDao.getModeId(); + + if(modeId <= 0){ + logger.info("未配置对应的模块!"); + return; + } + + //获取模块对应的表名称 + String modeTable = ToolUtilNew.getModeTableById(modeId); + + if(StringUtils.isBlank(modeTable)){ + logger.info("该模块对应的表名称不存在!"); + return; + } + + //模块的外键 + FieldViewInfo foreignKeyField = syncConfigDao.getForeignKeyField(); + + if(foreignKeyField == null){ + logger.info("外键字段为空!"); + return; + } + + //获取当前库中已存在的记录集合 + Map oaDataMap = sqlMapper.getModeExistData(foreignKeyField.getFieldName(), modeTable); + + //上一次同步时间戳 + String lastSyncTs = StringUtils.isNotBlank(syncConfigDao.getLastSyncTs()) ? syncConfigDao.getLastSyncTs() : "2000-01-01 00:00:01"; + + RestApiUtil restApiUtil = new RestApiUtil(); + + List> dataList = restApiUtil.getOrganizationList(lastSyncTs, syncConfigDao.getDataType()); + + + // 使用 Stream 对接口数据进行去除重复记录 + List> distinctList = dataList.stream() + .filter(distinctByKey(map -> map.get(syncConfigDao.getKeyNodeName()))) + .collect(Collectors.toList()); + + dealDataOperate(modeTable,modeId,syncConfigDao.getKeyNodeName(),distinctList,oaDataMap,syncConfigDao.getFieldDataList()); + + } + + /** + * 数据处理操作 + * @param billTable 表单名称 + * @param modeId 模块ID + * @param keyNodeName 主键节点名称 + * @param dataList 接口数据集 + * @param oaDataMap OA数据集 + * @param detailDaoList 字段详细配置集合 + */ + private void dealDataOperate(String billTable,int modeId,String keyNodeName,List> dataList, Map oaDataMap, List detailDaoList){ + + String currentDateTime = TimeUtil.getCurrentTimeString(); + + for(Map interfaceMap : dataList){ + //获取主键值 + String keyNodeValue = Util.null2String(interfaceMap.get(keyNodeName)); + + if(StringUtils.isBlank(keyNodeValue)){ + continue; + } + + int dataId; + boolean isNewData = false; + if(oaDataMap.containsKey(keyNodeValue)){//该数据已在历史记录中存在 + dataId = oaDataMap.get(keyNodeValue); + } else {//该记录不存在 + dataId = Util.getModeDataId(billTable,modeId,1); + isNewData = true; + } + + StringBuilder setColumns = new StringBuilder(); + + Map paramMap = new HashMap<>(); + + for(SyncConfigDetailDao dao : detailDaoList){ + String modeFieldName = dao.getModeField().getFieldName(); + + setColumns.append(",").append(modeFieldName).append(" = #{").append(modeFieldName).append("}"); + + Object fieldValue = ChangeRuleMethod.VALUE_RULE_FUNCTION.get(dao.getChangeRule()).apply(dao, interfaceMap); + + paramMap.put(modeFieldName,fieldValue); + } + + String updateSQL = "update " + billTable + " set modeDataModifyDatetime = '" + currentDateTime + "'" + setColumns.toString() + " where id = #{id}"; + + paramMap.put("id",dataId); + + if(sqlMapper.updateModeData(updateSQL,paramMap)){ + if(isNewData){ + oaDataMap.put(keyNodeName,dataId); + } + } else{ + sqlMapper.deleteRedundancyData(billTable,dataId); + } + } + } + + /** + * 判断是否重复 + * @param keyExtractor 重复主键 + * @return 返回是否重复 + * @param 主键值 + */ + private Predicate distinctByKey(Function keyExtractor) { + Map seen = new HashMap<>(); + return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } +} diff --git a/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/RestApiUtil.java b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/RestApiUtil.java new file mode 100644 index 0000000..1e01c03 --- /dev/null +++ b/src/main/java/weaver/weilin/zhu/xyzq/scheduled/util/RestApiUtil.java @@ -0,0 +1,129 @@ +package weaver.weilin.zhu.xyzq.scheduled.util; + +import aiyh.utils.Util; +import aiyh.utils.httpUtil.HttpArgsType; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtils; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; +import weaver.zwl.common.ToolUtilNew; + +import java.io.IOException; +import java.util.*; + +/** + * 兴业证券 + * API 请求工具类 + * @author bleach + */ +public class RestApiUtil { + + /** + * 基本参数 + */ + private Map paramMap; + + /** + * 日志操作类 + */ + private final Logger logger = Util.getLogger(); + + /** + * HTTP请求工具类 + */ + private final HttpUtils httpUtils = new HttpUtils(); + + /** + * 无参构造方法 + */ + public RestApiUtil(){ + initParam(); + } + + /** + * 获取组织信息列表 + * @param lastSyncDateTime 上一次同步时间戳 + * @param dataType 数据类型 0-组织 1-人员 + * @return 返回接口返回的数据集 + */ + @SuppressWarnings("unchecked") + public List> getOrganizationList(String lastSyncDateTime,int dataType){ + String requestBaseURL = Util.null2String(paramMap.get("Organization_BaseURL")); + + Map headerMap = new HashMap<>(); + headerMap.put("Content-Type", HttpArgsType.APPLICATION_JSON); + + String actualRequestURL = ""; + + if(dataType == 0){ + actualRequestURL = requestBaseURL + "RESTHRService/GetOrganizationList"; + } else if (dataType == 1) { + actualRequestURL = requestBaseURL + "RESTHRService/GetEmployeeList"; + } + + JSONObject requestBody = new JSONObject(); + requestBody.put("sysid",Util.null2String(paramMap.get("Organization_SysId"))); + requestBody.put("data_upd_tm",lastSyncDateTime); + requestBody.put("size",100); + + int page = 1; + boolean hasNextPage; + + List> mergedDataList = new ArrayList<>(); + + do { + requestBody.put("page",page); + + try { + ResponeVo responeVo = httpUtils.apiPostObject(actualRequestURL, requestBody, headerMap); + + if(responeVo != null && responeVo.getCode() == 200){ + //获取接口返回信息 + String entityString = responeVo.getEntityString(); + + if(StringUtils.isBlank(entityString)) { + logger.info("接口调用失败,返回信息为空!"); + break; + } + JSONObject resultObj = JSONObject.parseObject(entityString); + + String responseData = resultObj.getString("ResponseData"); + + JSONObject responseDataObj = JSONObject.parseObject(responseData); + + boolean isSuccess = (boolean) Util.getValueByKeyStr("resphead.success",responseDataObj); + + if(isSuccess){ + hasNextPage = (boolean) Util.getValueByKeyStr("respbody.data.hasNextPage",responseDataObj); + + //详细数据集合 + List> dataList = (List>) Util.getValueByKeyStr("respbody.data.list",responseDataObj); + + mergedDataList.addAll((Collection>) dataList); + page ++; + } else { + //接口获取失败 + return null; + } + } else { + assert responeVo != null; + logger.info("接口调用失败,失败状态码:[" + responeVo.getCode() + "]"); + break; + } + } catch (IOException e) { + logger.info(Util.getErrString(e)); + throw new RuntimeException(e); + } + } while (hasNextPage); + + return mergedDataList; + } + + /** + * 初始化参数配置 + */ + private void initParam(){ + paramMap = ToolUtilNew.getSystemParamList("Organization_"); + } +} diff --git a/src/main/java/weaver/zwl/common/ToolUtilNew.java b/src/main/java/weaver/zwl/common/ToolUtilNew.java index 6b74c17..05c0ee2 100644 --- a/src/main/java/weaver/zwl/common/ToolUtilNew.java +++ b/src/main/java/weaver/zwl/common/ToolUtilNew.java @@ -423,4 +423,17 @@ public class ToolUtilNew extends ToolUtil{ return returnString; } + /** + * 获取模块ID获取其表名称 + * @param modeId 模块ID + * @return 表单名称 + */ + public static String getModeTableById(int modeId){ + RecordSet rs = new RecordSet(); + + if(rs.executeQuery("select wb.tablename from modeInfo m inner join workflow_bill wb on m.formid = wb.id where m.id = ?") && rs.next()){ + return Util.null2String(rs.getString(1)); + } + return ""; + } } From f672d68ac07b30e2616819b59f9ccc7eb3ca8a19 Mon Sep 17 00:00:00 2001 From: "youhong.ai" Date: Mon, 10 Jul 2023 14:53:28 +0800 Subject: [PATCH 09/14] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E6=89=93=E5=8C=85=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../youhong.ai/pcn/workflow_code_block.js | 1 - node_modules/.bin/loose-envify | 1 + node_modules/.package-lock.json | 56 + node_modules/js-tokens/CHANGELOG.md | 151 + node_modules/js-tokens/LICENSE | 21 + node_modules/js-tokens/README.md | 240 + node_modules/js-tokens/index.js | 23 + node_modules/js-tokens/package.json | 30 + node_modules/loose-envify/LICENSE | 21 + node_modules/loose-envify/README.md | 45 + node_modules/loose-envify/cli.js | 16 + node_modules/loose-envify/custom.js | 4 + node_modules/loose-envify/index.js | 3 + node_modules/loose-envify/loose-envify.js | 36 + node_modules/loose-envify/package.json | 36 + node_modules/loose-envify/replace.js | 65 + node_modules/react-dom/LICENSE | 21 + node_modules/react-dom/README.md | 60 + ...t-dom-server-legacy.browser.development.js | 7018 ++++ ...om-server-legacy.browser.production.min.js | 93 + ...eact-dom-server-legacy.node.development.js | 7078 ++++ ...t-dom-server-legacy.node.production.min.js | 101 + .../react-dom-server.browser.development.js | 7003 ++++ ...react-dom-server.browser.production.min.js | 96 + .../cjs/react-dom-server.node.development.js | 7059 ++++ .../react-dom-server.node.production.min.js | 102 + .../cjs/react-dom-test-utils.development.js | 1741 + .../react-dom-test-utils.production.min.js | 40 + .../react-dom/cjs/react-dom.development.js | 29868 +++++++++++++++ .../react-dom/cjs/react-dom.production.min.js | 323 + .../react-dom/cjs/react-dom.profiling.min.js | 367 + node_modules/react-dom/client.js | 25 + node_modules/react-dom/index.js | 38 + node_modules/react-dom/package.json | 62 + node_modules/react-dom/profiling.js | 38 + node_modules/react-dom/server.browser.js | 17 + node_modules/react-dom/server.js | 3 + node_modules/react-dom/server.node.js | 17 + node_modules/react-dom/test-utils.js | 7 + ...t-dom-server-legacy.browser.development.js | 7015 ++++ ...om-server-legacy.browser.production.min.js | 75 + .../react-dom-server.browser.development.js | 7000 ++++ ...react-dom-server.browser.production.min.js | 76 + .../umd/react-dom-test-utils.development.js | 1737 + .../react-dom-test-utils.production.min.js | 33 + .../react-dom/umd/react-dom.development.js | 29869 ++++++++++++++++ .../react-dom/umd/react-dom.production.min.js | 267 + .../react-dom/umd/react-dom.profiling.min.js | 285 + node_modules/react/LICENSE | 21 + node_modules/react/README.md | 37 + .../cjs/react-jsx-dev-runtime.development.js | 1296 + .../react-jsx-dev-runtime.production.min.js | 10 + .../react-jsx-dev-runtime.profiling.min.js | 10 + .../cjs/react-jsx-runtime.development.js | 1314 + .../cjs/react-jsx-runtime.production.min.js | 11 + .../cjs/react-jsx-runtime.profiling.min.js | 11 + node_modules/react/cjs/react.development.js | 2739 ++ .../react/cjs/react.production.min.js | 26 + .../cjs/react.shared-subset.development.js | 20 + .../cjs/react.shared-subset.production.min.js | 10 + node_modules/react/index.js | 7 + node_modules/react/jsx-dev-runtime.js | 7 + node_modules/react/jsx-runtime.js | 7 + node_modules/react/package.json | 47 + node_modules/react/react.shared-subset.js | 7 + node_modules/react/umd/react.development.js | 3342 ++ .../react/umd/react.production.min.js | 31 + node_modules/react/umd/react.profiling.min.js | 31 + node_modules/scheduler/LICENSE | 21 + node_modules/scheduler/README.md | 9 + .../scheduler-unstable_mock.development.js | 700 + .../scheduler-unstable_mock.production.min.js | 20 + ...cheduler-unstable_post_task.development.js | 207 + ...duler-unstable_post_task.production.min.js | 14 + .../scheduler/cjs/scheduler.development.js | 634 + .../scheduler/cjs/scheduler.production.min.js | 19 + node_modules/scheduler/index.js | 7 + node_modules/scheduler/package.json | 36 + .../scheduler-unstable_mock.development.js | 699 + .../scheduler-unstable_mock.production.min.js | 19 + .../scheduler/umd/scheduler.development.js | 152 + .../scheduler/umd/scheduler.production.min.js | 146 + .../scheduler/umd/scheduler.profiling.min.js | 146 + node_modules/scheduler/unstable_mock.js | 7 + node_modules/scheduler/unstable_post_task.js | 7 + package-lock.json | 63 + package.json | 7 + .../utils/annotation/ValueRuleMethodNo.java | 20 + .../controller/ExamBtnControlController.java | 16 + .../mapper/ExamBtnControlMapper.java | 56 + .../service/ExamBtnControlService.java | 91 +- .../util/CompressPictureUtil.java | 33 +- .../service/WorkflowQueueService.java | 98 +- src/test/java/BuilderPackageEcology.java | 23 +- .../java/builderpackage/FileTreeBuilder.java | 4 +- 95 files changed, 120469 insertions(+), 52 deletions(-) create mode 120000 node_modules/.bin/loose-envify create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/js-tokens/CHANGELOG.md create mode 100644 node_modules/js-tokens/LICENSE create mode 100644 node_modules/js-tokens/README.md create mode 100644 node_modules/js-tokens/index.js create mode 100644 node_modules/js-tokens/package.json create mode 100644 node_modules/loose-envify/LICENSE create mode 100644 node_modules/loose-envify/README.md create mode 100755 node_modules/loose-envify/cli.js create mode 100644 node_modules/loose-envify/custom.js create mode 100644 node_modules/loose-envify/index.js create mode 100644 node_modules/loose-envify/loose-envify.js create mode 100644 node_modules/loose-envify/package.json create mode 100644 node_modules/loose-envify/replace.js create mode 100644 node_modules/react-dom/LICENSE create mode 100644 node_modules/react-dom/README.md create mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.node.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.browser.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.browser.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.node.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.node.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-test-utils.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-test-utils.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom.development.js create mode 100644 node_modules/react-dom/cjs/react-dom.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom.profiling.min.js create mode 100644 node_modules/react-dom/client.js create mode 100644 node_modules/react-dom/index.js create mode 100644 node_modules/react-dom/package.json create mode 100644 node_modules/react-dom/profiling.js create mode 100644 node_modules/react-dom/server.browser.js create mode 100644 node_modules/react-dom/server.js create mode 100644 node_modules/react-dom/server.node.js create mode 100644 node_modules/react-dom/test-utils.js create mode 100644 node_modules/react-dom/umd/react-dom-server-legacy.browser.development.js create mode 100644 node_modules/react-dom/umd/react-dom-server-legacy.browser.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom-server.browser.development.js create mode 100644 node_modules/react-dom/umd/react-dom-server.browser.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom-test-utils.development.js create mode 100644 node_modules/react-dom/umd/react-dom-test-utils.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom.development.js create mode 100644 node_modules/react-dom/umd/react-dom.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom.profiling.min.js create mode 100644 node_modules/react/LICENSE create mode 100644 node_modules/react/README.md create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.development.js create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.production.min.js create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.profiling.min.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.development.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.production.min.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.profiling.min.js create mode 100644 node_modules/react/cjs/react.development.js create mode 100644 node_modules/react/cjs/react.production.min.js create mode 100644 node_modules/react/cjs/react.shared-subset.development.js create mode 100644 node_modules/react/cjs/react.shared-subset.production.min.js create mode 100644 node_modules/react/index.js create mode 100644 node_modules/react/jsx-dev-runtime.js create mode 100644 node_modules/react/jsx-runtime.js create mode 100644 node_modules/react/package.json create mode 100644 node_modules/react/react.shared-subset.js create mode 100644 node_modules/react/umd/react.development.js create mode 100644 node_modules/react/umd/react.production.min.js create mode 100644 node_modules/react/umd/react.profiling.min.js create mode 100644 node_modules/scheduler/LICENSE create mode 100644 node_modules/scheduler/README.md create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_mock.development.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_mock.production.min.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_post_task.development.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_post_task.production.min.js create mode 100644 node_modules/scheduler/cjs/scheduler.development.js create mode 100644 node_modules/scheduler/cjs/scheduler.production.min.js create mode 100644 node_modules/scheduler/index.js create mode 100644 node_modules/scheduler/package.json create mode 100644 node_modules/scheduler/umd/scheduler-unstable_mock.development.js create mode 100644 node_modules/scheduler/umd/scheduler-unstable_mock.production.min.js create mode 100644 node_modules/scheduler/umd/scheduler.development.js create mode 100644 node_modules/scheduler/umd/scheduler.production.min.js create mode 100644 node_modules/scheduler/umd/scheduler.profiling.min.js create mode 100644 node_modules/scheduler/unstable_mock.js create mode 100644 node_modules/scheduler/unstable_post_task.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/main/java/aiyh/utils/annotation/ValueRuleMethodNo.java diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 8d9c82c..3bc9bfc 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -1083,7 +1083,6 @@ $(() => { table: config.table, questNumberMap: typeNumberObj } - console.log('请求参数', params) Utils.api({ url: "/api/aiyh/exam-btn/control/random-test-questions", data: JSON.stringify(params), diff --git a/node_modules/.bin/loose-envify b/node_modules/.bin/loose-envify new file mode 120000 index 0000000..ed9009c --- /dev/null +++ b/node_modules/.bin/loose-envify @@ -0,0 +1 @@ +../loose-envify/cli.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..e2cb869 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,56 @@ +{ + "name": "ecology9-project", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/react": { + "version": "18.2.0", + "resolved": "https://registry.npmmirror.com/react/-/react-18.2.0.tgz", + "integrity": "sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.2.0", + "resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-18.2.0.tgz", + "integrity": "sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.0" + }, + "peerDependencies": { + "react": "^18.2.0" + } + }, + "node_modules/scheduler": { + "version": "0.23.0", + "resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.23.0.tgz", + "integrity": "sha512-CtuThmgHNg7zIZWAXi3AsyIzA3n4xx7aNyjwC2VJldO2LMVDhFK+63xGqq6CsJH4rTAt6/M+N4GhZiDYPx9eUw==", + "dependencies": { + "loose-envify": "^1.1.0" + } + } + } +} diff --git a/node_modules/js-tokens/CHANGELOG.md b/node_modules/js-tokens/CHANGELOG.md new file mode 100644 index 0000000..755e6f6 --- /dev/null +++ b/node_modules/js-tokens/CHANGELOG.md @@ -0,0 +1,151 @@ +### Version 4.0.0 (2018-01-28) ### + +- Added: Support for ES2018. The only change needed was recognizing the `s` + regex flag. +- Changed: _All_ tokens returned by the `matchToToken` function now have a + `closed` property. It is set to `undefined` for the tokens where “closed” + doesn’t make sense. This means that all tokens objects have the same shape, + which might improve performance. + +These are the breaking changes: + +- `'/a/s'.match(jsTokens)` no longer returns `['/', 'a', '/', 's']`, but + `['/a/s']`. (There are of course other variations of this.) +- Code that rely on some token objects not having the `closed` property could + now behave differently. + + +### Version 3.0.2 (2017-06-28) ### + +- No code changes. Just updates to the readme. + + +### Version 3.0.1 (2017-01-30) ### + +- Fixed: ES2015 unicode escapes with more than 6 hex digits are now matched + correctly. + + +### Version 3.0.0 (2017-01-11) ### + +This release contains one breaking change, that should [improve performance in +V8][v8-perf]: + +> So how can you, as a JavaScript developer, ensure that your RegExps are fast? +> If you are not interested in hooking into RegExp internals, make sure that +> neither the RegExp instance, nor its prototype is modified in order to get the +> best performance: +> +> ```js +> var re = /./g; +> re.exec(''); // Fast path. +> re.new_property = 'slow'; +> ``` + +This module used to export a single regex, with `.matchToToken` bolted +on, just like in the above example. This release changes the exports of +the module to avoid this issue. + +Before: + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens") +var matchToToken = jsTokens.matchToToken +``` + +After: + +```js +import jsTokens, {matchToToken} from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +var matchToToken = require("js-tokens").matchToToken +``` + +[v8-perf]: http://v8project.blogspot.se/2017/01/speeding-up-v8-regular-expressions.html + + +### Version 2.0.0 (2016-06-19) ### + +- Added: Support for ES2016. In other words, support for the `**` exponentiation + operator. + +These are the breaking changes: + +- `'**'.match(jsTokens)` no longer returns `['*', '*']`, but `['**']`. +- `'**='.match(jsTokens)` no longer returns `['*', '*=']`, but `['**=']`. + + +### Version 1.0.3 (2016-03-27) ### + +- Improved: Made the regex ever so slightly smaller. +- Updated: The readme. + + +### Version 1.0.2 (2015-10-18) ### + +- Improved: Limited npm package contents for a smaller download. Thanks to + @zertosh! + + +### Version 1.0.1 (2015-06-20) ### + +- Fixed: Declared an undeclared variable. + + +### Version 1.0.0 (2015-02-26) ### + +- Changed: Merged the 'operator' and 'punctuation' types into 'punctuator'. That + type is now equivalent to the Punctuator token in the ECMAScript + specification. (Backwards-incompatible change.) +- Fixed: A `-` followed by a number is now correctly matched as a punctuator + followed by a number. It used to be matched as just a number, but there is no + such thing as negative number literals. (Possibly backwards-incompatible + change.) + + +### Version 0.4.1 (2015-02-21) ### + +- Added: Support for the regex `u` flag. + + +### Version 0.4.0 (2015-02-21) ### + +- Improved: `jsTokens.matchToToken` performance. +- Added: Support for octal and binary number literals. +- Added: Support for template strings. + + +### Version 0.3.1 (2015-01-06) ### + +- Fixed: Support for unicode spaces. They used to be allowed in names (which is + very confusing), and some unicode newlines were wrongly allowed in strings and + regexes. + + +### Version 0.3.0 (2014-12-19) ### + +- Changed: The `jsTokens.names` array has been replaced with the + `jsTokens.matchToToken` function. The capturing groups of `jsTokens` are no + longer part of the public API; instead use said function. See this [gist] for + an example. (Backwards-incompatible change.) +- Changed: The empty string is now considered an “invalid” token, instead an + “empty” token (its own group). (Backwards-incompatible change.) +- Removed: component support. (Backwards-incompatible change.) + +[gist]: https://gist.github.com/lydell/be49dbf80c382c473004 + + +### Version 0.2.0 (2014-06-19) ### + +- Changed: Match ES6 function arrows (`=>`) as an operator, instead of its own + category (“functionArrow”), for simplicity. (Backwards-incompatible change.) +- Added: ES6 splats (`...`) are now matched as an operator (instead of three + punctuations). (Backwards-incompatible change.) + + +### Version 0.1.0 (2014-03-08) ### + +- Initial release. diff --git a/node_modules/js-tokens/LICENSE b/node_modules/js-tokens/LICENSE new file mode 100644 index 0000000..54aef52 --- /dev/null +++ b/node_modules/js-tokens/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell + +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. diff --git a/node_modules/js-tokens/README.md b/node_modules/js-tokens/README.md new file mode 100644 index 0000000..00cdf16 --- /dev/null +++ b/node_modules/js-tokens/README.md @@ -0,0 +1,240 @@ +Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) +======== + +A regex that tokenizes JavaScript. + +```js +var jsTokens = require("js-tokens").default + +var jsString = "var foo=opts.foo;\n..." + +jsString.match(jsTokens) +// ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] +``` + + +Installation +============ + +`npm install js-tokens` + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +``` + + +Usage +===== + +### `jsTokens` ### + +A regex with the `g` flag that matches JavaScript tokens. + +The regex _always_ matches, even invalid JavaScript and the empty string. + +The next match is always directly after the previous. + +### `var token = matchToToken(match)` ### + +```js +import {matchToToken} from "js-tokens" +// or: +var matchToToken = require("js-tokens").matchToToken +``` + +Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: +String, value: String}` object. The following types are available: + +- string +- comment +- regex +- number +- name +- punctuator +- whitespace +- invalid + +Multi-line comments and strings also have a `closed` property indicating if the +token was closed or not (see below). + +Comments and strings both come in several flavors. To distinguish them, check if +the token starts with `//`, `/*`, `'`, `"` or `` ` ``. + +Names are ECMAScript IdentifierNames, that is, including both identifiers and +keywords. You may use [is-keyword-js] to tell them apart. + +Whitespace includes both line terminators and other whitespace. + +[is-keyword-js]: https://github.com/crissdev/is-keyword-js + + +ECMAScript support +================== + +The intention is to always support the latest ECMAScript version whose feature +set has been finalized. + +If adding support for a newer version requires changes, a new version with a +major verion bump will be released. + +Currently, ECMAScript 2018 is supported. + + +Invalid code handling +===================== + +Unterminated strings are still matched as strings. JavaScript strings cannot +contain (unescaped) newlines, so unterminated strings simply end at the end of +the line. Unterminated template strings can contain unescaped newlines, though, +so they go on to the end of input. + +Unterminated multi-line comments are also still matched as comments. They +simply go on to the end of the input. + +Unterminated regex literals are likely matched as division and whatever is +inside the regex. + +Invalid ASCII characters have their own capturing group. + +Invalid non-ASCII characters are treated as names, to simplify the matching of +names (except unicode spaces which are treated as whitespace). Note: See also +the [ES2018](#es2018) section. + +Regex literals may contain invalid regex syntax. They are still matched as +regex literals. They may also contain repeated regex flags, to keep the regex +simple. + +Strings may contain invalid escape sequences. + + +Limitations +=========== + +Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be +perfect. But that’s not the point either. + +You may compare jsTokens with [esprima] by using `esprima-compare.js`. +See `npm run esprima-compare`! + +[esprima]: http://esprima.org/ + +### Template string interpolation ### + +Template strings are matched as single tokens, from the starting `` ` `` to the +ending `` ` ``, including interpolations (whose tokens are not matched +individually). + +Matching template string interpolations requires recursive balancing of `{` and +`}`—something that JavaScript regexes cannot do. Only one level of nesting is +supported. + +### Division and regex literals collision ### + +Consider this example: + +```js +var g = 9.82 +var number = bar / 2/g + +var regex = / 2/g +``` + +A human can easily understand that in the `number` line we’re dealing with +division, and in the `regex` line we’re dealing with a regex literal. How come? +Because humans can look at the whole code to put the `/` characters in context. +A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also +look backwards. See the [ES2018](#es2018) section). + +When the `jsTokens` regex scans throught the above, it will see the following +at the end of both the `number` and `regex` rows: + +```js +/ 2/g +``` + +It is then impossible to know if that is a regex literal, or part of an +expression dealing with division. + +Here is a similar case: + +```js +foo /= 2/g +foo(/= 2/g) +``` + +The first line divides the `foo` variable with `2/g`. The second line calls the +`foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only +sees forwards, it cannot tell the two cases apart. + +There are some cases where we _can_ tell division and regex literals apart, +though. + +First off, we have the simple cases where there’s only one slash in the line: + +```js +var foo = 2/g +foo /= 2 +``` + +Regex literals cannot contain newlines, so the above cases are correctly +identified as division. Things are only problematic when there are more than +one non-comment slash in a single line. + +Secondly, not every character is a valid regex flag. + +```js +var number = bar / 2/e +``` + +The above example is also correctly identified as division, because `e` is not a +valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` +(any letter) as flags, but it is not worth it since it increases the amount of +ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are +allowed. This means that the above example will be identified as division as +long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 +characters long. + +Lastly, we can look _forward_ for information. + +- If the token following what looks like a regex literal is not valid after a + regex literal, but is valid in a division expression, then the regex literal + is treated as division instead. For example, a flagless regex cannot be + followed by a string, number or name, but all of those three can be the + denominator of a division. +- Generally, if what looks like a regex literal is followed by an operator, the + regex literal is treated as division instead. This is because regexes are + seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division + could likely be part of such an expression. + +Please consult the regex source and the test cases for precise information on +when regex or division is matched (should you need to know). In short, you +could sum it up as: + +If the end of a statement looks like a regex literal (even if it isn’t), it +will be treated as one. Otherwise it should work as expected (if you write sane +code). + +### ES2018 ### + +ES2018 added some nice regex improvements to the language. + +- [Unicode property escapes] should allow telling names and invalid non-ASCII + characters apart without blowing up the regex size. +- [Lookbehind assertions] should allow matching telling division and regex + literals apart in more cases. +- [Named capture groups] might simplify some things. + +These things would be nice to do, but are not critical. They probably have to +wait until the oldest maintained Node.js LTS release supports those features. + +[Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html +[Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html +[Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html + + +License +======= + +[MIT](LICENSE). diff --git a/node_modules/js-tokens/index.js b/node_modules/js-tokens/index.js new file mode 100644 index 0000000..b23a4a0 --- /dev/null +++ b/node_modules/js-tokens/index.js @@ -0,0 +1,23 @@ +// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell +// License: MIT. (See LICENSE.) + +Object.defineProperty(exports, "__esModule", { + value: true +}) + +// This regex comes from regex.coffee, and is inserted here by generate-index.js +// (run `npm run build`). +exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g + +exports.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined} + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) + else if (match[ 5]) token.type = "comment" + else if (match[ 6]) token.type = "comment", token.closed = !!match[7] + else if (match[ 8]) token.type = "regex" + else if (match[ 9]) token.type = "number" + else if (match[10]) token.type = "name" + else if (match[11]) token.type = "punctuator" + else if (match[12]) token.type = "whitespace" + return token +} diff --git a/node_modules/js-tokens/package.json b/node_modules/js-tokens/package.json new file mode 100644 index 0000000..66752fa --- /dev/null +++ b/node_modules/js-tokens/package.json @@ -0,0 +1,30 @@ +{ + "name": "js-tokens", + "version": "4.0.0", + "author": "Simon Lydell", + "license": "MIT", + "description": "A regex that tokenizes JavaScript.", + "keywords": [ + "JavaScript", + "js", + "token", + "tokenize", + "regex" + ], + "files": [ + "index.js" + ], + "repository": "lydell/js-tokens", + "scripts": { + "test": "mocha --ui tdd", + "esprima-compare": "node esprima-compare ./index.js everything.js/es5.js", + "build": "node generate-index.js", + "dev": "npm run build && npm test" + }, + "devDependencies": { + "coffeescript": "2.1.1", + "esprima": "4.0.0", + "everything.js": "1.0.3", + "mocha": "5.0.0" + } +} diff --git a/node_modules/loose-envify/LICENSE b/node_modules/loose-envify/LICENSE new file mode 100644 index 0000000..fbafb48 --- /dev/null +++ b/node_modules/loose-envify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andres Suarez + +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. diff --git a/node_modules/loose-envify/README.md b/node_modules/loose-envify/README.md new file mode 100644 index 0000000..7f4e07b --- /dev/null +++ b/node_modules/loose-envify/README.md @@ -0,0 +1,45 @@ +# loose-envify + +[![Build Status](https://travis-ci.org/zertosh/loose-envify.svg?branch=master)](https://travis-ci.org/zertosh/loose-envify) + +Fast (and loose) selective `process.env` replacer using [js-tokens](https://github.com/lydell/js-tokens) instead of an AST. Works just like [envify](https://github.com/hughsk/envify) but much faster. + +## Gotchas + +* Doesn't handle broken syntax. +* Doesn't look inside embedded expressions in template strings. + - **this won't work:** + ```js + console.log(`the current env is ${process.env.NODE_ENV}`); + ``` +* Doesn't replace oddly-spaced or oddly-commented expressions. + - **this won't work:** + ```js + console.log(process./*won't*/env./*work*/NODE_ENV); + ``` + +## Usage/Options + +loose-envify has the exact same interface as [envify](https://github.com/hughsk/envify), including the CLI. + +## Benchmark + +``` +envify: + + $ for i in {1..5}; do node bench/bench.js 'envify'; done + 708ms + 727ms + 791ms + 719ms + 720ms + +loose-envify: + + $ for i in {1..5}; do node bench/bench.js '../'; done + 51ms + 52ms + 52ms + 52ms + 52ms +``` diff --git a/node_modules/loose-envify/cli.js b/node_modules/loose-envify/cli.js new file mode 100755 index 0000000..c0b63cb --- /dev/null +++ b/node_modules/loose-envify/cli.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node +'use strict'; + +var looseEnvify = require('./'); +var fs = require('fs'); + +if (process.argv[2]) { + fs.createReadStream(process.argv[2], {encoding: 'utf8'}) + .pipe(looseEnvify(process.argv[2])) + .pipe(process.stdout); +} else { + process.stdin.resume() + process.stdin + .pipe(looseEnvify(__filename)) + .pipe(process.stdout); +} diff --git a/node_modules/loose-envify/custom.js b/node_modules/loose-envify/custom.js new file mode 100644 index 0000000..6389bfa --- /dev/null +++ b/node_modules/loose-envify/custom.js @@ -0,0 +1,4 @@ +// envify compatibility +'use strict'; + +module.exports = require('./loose-envify'); diff --git a/node_modules/loose-envify/index.js b/node_modules/loose-envify/index.js new file mode 100644 index 0000000..8cd8305 --- /dev/null +++ b/node_modules/loose-envify/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./loose-envify')(process.env); diff --git a/node_modules/loose-envify/loose-envify.js b/node_modules/loose-envify/loose-envify.js new file mode 100644 index 0000000..b5a5be2 --- /dev/null +++ b/node_modules/loose-envify/loose-envify.js @@ -0,0 +1,36 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); +var replace = require('./replace'); + +var jsonExtRe = /\.json$/; + +module.exports = function(rootEnv) { + rootEnv = rootEnv || process.env; + return function (file, trOpts) { + if (jsonExtRe.test(file)) { + return stream.PassThrough(); + } + var envs = trOpts ? [rootEnv, trOpts] : [rootEnv]; + return new LooseEnvify(envs); + }; +}; + +function LooseEnvify(envs) { + stream.Transform.call(this); + this._data = ''; + this._envs = envs; +} +util.inherits(LooseEnvify, stream.Transform); + +LooseEnvify.prototype._transform = function(buf, enc, cb) { + this._data += buf; + cb(); +}; + +LooseEnvify.prototype._flush = function(cb) { + var replaced = replace(this._data, this._envs); + this.push(replaced); + cb(); +}; diff --git a/node_modules/loose-envify/package.json b/node_modules/loose-envify/package.json new file mode 100644 index 0000000..5e3d0e2 --- /dev/null +++ b/node_modules/loose-envify/package.json @@ -0,0 +1,36 @@ +{ + "name": "loose-envify", + "version": "1.4.0", + "description": "Fast (and loose) selective `process.env` replacer using js-tokens instead of an AST", + "keywords": [ + "environment", + "variables", + "browserify", + "browserify-transform", + "transform", + "source", + "configuration" + ], + "homepage": "https://github.com/zertosh/loose-envify", + "license": "MIT", + "author": "Andres Suarez ", + "main": "index.js", + "bin": { + "loose-envify": "cli.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/zertosh/loose-envify.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "devDependencies": { + "browserify": "^13.1.1", + "envify": "^3.4.0", + "tap": "^8.0.0" + } +} diff --git a/node_modules/loose-envify/replace.js b/node_modules/loose-envify/replace.js new file mode 100644 index 0000000..ec15e81 --- /dev/null +++ b/node_modules/loose-envify/replace.js @@ -0,0 +1,65 @@ +'use strict'; + +var jsTokens = require('js-tokens').default; + +var processEnvRe = /\bprocess\.env\.[_$a-zA-Z][$\w]+\b/; +var spaceOrCommentRe = /^(?:\s|\/[/*])/; + +function replace(src, envs) { + if (!processEnvRe.test(src)) { + return src; + } + + var out = []; + var purge = envs.some(function(env) { + return env._ && env._.indexOf('purge') !== -1; + }); + + jsTokens.lastIndex = 0 + var parts = src.match(jsTokens); + + for (var i = 0; i < parts.length; i++) { + if (parts[i ] === 'process' && + parts[i + 1] === '.' && + parts[i + 2] === 'env' && + parts[i + 3] === '.') { + var prevCodeToken = getAdjacentCodeToken(-1, parts, i); + var nextCodeToken = getAdjacentCodeToken(1, parts, i + 4); + var replacement = getReplacementString(envs, parts[i + 4], purge); + if (prevCodeToken !== '.' && + nextCodeToken !== '.' && + nextCodeToken !== '=' && + typeof replacement === 'string') { + out.push(replacement); + i += 4; + continue; + } + } + out.push(parts[i]); + } + + return out.join(''); +} + +function getAdjacentCodeToken(dir, parts, i) { + while (true) { + var part = parts[i += dir]; + if (!spaceOrCommentRe.test(part)) { + return part; + } + } +} + +function getReplacementString(envs, name, purge) { + for (var j = 0; j < envs.length; j++) { + var env = envs[j]; + if (typeof env[name] !== 'undefined') { + return JSON.stringify(env[name]); + } + } + if (purge) { + return 'undefined'; + } +} + +module.exports = replace; diff --git a/node_modules/react-dom/LICENSE b/node_modules/react-dom/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/react-dom/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +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. diff --git a/node_modules/react-dom/README.md b/node_modules/react-dom/README.md new file mode 100644 index 0000000..ecba5cf --- /dev/null +++ b/node_modules/react-dom/README.md @@ -0,0 +1,60 @@ +# `react-dom` + +This package serves as the entry point to the DOM and server renderers for React. It is intended to be paired with the generic React package, which is shipped as `react` to npm. + +## Installation + +```sh +npm install react react-dom +``` + +## Usage + +### In the browser + +```js +import { createRoot } from 'react-dom/client'; + +function App() { + return
Hello World
; +} + +const root = createRoot(document.getElementById('root')); +root.render(); +``` + +### On the server + +```js +import { renderToPipeableStream } from 'react-dom/server'; + +function App() { + return
Hello World
; +} + +function handleRequest(res) { + // ... in your server handler ... + const stream = renderToPipeableStream(, { + onShellReady() { + res.statusCode = 200; + res.setHeader('Content-type', 'text/html'); + stream.pipe(res); + }, + // ... + }); +} +``` + +## API + +### `react-dom` + +See https://reactjs.org/docs/react-dom.html + +### `react-dom/client` + +See https://reactjs.org/docs/react-dom-client.html + +### `react-dom/server` + +See https://reactjs.org/docs/react-dom-server.html diff --git a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js new file mode 100644 index 0000000..11c25e0 --- /dev/null +++ b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js @@ -0,0 +1,7018 @@ +/** + * @license React + * react-dom-server-legacy.browser.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var React = require('react'); + +var ReactVersion = '18.2.0'; + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +// by calls to these methods by a Babel plugin. +// +// In PROD (or in packages without access to React internals), +// they are left as they are instead. + +function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } + } +} +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + callback(); +} +function beginWriting(destination) {} +function writeChunk(destination, chunk) { + writeChunkAndReturn(destination, chunk); +} +function writeChunkAndReturn(destination, chunk) { + return destination.push(chunk); +} +function completeWriting(destination) {} +function close(destination) { + destination.push(null); +} +function stringToChunk(content) { + return content; +} +function stringToPrecomputedChunk(content) { + return content; +} +function closeWithError(destination, error) { + // $FlowFixMe: This is an Error object or the destination accepts other types. + destination.destroy(error); +} + +/* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ +// $FlowFixMe only called in DEV, so void return is not possible. +function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } +} // $FlowFixMe only called in DEV, so void return is not possible. + + +function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } +} + +function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; +} + +function checkAttributeStringCoercion(value, attributeName) { + { + if (willCoercionThrow(value)) { + error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} +function checkCSSPropertyStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} +function checkHtmlStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +// A reserved attribute. +// It is handled by React separately and shouldn't be written to the DOM. +var RESERVED = 0; // A simple string attribute. +// Attributes that aren't in the filter are presumed to have this type. + +var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called +// "enumerated" attributes with "true" and "false" as possible values. +// When true, it should be set to a "true" string. +// When false, it should be set to a "false" string. + +var BOOLEANISH_STRING = 2; // A real boolean attribute. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. + +var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. +// For any other value, should be present with that value. + +var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. +// When falsy, it should be removed. + +var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. +// When falsy, it should be removed. + +var POSITIVE_NUMERIC = 6; + +/* eslint-disable max-len */ +var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; +/* eslint-enable max-len */ + +var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; +var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; +function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { + return true; + } + + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { + return false; + } + + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + + illegalAttributeNameCache[attributeName] = true; + + { + error('Invalid attribute name: `%s`', attributeName); + } + + return false; +} +function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + + switch (typeof value) { + case 'function': // $FlowIssue symbol is perfectly valid here + + case 'symbol': + // eslint-disable-line + return true; + + case 'boolean': + { + if (isCustomComponentTag) { + return false; + } + + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix = name.toLowerCase().slice(0, 5); + return prefix !== 'data-' && prefix !== 'aria-'; + } + } + + default: + return false; + } +} +function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; +} + +function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL; + this.removeEmptyString = removeEmptyString; +} // When adding attributes to this list, be sure to also add them to +// the `possibleStandardNames` module to ensure casing and incorrect +// name warnings. + + +var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. + +var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular +// elements (not just inputs). Now that ReactDOMInput assigns to the +// defaultValue property -- do we need this? +'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; + +reservedProps.forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // A few React string attributes have a different name. +// This is a mapping from React prop names to the attribute names. + +[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { + var name = _ref[0], + attributeName = _ref[1]; + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are "enumerated" HTML attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). + +['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are "enumerated" SVG attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). +// Since these are SVG attributes, their attribute names are case-sensitive. + +['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML boolean attributes. + +['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM +// on the client side because the browsers are inconsistent. Instead we call focus(). +'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata +'itemScope'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are the few React props that we set as DOM properties +// rather than attributes. These are all booleans. + +['checked', // Note: `option.selected` is not updated if `select.multiple` is +// disabled with `removeAttribute`. We have special logic for handling this. +'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that are "overloaded booleans": they behave like +// booleans, but can also accept a string value. + +['capture', 'download' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that must be positive numbers. + +['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that must be numbers. + +['rowSpan', 'start'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); +var CAMELIZE = /[\-\:]([a-z])/g; + +var capitalize = function (token) { + return token[1].toUpperCase(); +}; // This is a list of all SVG attributes that need special casing, namespacing, +// or boolean value assignment. Regular attributes that just accept strings +// and have the same names are omitted, just like in the HTML attribute filter. +// Some of these attributes can be hard to find. This list was created by +// scraping the MDN documentation. + + +['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, null, // attributeNamespace + false, // sanitizeURL + false); +}); // String SVG attributes with the xlink namespace. + +['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL + false); +}); // String SVG attributes with the xml namespace. + +['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL + false); +}); // These attribute exists both in HTML and SVG. +// The attribute name is case-sensitive in SVG so we can't just use +// the React name like we do for attributes that exist only in HTML. + +['tabIndex', 'crossOrigin'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These attributes accept URLs. These must not allow javascript: URLS. +// These will also need to accept Trusted Types object in the future. + +var xlinkHref = 'xlinkHref'; +properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty +'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL +false); +['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + true, // sanitizeURL + true); +}); + +/** + * CSS properties which accept numbers but are not in units of "px". + */ +var isUnitlessNumber = { + animationIterationCount: true, + aspectRatio: true, + borderImageOutset: true, + borderImageSlice: true, + borderImageWidth: true, + boxFlex: true, + boxFlexGroup: true, + boxOrdinalGroup: true, + columnCount: true, + columns: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + flexOrder: true, + gridArea: true, + gridRow: true, + gridRowEnd: true, + gridRowSpan: true, + gridRowStart: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnSpan: true, + gridColumnStart: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + // SVG-related properties + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeDasharray: true, + strokeDashoffset: true, + strokeMiterlimit: true, + strokeOpacity: true, + strokeWidth: true +}; +/** + * @param {string} prefix vendor-specific prefix, eg: Webkit + * @param {string} key style name, eg: transitionDuration + * @return {string} style name prefixed with `prefix`, properly camelCased, eg: + * WebkitTransitionDuration + */ + +function prefixKey(prefix, key) { + return prefix + key.charAt(0).toUpperCase() + key.substring(1); +} +/** + * Support style names that may come passed in prefixed by adding permutations + * of vendor prefixes. + */ + + +var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an +// infinite loop, because it iterates over the newly added props too. + +Object.keys(isUnitlessNumber).forEach(function (prop) { + prefixes.forEach(function (prefix) { + isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; + }); +}); + +var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true +}; +function checkControlledValueProps(tagName, props) { + { + if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { + error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + + if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { + error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + } +} + +function isCustomComponent(tagName, props) { + if (tagName.indexOf('-') === -1) { + return typeof props.is === 'string'; + } + + switch (tagName) { + // These are reserved SVG and MathML elements. + // We don't mind this list too much because we expect it to never grow. + // The alternative is to track the namespace in a few places which is convoluted. + // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts + case 'annotation-xml': + case 'color-profile': + case 'font-face': + case 'font-face-src': + case 'font-face-uri': + case 'font-face-format': + case 'font-face-name': + case 'missing-glyph': + return false; + + default: + return true; + } +} + +var ariaProperties = { + 'aria-current': 0, + // state + 'aria-description': 0, + 'aria-details': 0, + 'aria-disabled': 0, + // state + 'aria-hidden': 0, + // state + 'aria-invalid': 0, + // state + 'aria-keyshortcuts': 0, + 'aria-label': 0, + 'aria-roledescription': 0, + // Widget Attributes + 'aria-autocomplete': 0, + 'aria-checked': 0, + 'aria-expanded': 0, + 'aria-haspopup': 0, + 'aria-level': 0, + 'aria-modal': 0, + 'aria-multiline': 0, + 'aria-multiselectable': 0, + 'aria-orientation': 0, + 'aria-placeholder': 0, + 'aria-pressed': 0, + 'aria-readonly': 0, + 'aria-required': 0, + 'aria-selected': 0, + 'aria-sort': 0, + 'aria-valuemax': 0, + 'aria-valuemin': 0, + 'aria-valuenow': 0, + 'aria-valuetext': 0, + // Live Region Attributes + 'aria-atomic': 0, + 'aria-busy': 0, + 'aria-live': 0, + 'aria-relevant': 0, + // Drag-and-Drop Attributes + 'aria-dropeffect': 0, + 'aria-grabbed': 0, + // Relationship Attributes + 'aria-activedescendant': 0, + 'aria-colcount': 0, + 'aria-colindex': 0, + 'aria-colspan': 0, + 'aria-controls': 0, + 'aria-describedby': 0, + 'aria-errormessage': 0, + 'aria-flowto': 0, + 'aria-labelledby': 0, + 'aria-owns': 0, + 'aria-posinset': 0, + 'aria-rowcount': 0, + 'aria-rowindex': 0, + 'aria-rowspan': 0, + 'aria-setsize': 0 +}; + +var warnedProperties = {}; +var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); +var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); + +function validateProperty(tagName, name) { + { + if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) { + return true; + } + + if (rARIACamel.test(name)) { + var ariaName = 'aria-' + name.slice(4).toLowerCase(); + var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM + // DOM properties, then it is an invalid aria-* attribute. + + if (correctName == null) { + error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name); + + warnedProperties[name] = true; + return true; + } // aria-* attributes should be lowercase; suggest the lowercase version. + + + if (name !== correctName) { + error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName); + + warnedProperties[name] = true; + return true; + } + } + + if (rARIA.test(name)) { + var lowerCasedName = name.toLowerCase(); + var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM + // DOM properties, then it is an invalid aria-* attribute. + + if (standardName == null) { + warnedProperties[name] = true; + return false; + } // aria-* attributes should be lowercase; suggest the lowercase version. + + + if (name !== standardName) { + error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName); + + warnedProperties[name] = true; + return true; + } + } + } + + return true; +} + +function warnInvalidARIAProps(type, props) { + { + var invalidProps = []; + + for (var key in props) { + var isValid = validateProperty(type, key); + + if (!isValid) { + invalidProps.push(key); + } + } + + var unknownPropString = invalidProps.map(function (prop) { + return '`' + prop + '`'; + }).join(', '); + + if (invalidProps.length === 1) { + error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); + } else if (invalidProps.length > 1) { + error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); + } + } +} + +function validateProperties(type, props) { + if (isCustomComponent(type, props)) { + return; + } + + warnInvalidARIAProps(type, props); +} + +var didWarnValueNull = false; +function validateProperties$1(type, props) { + { + if (type !== 'input' && type !== 'textarea' && type !== 'select') { + return; + } + + if (props != null && props.value === null && !didWarnValueNull) { + didWarnValueNull = true; + + if (type === 'select' && props.multiple) { + error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type); + } else { + error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type); + } + } + } +} + +// When adding attributes to the HTML or SVG allowed attribute list, be sure to +// also add them to this module to ensure casing and incorrect name +// warnings. +var possibleStandardNames = { + // HTML + accept: 'accept', + acceptcharset: 'acceptCharset', + 'accept-charset': 'acceptCharset', + accesskey: 'accessKey', + action: 'action', + allowfullscreen: 'allowFullScreen', + alt: 'alt', + as: 'as', + async: 'async', + autocapitalize: 'autoCapitalize', + autocomplete: 'autoComplete', + autocorrect: 'autoCorrect', + autofocus: 'autoFocus', + autoplay: 'autoPlay', + autosave: 'autoSave', + capture: 'capture', + cellpadding: 'cellPadding', + cellspacing: 'cellSpacing', + challenge: 'challenge', + charset: 'charSet', + checked: 'checked', + children: 'children', + cite: 'cite', + class: 'className', + classid: 'classID', + classname: 'className', + cols: 'cols', + colspan: 'colSpan', + content: 'content', + contenteditable: 'contentEditable', + contextmenu: 'contextMenu', + controls: 'controls', + controlslist: 'controlsList', + coords: 'coords', + crossorigin: 'crossOrigin', + dangerouslysetinnerhtml: 'dangerouslySetInnerHTML', + data: 'data', + datetime: 'dateTime', + default: 'default', + defaultchecked: 'defaultChecked', + defaultvalue: 'defaultValue', + defer: 'defer', + dir: 'dir', + disabled: 'disabled', + disablepictureinpicture: 'disablePictureInPicture', + disableremoteplayback: 'disableRemotePlayback', + download: 'download', + draggable: 'draggable', + enctype: 'encType', + enterkeyhint: 'enterKeyHint', + for: 'htmlFor', + form: 'form', + formmethod: 'formMethod', + formaction: 'formAction', + formenctype: 'formEncType', + formnovalidate: 'formNoValidate', + formtarget: 'formTarget', + frameborder: 'frameBorder', + headers: 'headers', + height: 'height', + hidden: 'hidden', + high: 'high', + href: 'href', + hreflang: 'hrefLang', + htmlfor: 'htmlFor', + httpequiv: 'httpEquiv', + 'http-equiv': 'httpEquiv', + icon: 'icon', + id: 'id', + imagesizes: 'imageSizes', + imagesrcset: 'imageSrcSet', + innerhtml: 'innerHTML', + inputmode: 'inputMode', + integrity: 'integrity', + is: 'is', + itemid: 'itemID', + itemprop: 'itemProp', + itemref: 'itemRef', + itemscope: 'itemScope', + itemtype: 'itemType', + keyparams: 'keyParams', + keytype: 'keyType', + kind: 'kind', + label: 'label', + lang: 'lang', + list: 'list', + loop: 'loop', + low: 'low', + manifest: 'manifest', + marginwidth: 'marginWidth', + marginheight: 'marginHeight', + max: 'max', + maxlength: 'maxLength', + media: 'media', + mediagroup: 'mediaGroup', + method: 'method', + min: 'min', + minlength: 'minLength', + multiple: 'multiple', + muted: 'muted', + name: 'name', + nomodule: 'noModule', + nonce: 'nonce', + novalidate: 'noValidate', + open: 'open', + optimum: 'optimum', + pattern: 'pattern', + placeholder: 'placeholder', + playsinline: 'playsInline', + poster: 'poster', + preload: 'preload', + profile: 'profile', + radiogroup: 'radioGroup', + readonly: 'readOnly', + referrerpolicy: 'referrerPolicy', + rel: 'rel', + required: 'required', + reversed: 'reversed', + role: 'role', + rows: 'rows', + rowspan: 'rowSpan', + sandbox: 'sandbox', + scope: 'scope', + scoped: 'scoped', + scrolling: 'scrolling', + seamless: 'seamless', + selected: 'selected', + shape: 'shape', + size: 'size', + sizes: 'sizes', + span: 'span', + spellcheck: 'spellCheck', + src: 'src', + srcdoc: 'srcDoc', + srclang: 'srcLang', + srcset: 'srcSet', + start: 'start', + step: 'step', + style: 'style', + summary: 'summary', + tabindex: 'tabIndex', + target: 'target', + title: 'title', + type: 'type', + usemap: 'useMap', + value: 'value', + width: 'width', + wmode: 'wmode', + wrap: 'wrap', + // SVG + about: 'about', + accentheight: 'accentHeight', + 'accent-height': 'accentHeight', + accumulate: 'accumulate', + additive: 'additive', + alignmentbaseline: 'alignmentBaseline', + 'alignment-baseline': 'alignmentBaseline', + allowreorder: 'allowReorder', + alphabetic: 'alphabetic', + amplitude: 'amplitude', + arabicform: 'arabicForm', + 'arabic-form': 'arabicForm', + ascent: 'ascent', + attributename: 'attributeName', + attributetype: 'attributeType', + autoreverse: 'autoReverse', + azimuth: 'azimuth', + basefrequency: 'baseFrequency', + baselineshift: 'baselineShift', + 'baseline-shift': 'baselineShift', + baseprofile: 'baseProfile', + bbox: 'bbox', + begin: 'begin', + bias: 'bias', + by: 'by', + calcmode: 'calcMode', + capheight: 'capHeight', + 'cap-height': 'capHeight', + clip: 'clip', + clippath: 'clipPath', + 'clip-path': 'clipPath', + clippathunits: 'clipPathUnits', + cliprule: 'clipRule', + 'clip-rule': 'clipRule', + color: 'color', + colorinterpolation: 'colorInterpolation', + 'color-interpolation': 'colorInterpolation', + colorinterpolationfilters: 'colorInterpolationFilters', + 'color-interpolation-filters': 'colorInterpolationFilters', + colorprofile: 'colorProfile', + 'color-profile': 'colorProfile', + colorrendering: 'colorRendering', + 'color-rendering': 'colorRendering', + contentscripttype: 'contentScriptType', + contentstyletype: 'contentStyleType', + cursor: 'cursor', + cx: 'cx', + cy: 'cy', + d: 'd', + datatype: 'datatype', + decelerate: 'decelerate', + descent: 'descent', + diffuseconstant: 'diffuseConstant', + direction: 'direction', + display: 'display', + divisor: 'divisor', + dominantbaseline: 'dominantBaseline', + 'dominant-baseline': 'dominantBaseline', + dur: 'dur', + dx: 'dx', + dy: 'dy', + edgemode: 'edgeMode', + elevation: 'elevation', + enablebackground: 'enableBackground', + 'enable-background': 'enableBackground', + end: 'end', + exponent: 'exponent', + externalresourcesrequired: 'externalResourcesRequired', + fill: 'fill', + fillopacity: 'fillOpacity', + 'fill-opacity': 'fillOpacity', + fillrule: 'fillRule', + 'fill-rule': 'fillRule', + filter: 'filter', + filterres: 'filterRes', + filterunits: 'filterUnits', + floodopacity: 'floodOpacity', + 'flood-opacity': 'floodOpacity', + floodcolor: 'floodColor', + 'flood-color': 'floodColor', + focusable: 'focusable', + fontfamily: 'fontFamily', + 'font-family': 'fontFamily', + fontsize: 'fontSize', + 'font-size': 'fontSize', + fontsizeadjust: 'fontSizeAdjust', + 'font-size-adjust': 'fontSizeAdjust', + fontstretch: 'fontStretch', + 'font-stretch': 'fontStretch', + fontstyle: 'fontStyle', + 'font-style': 'fontStyle', + fontvariant: 'fontVariant', + 'font-variant': 'fontVariant', + fontweight: 'fontWeight', + 'font-weight': 'fontWeight', + format: 'format', + from: 'from', + fx: 'fx', + fy: 'fy', + g1: 'g1', + g2: 'g2', + glyphname: 'glyphName', + 'glyph-name': 'glyphName', + glyphorientationhorizontal: 'glyphOrientationHorizontal', + 'glyph-orientation-horizontal': 'glyphOrientationHorizontal', + glyphorientationvertical: 'glyphOrientationVertical', + 'glyph-orientation-vertical': 'glyphOrientationVertical', + glyphref: 'glyphRef', + gradienttransform: 'gradientTransform', + gradientunits: 'gradientUnits', + hanging: 'hanging', + horizadvx: 'horizAdvX', + 'horiz-adv-x': 'horizAdvX', + horizoriginx: 'horizOriginX', + 'horiz-origin-x': 'horizOriginX', + ideographic: 'ideographic', + imagerendering: 'imageRendering', + 'image-rendering': 'imageRendering', + in2: 'in2', + in: 'in', + inlist: 'inlist', + intercept: 'intercept', + k1: 'k1', + k2: 'k2', + k3: 'k3', + k4: 'k4', + k: 'k', + kernelmatrix: 'kernelMatrix', + kernelunitlength: 'kernelUnitLength', + kerning: 'kerning', + keypoints: 'keyPoints', + keysplines: 'keySplines', + keytimes: 'keyTimes', + lengthadjust: 'lengthAdjust', + letterspacing: 'letterSpacing', + 'letter-spacing': 'letterSpacing', + lightingcolor: 'lightingColor', + 'lighting-color': 'lightingColor', + limitingconeangle: 'limitingConeAngle', + local: 'local', + markerend: 'markerEnd', + 'marker-end': 'markerEnd', + markerheight: 'markerHeight', + markermid: 'markerMid', + 'marker-mid': 'markerMid', + markerstart: 'markerStart', + 'marker-start': 'markerStart', + markerunits: 'markerUnits', + markerwidth: 'markerWidth', + mask: 'mask', + maskcontentunits: 'maskContentUnits', + maskunits: 'maskUnits', + mathematical: 'mathematical', + mode: 'mode', + numoctaves: 'numOctaves', + offset: 'offset', + opacity: 'opacity', + operator: 'operator', + order: 'order', + orient: 'orient', + orientation: 'orientation', + origin: 'origin', + overflow: 'overflow', + overlineposition: 'overlinePosition', + 'overline-position': 'overlinePosition', + overlinethickness: 'overlineThickness', + 'overline-thickness': 'overlineThickness', + paintorder: 'paintOrder', + 'paint-order': 'paintOrder', + panose1: 'panose1', + 'panose-1': 'panose1', + pathlength: 'pathLength', + patterncontentunits: 'patternContentUnits', + patterntransform: 'patternTransform', + patternunits: 'patternUnits', + pointerevents: 'pointerEvents', + 'pointer-events': 'pointerEvents', + points: 'points', + pointsatx: 'pointsAtX', + pointsaty: 'pointsAtY', + pointsatz: 'pointsAtZ', + prefix: 'prefix', + preservealpha: 'preserveAlpha', + preserveaspectratio: 'preserveAspectRatio', + primitiveunits: 'primitiveUnits', + property: 'property', + r: 'r', + radius: 'radius', + refx: 'refX', + refy: 'refY', + renderingintent: 'renderingIntent', + 'rendering-intent': 'renderingIntent', + repeatcount: 'repeatCount', + repeatdur: 'repeatDur', + requiredextensions: 'requiredExtensions', + requiredfeatures: 'requiredFeatures', + resource: 'resource', + restart: 'restart', + result: 'result', + results: 'results', + rotate: 'rotate', + rx: 'rx', + ry: 'ry', + scale: 'scale', + security: 'security', + seed: 'seed', + shaperendering: 'shapeRendering', + 'shape-rendering': 'shapeRendering', + slope: 'slope', + spacing: 'spacing', + specularconstant: 'specularConstant', + specularexponent: 'specularExponent', + speed: 'speed', + spreadmethod: 'spreadMethod', + startoffset: 'startOffset', + stddeviation: 'stdDeviation', + stemh: 'stemh', + stemv: 'stemv', + stitchtiles: 'stitchTiles', + stopcolor: 'stopColor', + 'stop-color': 'stopColor', + stopopacity: 'stopOpacity', + 'stop-opacity': 'stopOpacity', + strikethroughposition: 'strikethroughPosition', + 'strikethrough-position': 'strikethroughPosition', + strikethroughthickness: 'strikethroughThickness', + 'strikethrough-thickness': 'strikethroughThickness', + string: 'string', + stroke: 'stroke', + strokedasharray: 'strokeDasharray', + 'stroke-dasharray': 'strokeDasharray', + strokedashoffset: 'strokeDashoffset', + 'stroke-dashoffset': 'strokeDashoffset', + strokelinecap: 'strokeLinecap', + 'stroke-linecap': 'strokeLinecap', + strokelinejoin: 'strokeLinejoin', + 'stroke-linejoin': 'strokeLinejoin', + strokemiterlimit: 'strokeMiterlimit', + 'stroke-miterlimit': 'strokeMiterlimit', + strokewidth: 'strokeWidth', + 'stroke-width': 'strokeWidth', + strokeopacity: 'strokeOpacity', + 'stroke-opacity': 'strokeOpacity', + suppresscontenteditablewarning: 'suppressContentEditableWarning', + suppresshydrationwarning: 'suppressHydrationWarning', + surfacescale: 'surfaceScale', + systemlanguage: 'systemLanguage', + tablevalues: 'tableValues', + targetx: 'targetX', + targety: 'targetY', + textanchor: 'textAnchor', + 'text-anchor': 'textAnchor', + textdecoration: 'textDecoration', + 'text-decoration': 'textDecoration', + textlength: 'textLength', + textrendering: 'textRendering', + 'text-rendering': 'textRendering', + to: 'to', + transform: 'transform', + typeof: 'typeof', + u1: 'u1', + u2: 'u2', + underlineposition: 'underlinePosition', + 'underline-position': 'underlinePosition', + underlinethickness: 'underlineThickness', + 'underline-thickness': 'underlineThickness', + unicode: 'unicode', + unicodebidi: 'unicodeBidi', + 'unicode-bidi': 'unicodeBidi', + unicoderange: 'unicodeRange', + 'unicode-range': 'unicodeRange', + unitsperem: 'unitsPerEm', + 'units-per-em': 'unitsPerEm', + unselectable: 'unselectable', + valphabetic: 'vAlphabetic', + 'v-alphabetic': 'vAlphabetic', + values: 'values', + vectoreffect: 'vectorEffect', + 'vector-effect': 'vectorEffect', + version: 'version', + vertadvy: 'vertAdvY', + 'vert-adv-y': 'vertAdvY', + vertoriginx: 'vertOriginX', + 'vert-origin-x': 'vertOriginX', + vertoriginy: 'vertOriginY', + 'vert-origin-y': 'vertOriginY', + vhanging: 'vHanging', + 'v-hanging': 'vHanging', + videographic: 'vIdeographic', + 'v-ideographic': 'vIdeographic', + viewbox: 'viewBox', + viewtarget: 'viewTarget', + visibility: 'visibility', + vmathematical: 'vMathematical', + 'v-mathematical': 'vMathematical', + vocab: 'vocab', + widths: 'widths', + wordspacing: 'wordSpacing', + 'word-spacing': 'wordSpacing', + writingmode: 'writingMode', + 'writing-mode': 'writingMode', + x1: 'x1', + x2: 'x2', + x: 'x', + xchannelselector: 'xChannelSelector', + xheight: 'xHeight', + 'x-height': 'xHeight', + xlinkactuate: 'xlinkActuate', + 'xlink:actuate': 'xlinkActuate', + xlinkarcrole: 'xlinkArcrole', + 'xlink:arcrole': 'xlinkArcrole', + xlinkhref: 'xlinkHref', + 'xlink:href': 'xlinkHref', + xlinkrole: 'xlinkRole', + 'xlink:role': 'xlinkRole', + xlinkshow: 'xlinkShow', + 'xlink:show': 'xlinkShow', + xlinktitle: 'xlinkTitle', + 'xlink:title': 'xlinkTitle', + xlinktype: 'xlinkType', + 'xlink:type': 'xlinkType', + xmlbase: 'xmlBase', + 'xml:base': 'xmlBase', + xmllang: 'xmlLang', + 'xml:lang': 'xmlLang', + xmlns: 'xmlns', + 'xml:space': 'xmlSpace', + xmlnsxlink: 'xmlnsXlink', + 'xmlns:xlink': 'xmlnsXlink', + xmlspace: 'xmlSpace', + y1: 'y1', + y2: 'y2', + y: 'y', + ychannelselector: 'yChannelSelector', + z: 'z', + zoomandpan: 'zoomAndPan' +}; + +var validateProperty$1 = function () {}; + +{ + var warnedProperties$1 = {}; + var EVENT_NAME_REGEX = /^on./; + var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; + var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); + var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); + + validateProperty$1 = function (tagName, name, value, eventRegistry) { + if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { + return true; + } + + var lowerCasedName = name.toLowerCase(); + + if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') { + error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); + + warnedProperties$1[name] = true; + return true; + } // We can't rely on the event system being injected on the server. + + + if (eventRegistry != null) { + var registrationNameDependencies = eventRegistry.registrationNameDependencies, + possibleRegistrationNames = eventRegistry.possibleRegistrationNames; + + if (registrationNameDependencies.hasOwnProperty(name)) { + return true; + } + + var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null; + + if (registrationName != null) { + error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName); + + warnedProperties$1[name] = true; + return true; + } + + if (EVENT_NAME_REGEX.test(name)) { + error('Unknown event handler property `%s`. It will be ignored.', name); + + warnedProperties$1[name] = true; + return true; + } + } else if (EVENT_NAME_REGEX.test(name)) { + // If no event plugins have been injected, we are in a server environment. + // So we can't tell if the event name is correct for sure, but we can filter + // out known bad ones like `onclick`. We can't suggest a specific replacement though. + if (INVALID_EVENT_NAME_REGEX.test(name)) { + error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name); + } + + warnedProperties$1[name] = true; + return true; + } // Let the ARIA attribute hook validate ARIA attributes + + + if (rARIA$1.test(name) || rARIACamel$1.test(name)) { + return true; + } + + if (lowerCasedName === 'innerhtml') { + error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); + + warnedProperties$1[name] = true; + return true; + } + + if (lowerCasedName === 'aria') { + error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.'); + + warnedProperties$1[name] = true; + return true; + } + + if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') { + error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value); + + warnedProperties$1[name] = true; + return true; + } + + if (typeof value === 'number' && isNaN(value)) { + error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name); + + warnedProperties$1[name] = true; + return true; + } + + var propertyInfo = getPropertyInfo(name); + var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config. + + if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { + var standardName = possibleStandardNames[lowerCasedName]; + + if (standardName !== name) { + error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName); + + warnedProperties$1[name] = true; + return true; + } + } else if (!isReserved && name !== lowerCasedName) { + // Unknown attributes should have lowercase casing since that's how they + // will be cased anyway with server rendering. + error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName); + + warnedProperties$1[name] = true; + return true; + } + + if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + if (value) { + error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name); + } else { + error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); + } + + warnedProperties$1[name] = true; + return true; + } // Now that we've validated casing, do not validate + // data types for reserved props + + + if (isReserved) { + return true; + } // Warn when a known attribute is a bad type + + + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + warnedProperties$1[name] = true; + return false; + } // Warn when passing the strings 'false' or 'true' into a boolean prop + + + if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) { + error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value); + + warnedProperties$1[name] = true; + return true; + } + + return true; + }; +} + +var warnUnknownProperties = function (type, props, eventRegistry) { + { + var unknownProps = []; + + for (var key in props) { + var isValid = validateProperty$1(type, key, props[key], eventRegistry); + + if (!isValid) { + unknownProps.push(key); + } + } + + var unknownPropString = unknownProps.map(function (prop) { + return '`' + prop + '`'; + }).join(', '); + + if (unknownProps.length === 1) { + error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); + } else if (unknownProps.length > 1) { + error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); + } + } +}; + +function validateProperties$2(type, props, eventRegistry) { + if (isCustomComponent(type, props)) { + return; + } + + warnUnknownProperties(type, props, eventRegistry); +} + +var warnValidStyle = function () {}; + +{ + // 'msTransform' is correct, but the other prefixes should be capitalized + var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; + var msPattern = /^-ms-/; + var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon + + var badStyleValueWithSemicolonPattern = /;\s*$/; + var warnedStyleNames = {}; + var warnedStyleValues = {}; + var warnedForNaNValue = false; + var warnedForInfinityValue = false; + + var camelize = function (string) { + return string.replace(hyphenPattern, function (_, character) { + return character.toUpperCase(); + }); + }; + + var warnHyphenatedStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + + error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests + // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix + // is converted to lowercase `ms`. + camelize(name.replace(msPattern, 'ms-'))); + }; + + var warnBadVendoredStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + + error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)); + }; + + var warnStyleValueWithSemicolon = function (name, value) { + if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { + return; + } + + warnedStyleValues[value] = true; + + error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')); + }; + + var warnStyleValueIsNaN = function (name, value) { + if (warnedForNaNValue) { + return; + } + + warnedForNaNValue = true; + + error('`NaN` is an invalid value for the `%s` css style property.', name); + }; + + var warnStyleValueIsInfinity = function (name, value) { + if (warnedForInfinityValue) { + return; + } + + warnedForInfinityValue = true; + + error('`Infinity` is an invalid value for the `%s` css style property.', name); + }; + + warnValidStyle = function (name, value) { + if (name.indexOf('-') > -1) { + warnHyphenatedStyleName(name); + } else if (badVendoredStyleNamePattern.test(name)) { + warnBadVendoredStyleName(name); + } else if (badStyleValueWithSemicolonPattern.test(value)) { + warnStyleValueWithSemicolon(name, value); + } + + if (typeof value === 'number') { + if (isNaN(value)) { + warnStyleValueIsNaN(name, value); + } else if (!isFinite(value)) { + warnStyleValueIsInfinity(name, value); + } + } + }; +} + +var warnValidStyle$1 = warnValidStyle; + +// code copied and modified from escape-html +var matchHtmlRegExp = /["'&<>]/; +/** + * Escapes special characters and HTML entities in a given html string. + * + * @param {string} string HTML string to escape for later insertion + * @return {string} + * @public + */ + +function escapeHtml(string) { + { + checkHtmlStringCoercion(string); + } + + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: + // " + escape = '"'; + break; + + case 38: + // & + escape = '&'; + break; + + case 39: + // ' + escape = '''; // modified from escape-html; used to be ''' + + break; + + case 60: + // < + escape = '<'; + break; + + case 62: + // > + escape = '>'; + break; + + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index ? html + str.substring(lastIndex, index) : html; +} // end code copied and modified from escape-html + +/** + * Escapes text to prevent scripting attacks. + * + * @param {*} text Text value to escape. + * @return {string} An escaped string. + */ + + +function escapeTextForBrowser(text) { + if (typeof text === 'boolean' || typeof text === 'number') { + // this shortcircuit helps perf for types that we know will never have + // special characters, especially given that this function is used often + // for numeric dom ids. + return '' + text; + } + + return escapeHtml(text); +} + +var uppercasePattern = /([A-Z])/g; +var msPattern$1 = /^ms-/; +/** + * Hyphenates a camelcased CSS property name, for example: + * + * > hyphenateStyleName('backgroundColor') + * < "background-color" + * > hyphenateStyleName('MozTransition') + * < "-moz-transition" + * > hyphenateStyleName('msTransition') + * < "-ms-transition" + * + * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix + * is converted to `-ms-`. + */ + +function hyphenateStyleName(name) { + return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-'); +} + +// and any newline or tab are filtered out as if they're not part of the URL. +// https://url.spec.whatwg.org/#url-parsing +// Tab or newline are defined as \r\n\t: +// https://infra.spec.whatwg.org/#ascii-tab-or-newline +// A C0 control is a code point in the range \u0000 NULL to \u001F +// INFORMATION SEPARATOR ONE, inclusive: +// https://infra.spec.whatwg.org/#c0-control-or-space + +/* eslint-disable max-len */ + +var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; +var didWarn = false; + +function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + + error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); + } + } +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +var startInlineScript = stringToPrecomputedChunk(''); +var startScriptSrc = stringToPrecomputedChunk(''); +/** + * This escaping function is designed to work with bootstrapScriptContent only. + * because we know we are escaping the entire script. We can avoid for instance + * escaping html comment string sequences that are valid javascript as well because + * if there are no sebsequent '); +function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) { + writeChunk(destination, responseState.startInlineScript); + + if (!responseState.sentCompleteSegmentFunction) { + // The first time we write this, we'll need to include the full implementation. + responseState.sentCompleteSegmentFunction = true; + writeChunk(destination, completeSegmentScript1Full); + } else { + // Future calls can just reuse the same function. + writeChunk(destination, completeSegmentScript1Partial); + } + + writeChunk(destination, responseState.segmentPrefix); + var formattedID = stringToChunk(contentSegmentID.toString(16)); + writeChunk(destination, formattedID); + writeChunk(destination, completeSegmentScript2); + writeChunk(destination, responseState.placeholderPrefix); + writeChunk(destination, formattedID); + return writeChunkAndReturn(destination, completeSegmentScript3); +} +var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("'); +var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("'); +var completeBoundaryScript2 = stringToPrecomputedChunk('","'); +var completeBoundaryScript3 = stringToPrecomputedChunk('")'); +function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) { + writeChunk(destination, responseState.startInlineScript); + + if (!responseState.sentCompleteBoundaryFunction) { + // The first time we write this, we'll need to include the full implementation. + responseState.sentCompleteBoundaryFunction = true; + writeChunk(destination, completeBoundaryScript1Full); + } else { + // Future calls can just reuse the same function. + writeChunk(destination, completeBoundaryScript1Partial); + } + + if (boundaryID === null) { + throw new Error('An ID must have been assigned before we can complete the boundary.'); + } + + var formattedContentID = stringToChunk(contentSegmentID.toString(16)); + writeChunk(destination, boundaryID); + writeChunk(destination, completeBoundaryScript2); + writeChunk(destination, responseState.segmentPrefix); + writeChunk(destination, formattedContentID); + return writeChunkAndReturn(destination, completeBoundaryScript3); +} +var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("'); +var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("'); +var clientRenderScript1A = stringToPrecomputedChunk('"'); +var clientRenderScript2 = stringToPrecomputedChunk(')'); +var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(','); +function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) { + writeChunk(destination, responseState.startInlineScript); + + if (!responseState.sentClientRenderFunction) { + // The first time we write this, we'll need to include the full implementation. + responseState.sentClientRenderFunction = true; + writeChunk(destination, clientRenderScript1Full); + } else { + // Future calls can just reuse the same function. + writeChunk(destination, clientRenderScript1Partial); + } + + if (boundaryID === null) { + throw new Error('An ID must have been assigned before we can complete the boundary.'); + } + + writeChunk(destination, boundaryID); + writeChunk(destination, clientRenderScript1A); + + if (errorDigest || errorMessage || errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || ''))); + } + + if (errorMessage || errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || ''))); + } + + if (errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack))); + } + + return writeChunkAndReturn(destination, clientRenderScript2); +} +var regexForJSStringsInScripts = /[<\u2028\u2029]/g; + +function escapeJSStringsForInstructionScripts(input) { + var escaped = JSON.stringify(input); + return escaped.replace(regexForJSStringsInScripts, function (match) { + switch (match) { + // santizing breaking out of strings and script tags + case '<': + return "\\u003c"; + + case "\u2028": + return "\\u2028"; + + case "\u2029": + return "\\u2029"; + + default: + { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React'); + } + } + }); +} + +function createResponseState$1(generateStaticMarkup, identifierPrefix) { + var responseState = createResponseState(identifierPrefix, undefined); + return { + // Keep this in sync with ReactDOMServerFormatConfig + bootstrapChunks: responseState.bootstrapChunks, + startInlineScript: responseState.startInlineScript, + placeholderPrefix: responseState.placeholderPrefix, + segmentPrefix: responseState.segmentPrefix, + boundaryPrefix: responseState.boundaryPrefix, + idPrefix: responseState.idPrefix, + nextSuspenseID: responseState.nextSuspenseID, + sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction, + sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction, + sentClientRenderFunction: responseState.sentClientRenderFunction, + // This is an extra field for the legacy renderer + generateStaticMarkup: generateStaticMarkup + }; +} +function createRootFormatContext() { + return { + insertionMode: HTML_MODE, + // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode. + selectedValue: null + }; +} +function pushTextInstance$1(target, text, responseState, textEmbedded) { + if (responseState.generateStaticMarkup) { + target.push(stringToChunk(escapeTextForBrowser(text))); + return false; + } else { + return pushTextInstance(target, text, responseState, textEmbedded); + } +} +function pushSegmentFinale$1(target, responseState, lastPushedText, textEmbedded) { + if (responseState.generateStaticMarkup) { + return; + } else { + return pushSegmentFinale(target, responseState, lastPushedText, textEmbedded); + } +} +function writeStartCompletedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + // A completed boundary is done and doesn't need a representation in the HTML + // if we're not going to be hydrating it. + return true; + } + + return writeStartCompletedSuspenseBoundary(destination); +} +function writeStartClientRenderedSuspenseBoundary$1(destination, responseState, // flushing these error arguments are not currently supported in this legacy streaming format. +errorDigest, errorMessage, errorComponentStack) { + if (responseState.generateStaticMarkup) { + // A client rendered boundary is done and doesn't need a representation in the HTML + // since we'll never hydrate it. This is arguably an error in static generation. + return true; + } + + return writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMessage, errorComponentStack); +} +function writeEndCompletedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + return true; + } + + return writeEndCompletedSuspenseBoundary(destination); +} +function writeEndClientRenderedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + return true; + } + + return writeEndClientRenderedSuspenseBoundary(destination); +} + +var assign = Object.assign; + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PORTAL_TYPE = Symbol.for('react.portal'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); +var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_CONTEXT_TYPE = Symbol.for('react.context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SCOPE_TYPE = Symbol.for('react.scope'); +var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); +var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + + if (displayName) { + return displayName; + } + + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; +} // Keep in sync with react-reconciler/getComponentNameFromFiber + + +function getContextName(type) { + return type.displayName || 'Context'; +} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + +function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + + if (outerName !== null) { + return outerName; + } + + return getComponentNameFromType(type.type) || 'Memo'; + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + + return null; +} + +// Helpers to patch console.logs to avoid logging during side-effect free +// replaying on render function. This currently only patches the object +// lazily which won't cover if the log function was extracted eagerly. +// We could also eagerly patch the method. +var disabledDepth = 0; +var prevLog; +var prevInfo; +var prevWarn; +var prevError; +var prevGroup; +var prevGroupCollapsed; +var prevGroupEnd; + +function disabledLog() {} + +disabledLog.__reactDisabledLog = true; +function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } +} +function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } +} + +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var prefix; +function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } +} +var reentry = false; +var componentFrameCache; + +{ + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); +} + +function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; +} + +function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } +} +function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } +} + +function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); +} + +function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; +} + +var loggedTypeFailures = {}; +var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + +function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } +} + +function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + + setCurrentlyValidatingElement(null); + } + + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + + error('Failed %s type: %s', location, error$1.message); + + setCurrentlyValidatingElement(null); + } + } + } + } +} + +var warnedAboutMissingGetChildContext; + +{ + warnedAboutMissingGetChildContext = {}; +} + +var emptyContextObject = {}; + +{ + Object.freeze(emptyContextObject); +} + +function getMaskedContext(type, unmaskedContext) { + { + var contextTypes = type.contextTypes; + + if (!contextTypes) { + return emptyContextObject; + } + + var context = {}; + + for (var key in contextTypes) { + context[key] = unmaskedContext[key]; + } + + { + var name = getComponentNameFromType(type) || 'Unknown'; + checkPropTypes(contextTypes, context, 'context', name); + } + + return context; + } +} +function processChildContext(instance, type, parentContext, childContextTypes) { + { + // TODO (bvaughn) Replace this behavior with an invariant() in the future. + // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== 'function') { + { + var componentName = getComponentNameFromType(type) || 'Unknown'; + + if (!warnedAboutMissingGetChildContext[componentName]) { + warnedAboutMissingGetChildContext[componentName] = true; + + error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); + } + } + + return parentContext; + } + + var childContext = instance.getChildContext(); + + for (var contextKey in childContext) { + if (!(contextKey in childContextTypes)) { + throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); + } + } + + { + var name = getComponentNameFromType(type) || 'Unknown'; + checkPropTypes(childContextTypes, childContext, 'child context', name); + } + + return assign({}, parentContext, childContext); + } +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue2 = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue2 = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); + } // On the way back, we push the new ones that weren't common. + + + pushNode(next); + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue2; + context._currentValue2 = nextValue; + + { + if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer2 = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider(context) { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + if (prevSnapshot.context !== context) { + error('The parent context is not the expected context. This is probably a bug in React.'); + } + } + + { + var _value = prevSnapshot.parentValue; + + if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue2 = _value; + } + + { + if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer2 = rendererSigil; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext(context) { + var value = context._currentValue2; + return value; +} + +/** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ +function get(key) { + return key._reactInternals; +} +function set(key, value) { + key._reactInternals = value; +} + +var didWarnAboutNoopUpdateForComponent = {}; +var didWarnAboutDeprecatedWillMount = {}; +var didWarnAboutUninitializedState; +var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; +var didWarnAboutLegacyLifecyclesAndDerivedState; +var didWarnAboutUndefinedDerivedState; +var warnOnUndefinedDerivedState; +var warnOnInvalidCallback; +var didWarnAboutDirectlyAssigningPropsToState; +var didWarnAboutContextTypeAndContextTypes; +var didWarnAboutInvalidateContextType; + +{ + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutContextTypeAndContextTypes = new Set(); + didWarnAboutInvalidateContextType = new Set(); + var didWarnOnInvalidCallback = new Set(); + + warnOnInvalidCallback = function (callback, callerName) { + if (callback === null || typeof callback === 'function') { + return; + } + + var key = callerName + '_' + callback; + + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); + + error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); + } + }; + + warnOnUndefinedDerivedState = function (type, partialState) { + if (partialState === undefined) { + var componentName = getComponentNameFromType(type) || 'Component'; + + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); + + error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); + } + } + }; +} + +function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass'; + var warningKey = componentName + '.' + callerName; + + if (didWarnAboutNoopUpdateForComponent[warningKey]) { + return; + } + + error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName); + + didWarnAboutNoopUpdateForComponent[warningKey] = true; + } +} + +var classComponentUpdater = { + isMounted: function (inst) { + return false; + }, + enqueueSetState: function (inst, payload, callback) { + var internals = get(inst); + + if (internals.queue === null) { + warnNoop(inst, 'setState'); + } else { + internals.queue.push(payload); + + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + } + }, + enqueueReplaceState: function (inst, payload, callback) { + var internals = get(inst); + internals.replace = true; + internals.queue = [payload]; + + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + }, + enqueueForceUpdate: function (inst, callback) { + var internals = get(inst); + + if (internals.queue === null) { + warnNoop(inst, 'forceUpdate'); + } else { + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + } + } +}; + +function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) { + var partialState = getDerivedStateFromProps(nextProps, prevState); + + { + warnOnUndefinedDerivedState(ctor, partialState); + } // Merge the partial state and the previous state. + + + var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); + return newState; +} + +function constructClassInstance(ctor, props, maskedLegacyContext) { + var context = emptyContextObject; + var contextType = ctor.contextType; + + { + if ('contextType' in ctor) { + var isValid = // Allow null for conditional declaration + contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a + + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ''; + + if (contextType === undefined) { + addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; + } else if (typeof contextType !== 'object') { + addendum = ' However, it is set to a ' + typeof contextType + '.'; + } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { + addendum = ' Did you accidentally pass the Context.Provider instead?'; + } else if (contextType._context !== undefined) { + // + addendum = ' Did you accidentally pass the Context.Consumer instead?'; + } else { + addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; + } + + error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); + } + } + } + + if (typeof contextType === 'object' && contextType !== null) { + context = readContext(contextType); + } else { + context = maskedLegacyContext; + } + + var instance = new ctor(props, context); + + { + if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) { + var componentName = getComponentNameFromType(ctor) || 'Component'; + + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); + + error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); + } + } // If new component APIs are defined, "unsafe" lifecycles won't be called. + // Warn about these lifecycles if they are present. + // Don't warn about react-lifecycles-compat polyfilled methods though. + + + if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; + + if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { + foundWillMountName = 'componentWillMount'; + } else if (typeof instance.UNSAFE_componentWillMount === 'function') { + foundWillMountName = 'UNSAFE_componentWillMount'; + } + + if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + foundWillReceivePropsName = 'componentWillReceiveProps'; + } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; + } + + if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + foundWillUpdateName = 'componentWillUpdate'; + } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { + foundWillUpdateName = 'UNSAFE_componentWillUpdate'; + } + + if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { + var _componentName = getComponentNameFromType(ctor) || 'Component'; + + var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; + + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + + error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); + } + } + } + } + + return instance; +} + +function checkClassInstance(instance, ctor, newProps) { + { + var name = getComponentNameFromType(ctor) || 'Component'; + var renderPresent = instance.render; + + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === 'function') { + error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); + } else { + error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); + } + } + + if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { + error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); + } + + if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { + error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); + } + + if (instance.propTypes) { + error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); + } + + if (instance.contextType) { + error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); + } + + { + if (instance.contextTypes) { + error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); + } + + if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { + didWarnAboutContextTypeAndContextTypes.add(ctor); + + error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); + } + } + + if (typeof instance.componentShouldUpdate === 'function') { + error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); + } + + if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { + error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); + } + + if (typeof instance.componentDidUnmount === 'function') { + error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); + } + + if (typeof instance.componentDidReceiveProps === 'function') { + error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); + } + + if (typeof instance.componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); + } + + if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); + } + + var hasMutatedProps = instance.props !== newProps; + + if (instance.props !== undefined && hasMutatedProps) { + error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); + } + + if (instance.defaultProps) { + error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); + } + + if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); + + error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); + } + + if (typeof instance.getDerivedStateFromProps === 'function') { + error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } + + if (typeof instance.getDerivedStateFromError === 'function') { + error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } + + if (typeof ctor.getSnapshotBeforeUpdate === 'function') { + error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); + } + + var _state = instance.state; + + if (_state && (typeof _state !== 'object' || isArray(_state))) { + error('%s.state: must be set to an object or null', name); + } + + if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { + error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); + } + } +} + +function callComponentWillMount(type, instance) { + var oldState = instance.state; + + if (typeof instance.componentWillMount === 'function') { + { + if ( instance.componentWillMount.__suppressDeprecationWarning !== true) { + var componentName = getComponentNameFromType(type) || 'Unknown'; + + if (!didWarnAboutDeprecatedWillMount[componentName]) { + warn( // keep this warning in sync with ReactStrictModeWarning.js + 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName); + + didWarnAboutDeprecatedWillMount[componentName] = true; + } + } + } + + instance.componentWillMount(); + } + + if (typeof instance.UNSAFE_componentWillMount === 'function') { + instance.UNSAFE_componentWillMount(); + } + + if (oldState !== instance.state) { + { + error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component'); + } + + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } +} + +function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) { + if (internalInstance.queue !== null && internalInstance.queue.length > 0) { + var oldQueue = internalInstance.queue; + var oldReplace = internalInstance.replace; + internalInstance.queue = null; + internalInstance.replace = false; + + if (oldReplace && oldQueue.length === 1) { + inst.state = oldQueue[0]; + } else { + var nextState = oldReplace ? oldQueue[0] : inst.state; + var dontMutate = true; + + for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { + var partial = oldQueue[i]; + var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial; + + if (partialState != null) { + if (dontMutate) { + dontMutate = false; + nextState = assign({}, nextState, partialState); + } else { + assign(nextState, partialState); + } + } + } + + inst.state = nextState; + } + } else { + internalInstance.queue = null; + } +} // Invokes the mount life-cycles on a previously never rendered instance. + + +function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { + { + checkClassInstance(instance, ctor, newProps); + } + + var initialState = instance.state !== undefined ? instance.state : null; + instance.updater = classComponentUpdater; + instance.props = newProps; + instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. + // The internal instance will be used to manage updates that happen during this mount. + + var internalInstance = { + queue: [], + replace: false + }; + set(instance, internalInstance); + var contextType = ctor.contextType; + + if (typeof contextType === 'object' && contextType !== null) { + instance.context = readContext(contextType); + } else { + instance.context = maskedLegacyContext; + } + + { + if (instance.state === newProps) { + var componentName = getComponentNameFromType(ctor) || 'Component'; + + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); + + error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); + } + } + } + + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + + if (typeof getDerivedStateFromProps === 'function') { + instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps); + } // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. + + + if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { + callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's + // process them now. + + processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext); + } +} + +// Ids are base 32 strings whose binary representation corresponds to the +// position of a node in a tree. +// Every time the tree forks into multiple children, we add additional bits to +// the left of the sequence that represent the position of the child within the +// current level of children. +// +// 00101 00010001011010101 +// ╰─┬─╯ ╰───────┬───────╯ +// Fork 5 of 20 Parent id +// +// The leading 0s are important. In the above example, you only need 3 bits to +// represent slot 5. However, you need 5 bits to represent all the forks at +// the current level, so we must account for the empty bits at the end. +// +// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise, +// the zeroth id at a level would be indistinguishable from its parent. +// +// If a node has only one child, and does not materialize an id (i.e. does not +// contain a useId hook), then we don't need to allocate any space in the +// sequence. It's treated as a transparent indirection. For example, these two +// trees produce the same ids: +// +// <> <> +// +// +// +// +// +// +// However, we cannot skip any node that materializes an id. Otherwise, a parent +// id that does not fork would be indistinguishable from its child id. For +// example, this tree does not fork, but the parent and child must have +// different ids. +// +// +// +// +// +// To handle this scenario, every time we materialize an id, we allocate a +// new level with a single slot. You can think of this as a fork with only one +// prong, or an array of children with length 1. +// +// It's possible for the size of the sequence to exceed 32 bits, the max +// size for bitwise operations. When this happens, we make more room by +// converting the right part of the id to a string and storing it in an overflow +// variable. We use a base 32 string representation, because 32 is the largest +// power of 2 that is supported by toString(). We want the base to be large so +// that the resulting ids are compact, and we want the base to be a power of 2 +// because every log2(base) bits corresponds to a single character, i.e. every +// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without +// affecting the final result. +var emptyTreeContext = { + id: 1, + overflow: '' +}; +function getTreeId(context) { + var overflow = context.overflow; + var idWithLeadingBit = context.id; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; +} +function pushTreeContext(baseContext, totalChildren, index) { + var baseIdWithLeadingBit = baseContext.id; + var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part + // of the id; we use it to account for leading 0s. + + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index + 1; + var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into + // consideration the leading 1 we use to mark the end of the sequence. + + if (length > 30) { + // We overflowed the bitwise-safe range. Fall back to slower algorithm. + // This branch assumes the length of the base id is greater than 5; it won't + // work for smaller ids, because you need 5 bits per character. + // + // We encode the id in multiple steps: first the base id, then the + // remaining digits. + // + // Each 5 bit sequence corresponds to a single base 32 character. So for + // example, if the current id is 23 bits long, we can convert 20 of those + // bits into a string of 4 characters, with 3 bits left over. + // + // First calculate how many bits in the base id represent a complete + // sequence of characters. + var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. + + var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. + + var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. + + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because + // we made more room, this time it won't overflow. + + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + return { + id: 1 << restOfLength | id, + overflow: overflow + }; + } else { + // Normal path + var newBits = slot << baseLength; + + var _id = newBits | baseId; + + var _overflow = baseOverflow; + return { + id: 1 << length | _id, + overflow: _overflow + }; + } +} + +function getBitLength(number) { + return 32 - clz32(number); +} + +function getLeadingBit(id) { + return 1 << getBitLength(id) - 1; +} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. + + +var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. +// Based on: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 + +var log = Math.log; +var LN2 = Math.LN2; + +function clz32Fallback(x) { + var asUint = x >>> 0; + + if (asUint === 0) { + return 32; + } + + return 31 - (log(asUint) / LN2 | 0) | 0; +} + +/** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ +function is(x, y) { + return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare + ; +} + +var objectIs = typeof Object.is === 'function' ? Object.is : is; + +var currentlyRenderingComponent = null; +var currentlyRenderingTask = null; +var firstWorkInProgressHook = null; +var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook + +var isReRender = false; // Whether an update was scheduled during the currently executing render pass. + +var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component + +var localIdCounter = 0; // Lazily created map of render-phase updates + +var renderPhaseUpdates = null; // Counter to prevent infinite loops. + +var numberOfReRenders = 0; +var RE_RENDER_LIMIT = 25; +var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook + +var currentHookNameInDev; + +function resolveCurrentlyRenderingComponent() { + if (currentlyRenderingComponent === null) { + throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); + } + + { + if (isInHookUserCodeInDev) { + error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); + } + } + + return currentlyRenderingComponent; +} + +function areHookInputsEqual(nextDeps, prevDeps) { + if (prevDeps === null) { + { + error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); + } + + return false; + } + + { + // Don't bother comparing lengths in prod because these arrays should be + // passed inline. + if (nextDeps.length !== prevDeps.length) { + error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]"); + } + } + + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } + + return false; + } + + return true; +} + +function createHook() { + if (numberOfReRenders > 0) { + throw new Error('Rendered more hooks than during the previous render'); + } + + return { + memoizedState: null, + queue: null, + next: null + }; +} + +function createWorkInProgressHook() { + if (workInProgressHook === null) { + // This is the first hook in the list + if (firstWorkInProgressHook === null) { + isReRender = false; + firstWorkInProgressHook = workInProgressHook = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = firstWorkInProgressHook; + } + } else { + if (workInProgressHook.next === null) { + isReRender = false; // Append to the end of the list + + workInProgressHook = workInProgressHook.next = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = workInProgressHook.next; + } + } + + return workInProgressHook; +} + +function prepareToUseHooks(task, componentIdentity) { + currentlyRenderingComponent = componentIdentity; + currentlyRenderingTask = task; + + { + isInHookUserCodeInDev = false; + } // The following should have already been reset + // didScheduleRenderPhaseUpdate = false; + // localIdCounter = 0; + // firstWorkInProgressHook = null; + // numberOfReRenders = 0; + // renderPhaseUpdates = null; + // workInProgressHook = null; + + + localIdCounter = 0; +} +function finishHooks(Component, props, children, refOrContext) { + // This must be called after every function component to prevent hooks from + // being used in classes. + while (didScheduleRenderPhaseUpdate) { + // Updates were scheduled during the render phase. They are stored in + // the `renderPhaseUpdates` map. Call the component again, reusing the + // work-in-progress hooks and applying the additional updates on top. Keep + // restarting until no more updates are scheduled. + didScheduleRenderPhaseUpdate = false; + localIdCounter = 0; + numberOfReRenders += 1; // Start over from the beginning of the list + + workInProgressHook = null; + children = Component(props, refOrContext); + } + + resetHooksState(); + return children; +} +function checkDidRenderIdHook() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + var didRenderIdHook = localIdCounter !== 0; + return didRenderIdHook; +} // Reset the internal hooks state if an error occurs while rendering a component + +function resetHooksState() { + { + isInHookUserCodeInDev = false; + } + + currentlyRenderingComponent = null; + currentlyRenderingTask = null; + didScheduleRenderPhaseUpdate = false; + firstWorkInProgressHook = null; + numberOfReRenders = 0; + renderPhaseUpdates = null; + workInProgressHook = null; +} + +function readContext$1(context) { + { + if (isInHookUserCodeInDev) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext(context); +} + +function useContext(context) { + { + currentHookNameInDev = 'useContext'; + } + + resolveCurrentlyRenderingComponent(); + return readContext(context); +} + +function basicStateReducer(state, action) { + // $FlowFixMe: Flow doesn't like mixed types + return typeof action === 'function' ? action(state) : action; +} + +function useState(initialState) { + { + currentHookNameInDev = 'useState'; + } + + return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers + initialState); +} +function useReducer(reducer, initialArg, init) { + { + if (reducer !== basicStateReducer) { + currentHookNameInDev = 'useReducer'; + } + } + + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + + if (isReRender) { + // This is a re-render. Apply the new render phase updates to the previous + // current hook. + var queue = workInProgressHook.queue; + var dispatch = queue.dispatch; + + if (renderPhaseUpdates !== null) { + // Render phase updates are stored in a map of queue -> linked list + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + + if (firstRenderPhaseUpdate !== undefined) { + renderPhaseUpdates.delete(queue); + var newState = workInProgressHook.memoizedState; + var update = firstRenderPhaseUpdate; + + do { + // Process this render phase update. We don't have to check the + // priority because it will always be the same as the current + // render's. + var action = update.action; + + { + isInHookUserCodeInDev = true; + } + + newState = reducer(newState, action); + + { + isInHookUserCodeInDev = false; + } + + update = update.next; + } while (update !== null); + + workInProgressHook.memoizedState = newState; + return [newState, dispatch]; + } + } + + return [workInProgressHook.memoizedState, dispatch]; + } else { + { + isInHookUserCodeInDev = true; + } + + var initialState; + + if (reducer === basicStateReducer) { + // Special case for `useState`. + initialState = typeof initialArg === 'function' ? initialArg() : initialArg; + } else { + initialState = init !== undefined ? init(initialArg) : initialArg; + } + + { + isInHookUserCodeInDev = false; + } + + workInProgressHook.memoizedState = initialState; + + var _queue = workInProgressHook.queue = { + last: null, + dispatch: null + }; + + var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue); + + return [workInProgressHook.memoizedState, _dispatch]; + } +} + +function useMemo(nextCreate, deps) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + + if (workInProgressHook !== null) { + var prevState = workInProgressHook.memoizedState; + + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; + + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } + } + + { + isInHookUserCodeInDev = true; + } + + var nextValue = nextCreate(); + + { + isInHookUserCodeInDev = false; + } + + workInProgressHook.memoizedState = [nextValue, nextDeps]; + return nextValue; +} + +function useRef(initialValue) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var previousRef = workInProgressHook.memoizedState; + + if (previousRef === null) { + var ref = { + current: initialValue + }; + + { + Object.seal(ref); + } + + workInProgressHook.memoizedState = ref; + return ref; + } else { + return previousRef; + } +} + +function useLayoutEffect(create, inputs) { + { + currentHookNameInDev = 'useLayoutEffect'; + + error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.'); + } +} + +function dispatchAction(componentIdentity, queue, action) { + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); + } + + if (componentIdentity === currentlyRenderingComponent) { + // This is a render phase update. Stash it in a lazily-created map of + // queue -> linked list of updates. After this render pass, we'll restart + // and apply the stashed updates on top of the work-in-progress hook. + didScheduleRenderPhaseUpdate = true; + var update = { + action: action, + next: null + }; + + if (renderPhaseUpdates === null) { + renderPhaseUpdates = new Map(); + } + + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + + if (firstRenderPhaseUpdate === undefined) { + renderPhaseUpdates.set(queue, update); + } else { + // Append the update to the end of the list. + var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + + while (lastRenderPhaseUpdate.next !== null) { + lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; + } + + lastRenderPhaseUpdate.next = update; + } + } +} + +function useCallback(callback, deps) { + return useMemo(function () { + return callback; + }, deps); +} // TODO Decide on how to implement this hook for server rendering. +// If a mutation occurs during render, consider triggering a Suspense boundary +// and falling back to client rendering. + +function useMutableSource(source, getSnapshot, subscribe) { + resolveCurrentlyRenderingComponent(); + return getSnapshot(source._source); +} + +function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + if (getServerSnapshot === undefined) { + throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); + } + + return getServerSnapshot(); +} + +function useDeferredValue(value) { + resolveCurrentlyRenderingComponent(); + return value; +} + +function unsupportedStartTransition() { + throw new Error('startTransition cannot be called during server rendering.'); +} + +function useTransition() { + resolveCurrentlyRenderingComponent(); + return [false, unsupportedStartTransition]; +} + +function useId() { + var task = currentlyRenderingTask; + var treeId = getTreeId(task.treeContext); + var responseState = currentResponseState; + + if (responseState === null) { + throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.'); + } + + var localId = localIdCounter++; + return makeId(responseState, treeId, localId); +} + +function noop() {} + +var Dispatcher = { + readContext: readContext$1, + useContext: useContext, + useMemo: useMemo, + useReducer: useReducer, + useRef: useRef, + useState: useState, + useInsertionEffect: noop, + useLayoutEffect: useLayoutEffect, + useCallback: useCallback, + // useImperativeHandle is not run in the server environment + useImperativeHandle: noop, + // Effects are not run in the server environment. + useEffect: noop, + // Debugging effect + useDebugValue: noop, + useDeferredValue: useDeferredValue, + useTransition: useTransition, + useId: useId, + // Subscriptions are not setup in a server environment. + useMutableSource: useMutableSource, + useSyncExternalStore: useSyncExternalStore +}; + +var currentResponseState = null; +function setCurrentResponseState(responseState) { + currentResponseState = responseState; +} + +function getStackByComponentStackNode(componentStack) { + try { + var info = ''; + var node = componentStack; + + do { + switch (node.tag) { + case 0: + info += describeBuiltInComponentFrame(node.type, null, null); + break; + + case 1: + info += describeFunctionComponentFrame(node.type, null, null); + break; + + case 2: + info += describeClassComponentFrame(node.type, null, null); + break; + } + + node = node.parent; + } while (node); + + return info; + } catch (x) { + return '\nError generating stack: ' + x.message + '\n' + x.stack; + } +} + +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; +var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; +var PENDING = 0; +var COMPLETED = 1; +var FLUSHED = 2; +var ABORTED = 3; +var ERRORED = 4; +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +// This is a default heuristic for how to split up the HTML content into progressive +// loading. Our goal is to be able to display additional new content about every 500ms. +// Faster than that is unnecessary and should be throttled on the client. It also +// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower +// end device but higher end suffer less from the overhead than lower end does from +// not getting small enough pieces. We error on the side of low end. +// We base this on low end 3G speeds which is about 500kbits per second. We assume +// that there can be a reasonable drop off from max bandwidth which leaves you with +// as little as 80%. We can receive half of that each 500ms - at best. In practice, +// a little bandwidth is lost to processing and contention - e.g. CSS and images that +// are downloaded along with the main content. So we estimate about half of that to be +// the lower end throughput. In other words, we expect that you can at least show +// about 12.5kb of content per 500ms. Not counting starting latency for the first +// paint. +// 500 * 1024 / 8 * .8 * 0.5 / 2 +var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper + + return null; +} + +function noop$1() {} + +function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) { + var pingedTasks = []; + var abortSet = new Set(); + var request = { + destination: null, + responseState: responseState, + progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize, + status: OPEN, + fatalError: null, + nextSegmentId: 0, + allPendingTasks: 0, + pendingRootTasks: 0, + completedRootSegment: null, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + clientRenderedBoundaries: [], + completedBoundaries: [], + partialBoundaries: [], + onError: onError === undefined ? defaultErrorHandler : onError, + onAllReady: onAllReady === undefined ? noop$1 : onAllReady, + onShellReady: onShellReady === undefined ? noop$1 : onShellReady, + onShellError: onShellError === undefined ? noop$1 : onShellError, + onFatalError: onFatalError === undefined ? noop$1 : onFatalError + }; // This segment represents the root fallback. + + var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge + false, false); // There is no parent so conceptually, we're unblocked to flush this segment. + + rootSegment.parentFlushed = true; + var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext); + pingedTasks.push(rootTask); + return request; +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createSuspenseBoundary(request, fallbackAbortableTasks) { + return { + id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID, + rootSegmentID: -1, + parentFlushed: false, + pendingTasks: 0, + forceClientRender: false, + completedSegments: [], + byteSize: 0, + fallbackAbortableTasks: fallbackAbortableTasks, + errorDigest: null + }; +} + +function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) { + request.allPendingTasks++; + + if (blockedBoundary === null) { + request.pendingRootTasks++; + } else { + blockedBoundary.pendingTasks++; + } + + var task = { + node: node, + ping: function () { + return pingTask(request, task); + }, + blockedBoundary: blockedBoundary, + blockedSegment: blockedSegment, + abortSet: abortSet, + legacyContext: legacyContext, + context: context, + treeContext: treeContext + }; + + { + task.componentStack = null; + } + + abortSet.add(task); + return task; +} + +function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) { + return { + status: PENDING, + id: -1, + // lazily assigned later + index: index, + parentFlushed: false, + chunks: [], + children: [], + formatContext: formatContext, + boundary: boundary, + lastPushedText: lastPushedText, + textEmbedded: textEmbedded + }; +} // DEV-only global reference to the currently executing task + + +var currentTaskInDEV = null; + +function getCurrentStackInDEV() { + { + if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) { + return ''; + } + + return getStackByComponentStackNode(currentTaskInDEV.componentStack); + } +} + +function pushBuiltInComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 0, + parent: task.componentStack, + type: type + }; + } +} + +function pushFunctionComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 1, + parent: task.componentStack, + type: type + }; + } +} + +function pushClassComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 2, + parent: task.componentStack, + type: type + }; + } +} + +function popComponentStackInDEV(task) { + { + if (task.componentStack === null) { + error('Unexpectedly popped too many stack frames. This is a bug in React.'); + } else { + task.componentStack = task.componentStack.parent; + } + } +} // stash the component stack of an unwinding error until it is processed + + +var lastBoundaryErrorComponentStackDev = null; + +function captureBoundaryErrorDetailsDev(boundary, error) { + { + var errorMessage; + + if (typeof error === 'string') { + errorMessage = error; + } else if (error && typeof error.message === 'string') { + errorMessage = error.message; + } else { + // eslint-disable-next-line react-internal/safe-string-coercion + errorMessage = String(error); + } + + var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV(); + lastBoundaryErrorComponentStackDev = null; + boundary.errorMessage = errorMessage; + boundary.errorComponentStack = errorComponentStack; + } +} + +function logRecoverableError(request, error) { + // If this callback errors, we intentionally let that error bubble up to become a fatal error + // so that someone fixes the error reporting instead of hiding it. + var errorDigest = request.onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest; +} + +function fatalError(request, error) { + // This is called outside error handling code such as if the root errors outside + // a suspense boundary or if the root suspense boundary's fallback errors. + // It's also called if React itself or its host configs errors. + var onShellError = request.onShellError; + onShellError(error); + var onFatalError = request.onFatalError; + onFatalError(error); + + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function renderSuspenseBoundary(request, task, props) { + pushBuiltInComponentStackInDEV(task, 'Suspense'); + var parentBoundary = task.blockedBoundary; + var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for + // the fallback so that we can later replace that segment with the content. + // This also lets us split out the main content even if it doesn't suspend, + // in case it ends up generating a large subtree of content. + + var fallback = props.fallback; + var content = props.children; + var fallbackAbortSet = new Set(); + var newBoundary = createSuspenseBoundary(request, fallbackAbortSet); + var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback. + + var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them + false, false); + parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent + + parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately. + + var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them + false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is + // no parent segment so there's nothing to wait on. + + contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks. + // I suspect that there might be some efficiency benefits from not creating the suspended task + // and instead just using the stack if possible. + // TODO: Call this directly instead of messing with saving and restoring contexts. + // We can reuse the current context and task to render the content immediately without + // context switching. We just need to temporarily switch which boundary and which segment + // we're writing to. If something suspends, it'll spawn new suspended task with that context. + + task.blockedBoundary = newBoundary; + task.blockedSegment = contentRootSegment; + + try { + // We use the safe form because we don't handle suspending here. Only error handling. + renderNode(request, task, content); + pushSegmentFinale$1(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded); + contentRootSegment.status = COMPLETED; + queueCompletedSegment(newBoundary, contentRootSegment); + + if (newBoundary.pendingTasks === 0) { + // This must have been the last segment we were waiting on. This boundary is now complete. + // Therefore we won't need the fallback. We early return so that we don't have to create + // the fallback. + popComponentStackInDEV(task); + return; + } + } catch (error) { + contentRootSegment.status = ERRORED; + newBoundary.forceClientRender = true; + newBoundary.errorDigest = logRecoverableError(request, error); + + { + captureBoundaryErrorDetailsDev(newBoundary, error); + } // We don't need to decrement any task numbers because we didn't spawn any new task. + // We don't need to schedule any task because we know the parent has written yet. + // We do need to fallthrough to create the fallback though. + + } finally { + task.blockedBoundary = parentBoundary; + task.blockedSegment = parentSegment; + } // We create suspended task for the fallback because we don't want to actually work + // on it yet in case we finish the main content, so we queue for later. + + + var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext); + + { + suspendedFallbackTask.componentStack = task.componentStack; + } // TODO: This should be queued at a separate lower priority queue so that we only work + // on preparing fallbacks if we don't have any more main content to task on. + + + request.pingedTasks.push(suspendedFallbackTask); + popComponentStackInDEV(task); +} + +function renderHostElement(request, task, type, props) { + pushBuiltInComponentStackInDEV(task, type); + var segment = task.blockedSegment; + var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext); + segment.lastPushedText = false; + var prevContext = segment.formatContext; + segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still + // need to pop back up and finish this subtree of HTML. + + renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need + // the correct context. Therefore this is not in a finally. + + segment.formatContext = prevContext; + pushEndInstance(segment.chunks, type); + segment.lastPushedText = false; + popComponentStackInDEV(task); +} + +function shouldConstruct$1(Component) { + return Component.prototype && Component.prototype.isReactComponent; +} + +function renderWithHooks(request, task, Component, props, secondArg) { + var componentIdentity = {}; + prepareToUseHooks(task, componentIdentity); + var result = Component(props, secondArg); + return finishHooks(Component, props, result, secondArg); +} + +function finishClassComponent(request, task, instance, Component, props) { + var nextChildren = instance.render(); + + { + if (instance.props !== props) { + if (!didWarnAboutReassigningProps) { + error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component'); + } + + didWarnAboutReassigningProps = true; + } + } + + { + var childContextTypes = Component.childContextTypes; + + if (childContextTypes !== null && childContextTypes !== undefined) { + var previousContext = task.legacyContext; + var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes); + task.legacyContext = mergedContext; + renderNodeDestructive(request, task, nextChildren); + task.legacyContext = previousContext; + return; + } + } + + renderNodeDestructive(request, task, nextChildren); +} + +function renderClassComponent(request, task, Component, props) { + pushClassComponentStackInDEV(task, Component); + var maskedContext = getMaskedContext(Component, task.legacyContext) ; + var instance = constructClassInstance(Component, props, maskedContext); + mountClassInstance(instance, Component, props, maskedContext); + finishClassComponent(request, task, instance, Component, props); + popComponentStackInDEV(task); +} + +var didWarnAboutBadClass = {}; +var didWarnAboutModulePatternComponent = {}; +var didWarnAboutContextTypeOnFunctionComponent = {}; +var didWarnAboutGetDerivedStateOnFunctionComponent = {}; +var didWarnAboutReassigningProps = false; +var didWarnAboutGenerators = false; +var didWarnAboutMaps = false; +var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern +// components for some reason. + +function renderIndeterminateComponent(request, task, Component, props) { + var legacyContext; + + { + legacyContext = getMaskedContext(Component, task.legacyContext); + } + + pushFunctionComponentStackInDEV(task, Component); + + { + if (Component.prototype && typeof Component.prototype.render === 'function') { + var componentName = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutBadClass[componentName]) { + error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); + + didWarnAboutBadClass[componentName] = true; + } + } + } + + var value = renderWithHooks(request, task, Component, props, legacyContext); + var hasId = checkDidRenderIdHook(); + + { + // Support for module components is deprecated and is removed behind a flag. + // Whether or not it would crash later, we want to show a good message in DEV first. + if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + var _componentName = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutModulePatternComponent[_componentName]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); + + didWarnAboutModulePatternComponent[_componentName] = true; + } + } + } + + if ( // Run these checks in production only if the flag is off. + // Eventually we'll delete this branch altogether. + typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + { + var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutModulePatternComponent[_componentName2]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); + + didWarnAboutModulePatternComponent[_componentName2] = true; + } + } + + mountClassInstance(value, Component, props, legacyContext); + finishClassComponent(request, task, value, Component, props); + } else { + + { + validateFunctionComponentInDev(Component); + } // We're now successfully past this task, and we don't have to pop back to + // the previous task every again, so we can use the destructive recursive form. + + + if (hasId) { + // This component materialized an id. We treat this as its own level, with + // a single "child" slot. + var prevTreeContext = task.treeContext; + var totalChildren = 1; + var index = 0; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index); + + try { + renderNodeDestructive(request, task, value); + } finally { + task.treeContext = prevTreeContext; + } + } else { + renderNodeDestructive(request, task, value); + } + } + + popComponentStackInDEV(task); +} + +function validateFunctionComponentInDev(Component) { + { + if (Component) { + if (Component.childContextTypes) { + error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); + } + } + + if (typeof Component.getDerivedStateFromProps === 'function') { + var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { + error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); + + didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; + } + } + + if (typeof Component.contextType === 'object' && Component.contextType !== null) { + var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { + error('%s: Function components do not support contextType.', _componentName4); + + didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; + } + } + } +} + +function resolveDefaultProps(Component, baseProps) { + if (Component && Component.defaultProps) { + // Resolve default props. Taken from ReactElement + var props = assign({}, baseProps); + var defaultProps = Component.defaultProps; + + for (var propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + + return props; + } + + return baseProps; +} + +function renderForwardRef(request, task, type, props, ref) { + pushFunctionComponentStackInDEV(task, type.render); + var children = renderWithHooks(request, task, type.render, props, ref); + var hasId = checkDidRenderIdHook(); + + if (hasId) { + // This component materialized an id. We treat this as its own level, with + // a single "child" slot. + var prevTreeContext = task.treeContext; + var totalChildren = 1; + var index = 0; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index); + + try { + renderNodeDestructive(request, task, children); + } finally { + task.treeContext = prevTreeContext; + } + } else { + renderNodeDestructive(request, task, children); + } + + popComponentStackInDEV(task); +} + +function renderMemo(request, task, type, props, ref) { + var innerType = type.type; + var resolvedProps = resolveDefaultProps(innerType, props); + renderElement(request, task, innerType, resolvedProps, ref); +} + +function renderContextConsumer(request, task, context, props) { + // The logic below for Context differs depending on PROD or DEV mode. In + // DEV mode, we create a separate object for Context.Consumer that acts + // like a proxy to Context. This proxy object adds unnecessary code in PROD + // so we use the old behaviour (Context.Consumer references Context) to + // reduce size and overhead. The separate object references context via + // a property called "_context", which also gives us the ability to check + // in DEV mode if this property exists or not and warn if it does not. + { + if (context._context === undefined) { + // This may be because it's a Context (rather than a Consumer). + // Or it may be because it's older React where they're the same thing. + // We only want to warn if we're sure it's a new React. + if (context !== context.Consumer) { + if (!hasWarnedAboutUsingContextAsConsumer) { + hasWarnedAboutUsingContextAsConsumer = true; + + error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + } + } else { + context = context._context; + } + } + + var render = props.children; + + { + if (typeof render !== 'function') { + error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); + } + } + + var newValue = readContext(context); + var newChildren = render(newValue); + renderNodeDestructive(request, task, newChildren); +} + +function renderContextProvider(request, task, type, props) { + var context = type._context; + var value = props.value; + var children = props.children; + var prevSnapshot; + + { + prevSnapshot = task.context; + } + + task.context = pushProvider(context, value); + renderNodeDestructive(request, task, children); + task.context = popProvider(context); + + { + if (prevSnapshot !== task.context) { + error('Popping the context provider did not return back to the original snapshot. This is a bug in React.'); + } + } +} + +function renderLazyComponent(request, task, lazyComponent, props, ref) { + pushBuiltInComponentStackInDEV(task, 'Lazy'); + var payload = lazyComponent._payload; + var init = lazyComponent._init; + var Component = init(payload); + var resolvedProps = resolveDefaultProps(Component, props); + renderElement(request, task, Component, resolvedProps, ref); + popComponentStackInDEV(task); +} + +function renderElement(request, task, type, props, ref) { + if (typeof type === 'function') { + if (shouldConstruct$1(type)) { + renderClassComponent(request, task, type, props); + return; + } else { + renderIndeterminateComponent(request, task, type, props); + return; + } + } + + if (typeof type === 'string') { + renderHostElement(request, task, type, props); + return; + } + + switch (type) { + // TODO: LegacyHidden acts the same as a fragment. This only works + // because we currently assume that every instance of LegacyHidden is + // accompanied by a host component wrapper. In the hidden mode, the host + // component is given a `hidden` attribute, which ensures that the + // initial HTML is not visible. To support the use of LegacyHidden as a + // true fragment, without an extra DOM node, we would have to hide the + // initial HTML in some other way. + // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability. + case REACT_LEGACY_HIDDEN_TYPE: + case REACT_DEBUG_TRACING_MODE_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_PROFILER_TYPE: + case REACT_FRAGMENT_TYPE: + { + renderNodeDestructive(request, task, props.children); + return; + } + + case REACT_SUSPENSE_LIST_TYPE: + { + pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries. + + renderNodeDestructive(request, task, props.children); + popComponentStackInDEV(task); + return; + } + + case REACT_SCOPE_TYPE: + { + + throw new Error('ReactDOMServer does not yet support scope components.'); + } + // eslint-disable-next-line-no-fallthrough + + case REACT_SUSPENSE_TYPE: + { + { + renderSuspenseBoundary(request, task, props); + } + + return; + } + } + + if (typeof type === 'object' && type !== null) { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + { + renderForwardRef(request, task, type, props, ref); + return; + } + + case REACT_MEMO_TYPE: + { + renderMemo(request, task, type, props, ref); + return; + } + + case REACT_PROVIDER_TYPE: + { + renderContextProvider(request, task, type, props); + return; + } + + case REACT_CONTEXT_TYPE: + { + renderContextConsumer(request, task, type, props); + return; + } + + case REACT_LAZY_TYPE: + { + renderLazyComponent(request, task, type, props); + return; + } + } + } + + var info = ''; + + { + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; + } + } + + throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); +} + +function validateIterable(iterable, iteratorFn) { + { + // We don't support rendering Generators because it's a mutation. + // See https://github.com/facebook/react/issues/12995 + if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag + iterable[Symbol.toStringTag] === 'Generator') { + if (!didWarnAboutGenerators) { + error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); + } + + didWarnAboutGenerators = true; + } // Warn about using Maps as children + + + if (iterable.entries === iteratorFn) { + if (!didWarnAboutMaps) { + error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); + } + + didWarnAboutMaps = true; + } + } +} + +function renderNodeDestructive(request, task, node) { + { + // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture + // a component stack at the right place in the tree. We don't do this in renderNode + // becuase it is not called at every layer of the tree and we may lose frames + try { + return renderNodeDestructiveImpl(request, task, node); + } catch (x) { + if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else { + // This is an error, stash the component stack if it is null. + lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV(); + } // rethrow so normal suspense logic can handle thrown value accordingly + + + throw x; + } + } +} // This function by it self renders a node and consumes the task by mutating it +// to update the current execution state. + + +function renderNodeDestructiveImpl(request, task, node) { + // Stash the node we're working on. We'll pick up from this task in case + // something suspends. + task.node = node; // Handle object types + + if (typeof node === 'object' && node !== null) { + switch (node.$$typeof) { + case REACT_ELEMENT_TYPE: + { + var element = node; + var type = element.type; + var props = element.props; + var ref = element.ref; + renderElement(request, task, type, props, ref); + return; + } + + case REACT_PORTAL_TYPE: + throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.'); + // eslint-disable-next-line-no-fallthrough + + case REACT_LAZY_TYPE: + { + var lazyNode = node; + var payload = lazyNode._payload; + var init = lazyNode._init; + var resolvedNode; + + { + try { + resolvedNode = init(payload); + } catch (x) { + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be + // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position + // vs Component position. We do not want the frame for Errors so we exclusively do this in + // the wakeable branch + pushBuiltInComponentStackInDEV(task, 'Lazy'); + } + + throw x; + } + } + + renderNodeDestructive(request, task, resolvedNode); + return; + } + } + + if (isArray(node)) { + renderChildrenArray(request, task, node); + return; + } + + var iteratorFn = getIteratorFn(node); + + if (iteratorFn) { + { + validateIterable(node, iteratorFn); + } + + var iterator = iteratorFn.call(node); + + if (iterator) { + // We need to know how many total children are in this set, so that we + // can allocate enough id slots to acommodate them. So we must exhaust + // the iterator before we start recursively rendering the children. + // TODO: This is not great but I think it's inherent to the id + // generation algorithm. + var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that. + + if (!step.done) { + var children = []; + + do { + children.push(step.value); + step = iterator.next(); + } while (!step.done); + + renderChildrenArray(request, task, children); + return; + } + + return; + } + } + + var childString = Object.prototype.toString.call(node); + throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); + } + + if (typeof node === 'string') { + var segment = task.blockedSegment; + segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText); + return; + } + + if (typeof node === 'number') { + var _segment = task.blockedSegment; + _segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText); + return; + } + + { + if (typeof node === 'function') { + error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.'); + } + } +} + +function renderChildrenArray(request, task, children) { + var totalChildren = children.length; + + for (var i = 0; i < totalChildren; i++) { + var prevTreeContext = task.treeContext; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i); + + try { + // We need to use the non-destructive form so that we can safely pop back + // up and render the sibling if something suspends. + renderNode(request, task, children[i]); + } finally { + task.treeContext = prevTreeContext; + } + } +} + +function spawnNewSuspendedTask(request, task, x) { + // Something suspended, we'll need to create a new segment and resolve it later. + var segment = task.blockedSegment; + var insertionIndex = segment.chunks.length; + var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed + segment.lastPushedText, // Assume we are text embedded at the trailing edge + true); + segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it + + segment.lastPushedText = false; + var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext); + + { + if (task.componentStack !== null) { + // We pop one task off the stack because the node that suspended will be tried again, + // which will add it back onto the stack. + newTask.componentStack = task.componentStack.parent; + } + } + + var ping = newTask.ping; + x.then(ping, ping); +} // This is a non-destructive form of rendering a node. If it suspends it spawns +// a new task and restores the context of this task to what it was before. + + +function renderNode(request, task, node) { + // TODO: Store segment.children.length here and reset it in case something + // suspended partially through writing something. + // Snapshot the current context in case something throws to interrupt the + // process. + var previousFormatContext = task.blockedSegment.formatContext; + var previousLegacyContext = task.legacyContext; + var previousContext = task.context; + var previousComponentStack = null; + + { + previousComponentStack = task.componentStack; + } + + try { + return renderNodeDestructive(request, task, node); + } catch (x) { + resetHooksState(); + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner + // functions in case nothing throws so we don't use "finally" here. + + task.blockedSegment.formatContext = previousFormatContext; + task.legacyContext = previousLegacyContext; + task.context = previousContext; // Restore all active ReactContexts to what they were before. + + switchContext(previousContext); + + { + task.componentStack = previousComponentStack; + } + + return; + } else { + // Restore the context. We assume that this will be restored by the inner + // functions in case nothing throws so we don't use "finally" here. + task.blockedSegment.formatContext = previousFormatContext; + task.legacyContext = previousLegacyContext; + task.context = previousContext; // Restore all active ReactContexts to what they were before. + + switchContext(previousContext); + + { + task.componentStack = previousComponentStack; + } // We assume that we don't need the correct context. + // Let's terminate the rest of the tree and don't render any siblings. + + + throw x; + } + } +} + +function erroredTask(request, boundary, segment, error) { + // Report the error to a global handler. + var errorDigest = logRecoverableError(request, error); + + if (boundary === null) { + fatalError(request, error); + } else { + boundary.pendingTasks--; + + if (!boundary.forceClientRender) { + boundary.forceClientRender = true; + boundary.errorDigest = errorDigest; + + { + captureBoundaryErrorDetailsDev(boundary, error); + } // Regardless of what happens next, this boundary won't be displayed, + // so we can flush it, if the parent already flushed. + + + if (boundary.parentFlushed) { + // We don't have a preference where in the queue this goes since it's likely + // to error on the client anyway. However, intentionally client-rendered + // boundaries should be flushed earlier so that they can start on the client. + // We reuse the same queue for errors. + request.clientRenderedBoundaries.push(boundary); + } + } + } + + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + var onAllReady = request.onAllReady; + onAllReady(); + } +} + +function abortTaskSoft(task) { + // This aborts task without aborting the parent boundary that it blocks. + // It's used for when we didn't need this task to complete the tree. + // If task was needed, then it should use abortTask instead. + var request = this; + var boundary = task.blockedBoundary; + var segment = task.blockedSegment; + segment.status = ABORTED; + finishedTask(request, boundary, segment); +} + +function abortTask(task, request, reason) { + // This aborts the task and aborts the parent that it blocks, putting it into + // client rendered mode. + var boundary = task.blockedBoundary; + var segment = task.blockedSegment; + segment.status = ABORTED; + + if (boundary === null) { + request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close + // the request; + + if (request.status !== CLOSED) { + request.status = CLOSED; + + if (request.destination !== null) { + close(request.destination); + } + } + } else { + boundary.pendingTasks--; + + if (!boundary.forceClientRender) { + boundary.forceClientRender = true; + + var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + + boundary.errorDigest = request.onError(_error); + + { + var errorPrefix = 'The server did not finish this Suspense boundary: '; + + if (_error && typeof _error.message === 'string') { + _error = errorPrefix + _error.message; + } else { + // eslint-disable-next-line react-internal/safe-string-coercion + _error = errorPrefix + String(_error); + } + + var previousTaskInDev = currentTaskInDEV; + currentTaskInDEV = task; + + try { + captureBoundaryErrorDetailsDev(boundary, _error); + } finally { + currentTaskInDEV = previousTaskInDev; + } + } + + if (boundary.parentFlushed) { + request.clientRenderedBoundaries.push(boundary); + } + } // If this boundary was still pending then we haven't already cancelled its fallbacks. + // We'll need to abort the fallbacks, which will also error that parent boundary. + + + boundary.fallbackAbortableTasks.forEach(function (fallbackTask) { + return abortTask(fallbackTask, request, reason); + }); + boundary.fallbackAbortableTasks.clear(); + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + var onAllReady = request.onAllReady; + onAllReady(); + } + } +} + +function queueCompletedSegment(boundary, segment) { + if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) { + // This is an empty segment. There's nothing to write, so we can instead transfer the ID + // to the child. That way any existing references point to the child. + var childSegment = segment.children[0]; + childSegment.id = segment.id; + childSegment.parentFlushed = true; + + if (childSegment.status === COMPLETED) { + queueCompletedSegment(boundary, childSegment); + } + } else { + var completedSegments = boundary.completedSegments; + completedSegments.push(segment); + } +} + +function finishedTask(request, boundary, segment) { + if (boundary === null) { + if (segment.parentFlushed) { + if (request.completedRootSegment !== null) { + throw new Error('There can only be one root segment. This is a bug in React.'); + } + + request.completedRootSegment = segment; + } + + request.pendingRootTasks--; + + if (request.pendingRootTasks === 0) { + // We have completed the shell so the shell can't error anymore. + request.onShellError = noop$1; + var onShellReady = request.onShellReady; + onShellReady(); + } + } else { + boundary.pendingTasks--; + + if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) { + // This must have been the last segment we were waiting on. This boundary is now complete. + if (segment.parentFlushed) { + // Our parent segment already flushed, so we need to schedule this segment to be emitted. + // If it is a segment that was aborted, we'll write other content instead so we don't need + // to emit it. + if (segment.status === COMPLETED) { + queueCompletedSegment(boundary, segment); + } + } + + if (boundary.parentFlushed) { + // The segment might be part of a segment that didn't flush yet, but if the boundary's + // parent flushed, we need to schedule the boundary to be emitted. + request.completedBoundaries.push(boundary); + } // We can now cancel any pending task on the fallback since we won't need to show it anymore. + // This needs to happen after we read the parentFlushed flags because aborting can finish + // work which can trigger user code, which can start flushing, which can change those flags. + + + boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request); + boundary.fallbackAbortableTasks.clear(); + } else { + if (segment.parentFlushed) { + // Our parent already flushed, so we need to schedule this segment to be emitted. + // If it is a segment that was aborted, we'll write other content instead so we don't need + // to emit it. + if (segment.status === COMPLETED) { + queueCompletedSegment(boundary, segment); + var completedSegments = boundary.completedSegments; + + if (completedSegments.length === 1) { + // This is the first time since we last flushed that we completed anything. + // We can schedule this boundary to emit its partially completed segments early + // in case the parent has already been flushed. + if (boundary.parentFlushed) { + request.partialBoundaries.push(boundary); + } + } + } + } + } + } + + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + // This needs to be called at the very end so that we can synchronously write the result + // in the callback if needed. + var onAllReady = request.onAllReady; + onAllReady(); + } +} + +function retryTask(request, task) { + var segment = task.blockedSegment; + + if (segment.status !== PENDING) { + // We completed this by other means before we had a chance to retry it. + return; + } // We restore the context to what it was when we suspended. + // We don't restore it after we leave because it's likely that we'll end up + // needing a very similar context soon again. + + + switchContext(task.context); + var prevTaskInDEV = null; + + { + prevTaskInDEV = currentTaskInDEV; + currentTaskInDEV = task; + } + + try { + // We call the destructive form that mutates this task. That way if something + // suspends again, we can reuse the same task instead of spawning a new one. + renderNodeDestructive(request, task, task.node); + pushSegmentFinale$1(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded); + task.abortSet.delete(task); + segment.status = COMPLETED; + finishedTask(request, task.blockedBoundary, segment); + } catch (x) { + resetHooksState(); + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + } else { + task.abortSet.delete(task); + segment.status = ERRORED; + erroredTask(request, task.blockedBoundary, segment, x); + } + } finally { + { + currentTaskInDEV = prevTaskInDEV; + } + } +} + +function performWork(request) { + if (request.status === CLOSED) { + return; + } + + var prevContext = getActiveContext(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = Dispatcher; + var prevGetCurrentStackImpl; + + { + prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack; + ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV; + } + + var prevResponseState = currentResponseState; + setCurrentResponseState(request.responseState); + + try { + var pingedTasks = request.pingedTasks; + var i; + + for (i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + pingedTasks.splice(0, i); + + if (request.destination !== null) { + flushCompletedQueues(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + setCurrentResponseState(prevResponseState); + ReactCurrentDispatcher$1.current = prevDispatcher; + + { + ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl; + } + + if (prevDispatcher === Dispatcher) { + // This means that we were in a reentrant work loop. This could happen + // in a renderer that supports synchronous work like renderToString, + // when it's called from within another renderer. + // Normally we don't bother switching the contexts to their root/default + // values when leaving because we'll likely need the same or similar + // context again. However, when we're inside a synchronous loop like this + // we'll to restore the context to what it was before returning. + switchContext(prevContext); + } + } +} + +function flushSubtree(request, destination, segment) { + segment.parentFlushed = true; + + switch (segment.status) { + case PENDING: + { + // We're emitting a placeholder for this segment to be filled in later. + // Therefore we'll need to assign it an ID - to refer to it by. + var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately + + segment.lastPushedText = false; + segment.textEmbedded = false; + return writePlaceholder(destination, request.responseState, segmentID); + } + + case COMPLETED: + { + segment.status = FLUSHED; + var r = true; + var chunks = segment.chunks; + var chunkIdx = 0; + var children = segment.children; + + for (var childIdx = 0; childIdx < children.length; childIdx++) { + var nextChild = children[childIdx]; // Write all the chunks up until the next child. + + for (; chunkIdx < nextChild.index; chunkIdx++) { + writeChunk(destination, chunks[chunkIdx]); + } + + r = flushSegment(request, destination, nextChild); + } // Finally just write all the remaining chunks + + + for (; chunkIdx < chunks.length - 1; chunkIdx++) { + writeChunk(destination, chunks[chunkIdx]); + } + + if (chunkIdx < chunks.length) { + r = writeChunkAndReturn(destination, chunks[chunkIdx]); + } + + return r; + } + + default: + { + throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.'); + } + } +} + +function flushSegment(request, destination, segment) { + var boundary = segment.boundary; + + if (boundary === null) { + // Not a suspense boundary. + return flushSubtree(request, destination, segment); + } + + boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to + // emit the content or the fallback now. + + if (boundary.forceClientRender) { + // Emit a client rendered suspense boundary wrapper. + // We never queue the inner boundary so we'll never emit its content or partial segments. + writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState); + } else if (boundary.pendingTasks > 0) { + // This boundary is still loading. Emit a pending suspense boundary wrapper. + // Assign an ID to refer to the future content by. + boundary.rootSegmentID = request.nextSegmentId++; + + if (boundary.completedSegments.length > 0) { + // If this is at least partially complete, we can queue it to be partially emitted early. + request.partialBoundaries.push(boundary); + } /// This is the first time we should have referenced this ID. + + + var id = boundary.id = assignSuspenseBoundaryID(request.responseState); + writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndPendingSuspenseBoundary(destination, request.responseState); + } else if (boundary.byteSize > request.progressiveChunkSize) { + // This boundary is large and will be emitted separately so that we can progressively show + // other content. We add it to the queue during the flush because we have to ensure that + // the parent flushes first so that there's something to inject it into. + // We also have to make sure that it's emitted into the queue in a deterministic slot. + // I.e. we can't insert it here when it completes. + // Assign an ID to refer to the future content by. + boundary.rootSegmentID = request.nextSegmentId++; + request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper. + + writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndPendingSuspenseBoundary(destination, request.responseState); + } else { + // We can inline this boundary's content as a complete boundary. + writeStartCompletedSuspenseBoundary$1(destination, request.responseState); + var completedSegments = boundary.completedSegments; + + if (completedSegments.length !== 1) { + throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.'); + } + + var contentSegment = completedSegments[0]; + flushSegment(request, destination, contentSegment); + return writeEndCompletedSuspenseBoundary$1(destination, request.responseState); + } +} + +function flushClientRenderedBoundary(request, destination, boundary) { + return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); +} + +function flushSegmentContainer(request, destination, segment) { + writeStartSegment(destination, request.responseState, segment.formatContext, segment.id); + flushSegment(request, destination, segment); + return writeEndSegment(destination, segment.formatContext); +} + +function flushCompletedBoundary(request, destination, boundary) { + var completedSegments = boundary.completedSegments; + var i = 0; + + for (; i < completedSegments.length; i++) { + var segment = completedSegments[i]; + flushPartiallyCompletedSegment(request, destination, boundary, segment); + } + + completedSegments.length = 0; + return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID); +} + +function flushPartialBoundary(request, destination, boundary) { + var completedSegments = boundary.completedSegments; + var i = 0; + + for (; i < completedSegments.length; i++) { + var segment = completedSegments[i]; + + if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) { + i++; + completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority + // might want to write later. + + return false; + } + } + + completedSegments.splice(0, i); + return true; +} + +function flushPartiallyCompletedSegment(request, destination, boundary, segment) { + if (segment.status === FLUSHED) { + // We've already flushed this inline. + return true; + } + + var segmentID = segment.id; + + if (segmentID === -1) { + // This segment wasn't previously referred to. This happens at the root of + // a boundary. We make kind of a leap here and assume this is the root. + var rootSegmentID = segment.id = boundary.rootSegmentID; + + if (rootSegmentID === -1) { + throw new Error('A root segment ID must have been assigned by now. This is a bug in React.'); + } + + return flushSegmentContainer(request, destination, segment); + } else { + flushSegmentContainer(request, destination, segment); + return writeCompletedSegmentInstruction(destination, request.responseState, segmentID); + } +} + +function flushCompletedQueues(request, destination) { + + try { + // The structure of this is to go through each queue one by one and write + // until the sink tells us to stop. When we should stop, we still finish writing + // that item fully and then yield. At that point we remove the already completed + // items up until the point we completed them. + // TODO: Emit preloading. + // TODO: It's kind of unfortunate to keep checking this array after we've already + // emitted the root. + var completedRootSegment = request.completedRootSegment; + + if (completedRootSegment !== null && request.pendingRootTasks === 0) { + flushSegment(request, destination, completedRootSegment); + request.completedRootSegment = null; + writeCompletedRoot(destination, request.responseState); + } // We emit client rendering instructions for already emitted boundaries first. + // This is so that we can signal to the client to start client rendering them as + // soon as possible. + + + var clientRenderedBoundaries = request.clientRenderedBoundaries; + var i; + + for (i = 0; i < clientRenderedBoundaries.length; i++) { + var boundary = clientRenderedBoundaries[i]; + + if (!flushClientRenderedBoundary(request, destination, boundary)) { + request.destination = null; + i++; + clientRenderedBoundaries.splice(0, i); + return; + } + } + + clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries + // that are completely done since we can actually show them, than it is to emit + // any individual segments from a partially complete boundary. + + var completedBoundaries = request.completedBoundaries; + + for (i = 0; i < completedBoundaries.length; i++) { + var _boundary = completedBoundaries[i]; + + if (!flushCompletedBoundary(request, destination, _boundary)) { + request.destination = null; + i++; + completedBoundaries.splice(0, i); + return; + } + } + + completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before + // we continue with lower priorities. + + completeWriting(destination); + beginWriting(destination); // TODO: Here we'll emit data used by hydration. + // Next we emit any segments of any boundaries that are partially complete + // but not deeply complete. + + var partialBoundaries = request.partialBoundaries; + + for (i = 0; i < partialBoundaries.length; i++) { + var _boundary2 = partialBoundaries[i]; + + if (!flushPartialBoundary(request, destination, _boundary2)) { + request.destination = null; + i++; + partialBoundaries.splice(0, i); + return; + } + } + + partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had + // boundaries added to it in case they were too larged to be inlined. + // New ones might be added in this loop. + + var largeBoundaries = request.completedBoundaries; + + for (i = 0; i < largeBoundaries.length; i++) { + var _boundary3 = largeBoundaries[i]; + + if (!flushCompletedBoundary(request, destination, _boundary3)) { + request.destination = null; + i++; + largeBoundaries.splice(0, i); + return; + } + } + + largeBoundaries.splice(0, i); + } finally { + + if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because + // either they have pending task or they're complete. + ) { + { + if (request.abortableTasks.size !== 0) { + error('There was still abortable task at the root when we closed. This is a bug in React.'); + } + } // We're done. + + + close(destination); + } + } +} + +function startWork(request) { + scheduleWork(function () { + return performWork(request); + }); +} +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedQueues(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} // This is called to early terminate a request. It puts all pending boundaries in client rendered state. + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + abortableTasks.forEach(function (task) { + return abortTask(task, request, reason); + }); + abortableTasks.clear(); + + if (request.destination !== null) { + flushCompletedQueues(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function onError() {// Non-fatal errors are ignored. +} + +function renderToStringImpl(children, options, generateStaticMarkup, abortReason) { + var didFatal = false; + var fatalError = null; + var result = ''; + var destination = { + push: function (chunk) { + if (chunk !== null) { + result += chunk; + } + + return true; + }, + destroy: function (error) { + didFatal = true; + fatalError = error; + } + }; + var readyToStream = false; + + function onShellReady() { + readyToStream = true; + } + + var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined); + startWork(request); // If anything suspended and is still pending, we'll abort it before writing. + // That way we write only client-rendered boundaries from the start. + + abort(request, abortReason); + startFlowing(request, destination); + + if (didFatal) { + throw fatalError; + } + + if (!readyToStream) { + // Note: This error message is the one we use on the client. It doesn't + // really make sense here. But this is the legacy server renderer, anyway. + // We're going to delete it soon. + throw new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.'); + } + + return result; +} + +function renderToString(children, options) { + return renderToStringImpl(children, options, false, 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server'); +} + +function renderToStaticMarkup(children, options) { + return renderToStringImpl(children, options, true, 'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server'); +} + +function renderToNodeStream() { + throw new Error('ReactDOMServer.renderToNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToString() instead.'); +} + +function renderToStaticNodeStream() { + throw new Error('ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.'); +} + +exports.renderToNodeStream = renderToNodeStream; +exports.renderToStaticMarkup = renderToStaticMarkup; +exports.renderToStaticNodeStream = renderToStaticNodeStream; +exports.renderToString = renderToString; +exports.version = ReactVersion; + })(); +} diff --git a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js new file mode 100644 index 0000000..eca01a0 --- /dev/null +++ b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js @@ -0,0 +1,93 @@ +/** + * @license React + * react-dom-server-legacy.browser.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("react");function l(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c