commit d65bfda4e56b64c811037c2292f371a8f356ad1a Author: xiangxy Date: Tue Aug 29 15:11:11 2023 +0800 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8c45c81 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +.project +unpackage/ +.DS_Store \ No newline at end of file diff --git a/.hbuilderx/launch.json b/.hbuilderx/launch.json new file mode 100644 index 0000000..a97fd25 --- /dev/null +++ b/.hbuilderx/launch.json @@ -0,0 +1,20 @@ +{ // launch.json 配置了启动调试时相关设置,configurations下节点名称可为 app-plus/h5/mp-weixin/mp-baidu/mp-alipay/mp-qq/mp-toutiao/mp-360/ + // launchtype项可配置值为local或remote, local代表前端连本地云函数,remote代表前端连云端云函数 + "version": "0.0", + "configurations": [{ + "app-plus" : + { + "launchtype" : "local" + }, + "default" : + { + "launchtype" : "local" + }, + "h5" : + { + "launchtype" : "local" + }, + "type" : "uniCloud" + } + ] +} diff --git a/App.vue b/App.vue new file mode 100644 index 0000000..3d97b1b --- /dev/null +++ b/App.vue @@ -0,0 +1,25 @@ + + + diff --git a/common/style/layout.css b/common/style/layout.css new file mode 100644 index 0000000..cac4beb --- /dev/null +++ b/common/style/layout.css @@ -0,0 +1,370 @@ +page { + background-color: #f6f6f6 !important; + min-height: 100% !important; + height: 100% !important; +} +uni-page-body { + background-color: #f6f6f6 !important; + min-height: 100% !important; + height: 100% !important; +} +uni-button:after { + border: none; +} +/** iconfont */ +@font-face { + font-family: 'iconfont'; + src: url('@/static/iconfont/iconfont.woff2?t=1665454521636') format('woff2'), + url('@/static/iconfont/iconfont.woff?t=1665454521636') format('woff'), + url('@/static/iconfont/iconfont.ttf?t=1665454521636') format('truetype'); +} +.iconfont { + font-family: "iconfont" !important; + font-size: 50rpx; + color: #000; + font-style: normal; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +.icon_eye_close { + color: #bbb; +} +.icon_eye_active { + color: #ff6a00; +} +.icon_unchecked { + color: #fff; + width: 32rpx; + height: 32rpx; + background-color: #fff; + font-size: 24rpx; + border: 1rpx solid #bbb; +} +.icon_checked { + color: #ff6a00; + border: 1rpx solid #ff6a00; +} +.icon_back { + font-size: 52rpx; + line-height: 52rpx; + color: #fff; +} +.icon_home { + font-size: 52rpx; + line-height: 52rpx; + color: #fff; +} +.icon_scan { + width: 42rpx; + height: 48rpx; + font-size: 40rpx; + line-height: 48rpx; + color: #323232; + text-align: center; +} +.icon_phone { + width: 48rpx; + height: 48rpx; + font-size: 36rpx; + line-height: 48rpx; + color: #323232; + text-align: center; +} +.icon_del { + width: 46rpx; + height: 48rpx; + font-size: 46rpx; + line-height: 48rpx; + color: #323232; + text-align: center; +} +.icon_search { + width: 48rpx; + height: 48rpx; + font-size: 40rpx; + color: #323232; + line-height: 48rpx; +} +.cancel_icon::before { + content: "\e6dc"; +} +.cancel_icon { + display: block; + width: 100rpx; + height: 100rpx; + font-size: 50rpx; + color: #fff; + line-height: 100rpx; + text-align: center; + background-color: #E9B451; +} + +/** 内容 */ +.zd_container { + width: 100%; + height: 100%; +} +.zd_content { + width: 100%; + height: auto; + padding: 92rpx 15rpx 82rpx 14rpx; +} +.zd_wrapper { + width: 100%; + height: auto; + background-color: #fff; + border-radius: 24rpx; + padding: 14rpx; + margin-bottom: 20rpx; +} +.filter_item { + display: flex; + align-items: center; + width: 100%; + margin-bottom: 10rpx; +} +.filter_item:last-child { + margin-bottom: 0; +} +.filter_label_wraper { + flex: none; + width: 140rpx; + text-align:justify; + text-align-last: justify; + text-justify: inter-ideograph;/*兼容ie*/ +} +.filter_label { + display: block; + width: 140rpx; + line-height: 80rpx; + font-size: 28rpx; + color: #323232; + text-align:justify; + text-align-last: justify; + text-justify: inter-ideograph;/*兼容ie*/ +} +.filter_label_1 { + line-height: 30rpx; +} +.filter_search { + width: 100rpx; + height: 70rpx; + line-height: 70rpx; + font-size: 28rpx; + color: #323232; + text-align: center; + background-color: #fff; + border: 1px solid #ff6a00; + border-radius: 10rpx; + margin-left: 30rpx; +} +.filter_search_disabled { + background-color: #dcdfe6; + border: 1px solid #dcdfe6; + color: #fff; +} +.filter_input_wraper { + /* flex: 1; */ + width: calc(100% - 170rpx); + height: 80rpx; + padding: 5rpx 0; + margin-left: 30rpx; + display: flex; + justify-content: flex-start; + align-items: center; +} +.filter_input_wraper_1 { + height: 30rpx; +} +.filter_input_wraper_inn_text { + line-height: 30rpx; + font-size: 28rpx; + color: #606266; + margin-left: 10rpx; +} +.filter_input { + width: 100%; + height: 70rpx; + line-height: 70rpx; + border: 1px solid #dcdfe6; + background-color: #fff; + padding: 0 15rpx; + font-size: 28rpx; + color: #606266; + border-radius: 10rpx; +} +.filter_textarea { + width: 100%; + height: 210rpx; + line-height: 70rpx; + border: 1px solid #dcdfe6; + background-color: #fff; + padding: 0 15rpx; + font-size: 28rpx; + color: #606266; + border-radius: 10rpx; +} +.filter_input_disabled { + background-color: #eee; +} + +.grid-wraper { + width: 100%; +} +.slide_new { + width: 100%; + height: 100%; + overflow-y: auto; +} +.slide_new table { + table-layout: fixed; + min-width: 100%; + border-collapse: separate; + border-spacing: 0; + border: 0; +} +.slide_new table td, .slide_new table th { + box-sizing: border-box; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + white-space: nowrap; + padding: 0 20rpx; + border-bottom: 10rpx solid #f5f5f5; + text-align: center; +} +.slide_new table td:first-child, .slide_new table th:first-child{ + position: sticky; + left: 0; + z-index: 101; +} +.slide_new table thead tr th { + position: sticky; + top: 0; + background: #d7d7d7; + font-size: 26rpx; + line-height: 98rpx; + color: #696969; + font-weight: bold; + z-index: 100; +} +.slide_new table thead tr th:first-child { + background: #d7d7d7; +} +.slide_new table tbody tr td { + font-size: 28rpx; + line-height: 98rpx; + color: #323232; + background: #fff; +} +.slide_new table tbody tr.checked td { + background-color: #fef6e4; +} + +/** 提交栏 **/ +.submit-bar { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + align-items: center; + position: fixed; + bottom: 0; + left: 0; + width: 100%; + z-index: 200; + background-color: #fff; + padding-top: 10rpx; + box-shadow: 0 0 20rpx 0 rgba(160,160,160,0.7); +} +.submit-button { + font-size: 30rpx; + line-height: 62rpx; + color: #ff6a00; + text-align: center; + letter-spacing: 1rpx; + padding: 0 22rpx; + background-color: #fff; + border: 1px solid #ff6a00; + margin: 0 40rpx 10rpx 0; + border-radius: 30rpx; +} +.btn-disabled, .submit-button:disabled { + background-color: #c9c9c9; + border: 1px solid #c9c9c9; + color: #fff; +} + +/** 下拉框 */ +.uni-select__selector { + z-index: 300 !important; +} + +/** 弹窗 */ +.msg_wrapper { + position: fixed; + top: 0; + bottom: 0; + left: 0; + right: 0; + text-align: center; + z-index: 201; + display: flex; + justify-content: center; + align-items: center; +} +.msg_wrapper_1 { + text-align: left; +} + +.msg_box { + width: 90%; + padding: 20rpx; + background-color: #fff; + border-radius: 4px; + border: 1px solid #ebeef5; + box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%); + backface-visibility: hidden; +} + +.msg_mask { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + opacity: .7; + background: #000; + z-index: 200; +} + +.msg_btns { + width: 100%; + max-width: 300px; + margin: 40rpx auto 0; + display: flex; + justify-content: space-between; + align-items: center; +} +.msg_btn { + border-radius: 10rpx; +} +.msg_btn:disabled { + background-color: #c9c9c9; +} +.uni-select__input-placeholder,.uni-select__selector-empty, .uni-select__selector-item { + font-size: 28rpx !important +} +.sin_input { + width: 150rpx; + font-size: 28rpx; + line-height: 150rpx; + height: 68rpx; + color: #323232; + padding: 0 .1rem; + border: 1px solid #a1a1a1; + border-radius: 3px; +} +.layout-t tr.checked td .sin_input { + color: #8a8a8a; + border: 1px solid #ffffff; +} \ No newline at end of file diff --git a/common/style/mixin.styl b/common/style/mixin.styl new file mode 100644 index 0000000..f564d40 --- /dev/null +++ b/common/style/mixin.styl @@ -0,0 +1,51 @@ +$red = #ff6a00 +$green = #6CBE8B +$yellow = #E9B451 +$blue = #6798ef +$gray = #c9c9c9 +$fc1 = #323232 + +.bgred + background-color: $red !important +.bggreen + background-color: $green !important +.bgyellow + background-color: $yellow !important +.bgblue + background-color: $blue !important +.bggray + background-color: $gray !important + +//宽高 +_wh(w, h) + width: w + height: h + +//字体大小、行高、颜色 +_font(size,height,color=$fc1,weight=normal,align=left) + font-size: size + line-height: height + color: color + font-weight: weight + text-align: align + +//flex 布局和 子元素 对其方式 +_fj(x=space-between,y=center,r=row,n=nowrap) + display: flex + justify-content: x + align-items: y + flex-direction: r + flex-wrap: n + +// 背景图片地址和大小 +_bis(url,w,h=auto,x=center,y=center) + background-position: x y + background-size: w h + background-image: url(url) + background-repeat: no-repeat + +// 定位上下居中 +_ct() + position: absolute + top: 50% + transform: translateY(-50%) \ No newline at end of file diff --git a/common/style/reset.css b/common/style/reset.css new file mode 100644 index 0000000..8355389 --- /dev/null +++ b/common/style/reset.css @@ -0,0 +1,43 @@ +* { + padding: 0; + margin: 0; + list-style: none; + font-style: normal; + text-decoration: none; + border: none; + outline: none; + font-family: uniicons, Arial, "Microsoft Yahei", "Helvetica Neue", Helvetica, sans-serif; + box-sizing: border-box; + -webkit-box-sizing: border-box; + -webkit-tap-highlight-color:transparent; + -webkit-font-smoothing: antialiased; +} + +body, html { + -webkit-user-select: auto; + -ms-user-select: auto; + user-select: auto; +} + +input[type="button"], input[type="submit"], input[type="search"], input[type="reset"], textarea, select{ + -webkit-appearance: none; + appearance: none; +} + +.relative { + position: relative; +} +.hide { + display: none; +} +.vhide { + visibility:hidden; +} +.show { + display: block; +} +.ellipsis{ + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} \ No newline at end of file diff --git a/common/style/uni.css b/common/style/uni.css new file mode 100644 index 0000000..c72ebf0 --- /dev/null +++ b/common/style/uni.css @@ -0,0 +1,12 @@ +@font-face { + font-family: uniicons; + font-weight: normal; + font-style: normal; + src: url('~@/static/uni.ttf') format('truetype'); +} +.iconfont{ + font-family: uni; + text-decoration: none; + text-align: center; +} + diff --git a/components/NavBar.vue b/components/NavBar.vue new file mode 100644 index 0000000..a03af93 --- /dev/null +++ b/components/NavBar.vue @@ -0,0 +1,62 @@ + + + + + diff --git a/components/SearchBox.vue b/components/SearchBox.vue new file mode 100644 index 0000000..7525607 --- /dev/null +++ b/components/SearchBox.vue @@ -0,0 +1,138 @@ + + + + + diff --git a/components/SearchBox1.vue b/components/SearchBox1.vue new file mode 100644 index 0000000..63134f7 --- /dev/null +++ b/components/SearchBox1.vue @@ -0,0 +1,110 @@ + + + + + diff --git a/index.html b/index.html new file mode 100644 index 0000000..c3ff205 --- /dev/null +++ b/index.html @@ -0,0 +1,20 @@ + + + + + + + + + + +
+ + + diff --git a/main.js b/main.js new file mode 100644 index 0000000..1abc647 --- /dev/null +++ b/main.js @@ -0,0 +1,36 @@ +import App from './App' +import Vue from 'vue' + +Vue.config.productionTip = false +App.mpType = 'app' + +Vue.directive('enterNumber', { + inserted: function (el) { + el.addEventListener("keypress",function(e){ + e = e || window.event; + let charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode; + // if (parseInt(e.target.value) == 0) { + // e.preventDefault(); + // } + parseInt(e.target.value) == 0 && e.preventDefault(); + let re = /\d/; + if(!re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey){ + if(e.preventDefault){ + e.preventDefault(); + }else{ + e.returnValue = false; + } + } + }); + } +}); + +import store from '@/vuex/store.js' + +const app = new Vue({ + ...App, + store +}) + + +app.$mount() \ No newline at end of file diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..a164fa8 --- /dev/null +++ b/manifest.json @@ -0,0 +1,113 @@ +{ + "name" : "瑞泰马钢", + "appid" : "__UNI__B3AA5BE", + "description" : "瑞泰马钢手持系统", + "versionName" : "1.0.0", + "versionCode" : 100, + "transformPx" : false, + /* 5+App特有相关 */ + "app-plus" : { + "usingComponents" : true, + "nvueStyleCompiler" : "uni-app", + "compilerVersion" : 3, + "splashscreen" : { + "alwaysShowBeforeRender" : true, + "waiting" : true, + "autoclose" : true, + "delay" : 0 + }, + /* 模块配置 */ + "modules" : {}, + /* 应用发布信息 */ + "distribute" : { + /* android打包配置 */ + "android" : { + "permissions" : [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ] + }, + /* ios打包配置 */ + "ios" : { + "dSYMs" : false + }, + /* SDK配置 */ + "sdkConfigs" : { + "ad" : {} + }, + "icons" : { + "android" : { + "hdpi" : "unpackage/res/icons/72x72.png", + "xhdpi" : "unpackage/res/icons/96x96.png", + "xxhdpi" : "unpackage/res/icons/144x144.png", + "xxxhdpi" : "unpackage/res/icons/192x192.png" + }, + "ios" : { + "appstore" : "unpackage/res/icons/1024x1024.png", + "ipad" : { + "app" : "unpackage/res/icons/76x76.png", + "app@2x" : "unpackage/res/icons/152x152.png", + "notification" : "unpackage/res/icons/20x20.png", + "notification@2x" : "unpackage/res/icons/40x40.png", + "proapp@2x" : "unpackage/res/icons/167x167.png", + "settings" : "unpackage/res/icons/29x29.png", + "settings@2x" : "unpackage/res/icons/58x58.png", + "spotlight" : "unpackage/res/icons/40x40.png", + "spotlight@2x" : "unpackage/res/icons/80x80.png" + }, + "iphone" : { + "app@2x" : "unpackage/res/icons/120x120.png", + "app@3x" : "unpackage/res/icons/180x180.png", + "notification@2x" : "unpackage/res/icons/40x40.png", + "notification@3x" : "unpackage/res/icons/60x60.png", + "settings@2x" : "unpackage/res/icons/58x58.png", + "settings@3x" : "unpackage/res/icons/87x87.png", + "spotlight@2x" : "unpackage/res/icons/80x80.png", + "spotlight@3x" : "unpackage/res/icons/120x120.png" + } + } + } + } + }, + /* 快应用特有相关 */ + "quickapp" : {}, + /* 小程序特有相关 */ + "mp-weixin" : { + "appid" : "", + "setting" : { + "urlCheck" : false + }, + "usingComponents" : true + }, + "mp-alipay" : { + "usingComponents" : true + }, + "mp-baidu" : { + "usingComponents" : true + }, + "mp-toutiao" : { + "usingComponents" : true + }, + "uniStatistics" : { + "enable" : false + }, + "vueVersion" : "2", + "h5" : { + "router" : { + "base" : "./" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..7542a27 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "jsencrypt": "^3.2.1" + } +} diff --git a/pages.json b/pages.json new file mode 100644 index 0000000..ae030a4 --- /dev/null +++ b/pages.json @@ -0,0 +1,42 @@ +{ + "pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages + { + "path" : "pages/login/login", + "style": { + "navigationStyle": "custom" + } + } + ,{ + "path" : "pages/home/home", + "style": { + "navigationStyle": "custom" + } + } + ,{ + "path" : "pages/login/setup", + "style": { + "navigationStyle": "custom" + } + } + ,{ + "path" : "pages/login/upgrade", + "style": { + "navigationStyle": "custom" + } + }, + { + "path" : "pages/modules/equip-inspection", + "style": { + "navigationStyle": "custom" + } + } + ], + "globalStyle": { + // "pageOrientation": "landscape", + "navigationBarTextStyle": "white", + "navigationBarTitleText": "uni-app", + "navigationBarBackgroundColor": "#d7592f", + "backgroundColor": "#ffffff" + }, + "uniIdRouter": {} +} diff --git a/pages/home/home.vue b/pages/home/home.vue new file mode 100644 index 0000000..1ecc8b6 --- /dev/null +++ b/pages/home/home.vue @@ -0,0 +1,175 @@ + + + + + diff --git a/pages/login/login.vue b/pages/login/login.vue new file mode 100644 index 0000000..0477dc8 --- /dev/null +++ b/pages/login/login.vue @@ -0,0 +1,190 @@ + + + + + diff --git a/pages/login/setup.vue b/pages/login/setup.vue new file mode 100644 index 0000000..02851bb --- /dev/null +++ b/pages/login/setup.vue @@ -0,0 +1,105 @@ + + + + + diff --git a/pages/login/upgrade.vue b/pages/login/upgrade.vue new file mode 100644 index 0000000..b6bc9f5 --- /dev/null +++ b/pages/login/upgrade.vue @@ -0,0 +1,229 @@ + + + + + diff --git a/pages/modules/equip-inspection.vue b/pages/modules/equip-inspection.vue new file mode 100644 index 0000000..cfe8fb3 --- /dev/null +++ b/pages/modules/equip-inspection.vue @@ -0,0 +1,124 @@ + + + + + diff --git a/static/iconfont/iconfont.ttf b/static/iconfont/iconfont.ttf new file mode 100644 index 0000000..b68f8e9 Binary files /dev/null and b/static/iconfont/iconfont.ttf differ diff --git a/static/iconfont/iconfont.woff b/static/iconfont/iconfont.woff new file mode 100644 index 0000000..655b9ec Binary files /dev/null and b/static/iconfont/iconfont.woff differ diff --git a/static/iconfont/iconfont.woff2 b/static/iconfont/iconfont.woff2 new file mode 100644 index 0000000..c634af4 Binary files /dev/null and b/static/iconfont/iconfont.woff2 differ diff --git a/static/image/app_update_close.png b/static/image/app_update_close.png new file mode 100644 index 0000000..8b2ffe6 Binary files /dev/null and b/static/image/app_update_close.png differ diff --git a/static/image/bg_top.png b/static/image/bg_top.png new file mode 100644 index 0000000..015f698 Binary files /dev/null and b/static/image/bg_top.png differ diff --git a/static/image/exit.png b/static/image/exit.png new file mode 100644 index 0000000..fefa052 Binary files /dev/null and b/static/image/exit.png differ diff --git a/static/image/info_bg.png b/static/image/info_bg.png new file mode 100644 index 0000000..8f7e000 Binary files /dev/null and b/static/image/info_bg.png differ diff --git a/static/image/login_bg.png b/static/image/login_bg.png new file mode 100644 index 0000000..680a940 Binary files /dev/null and b/static/image/login_bg.png differ diff --git a/static/image/menu/RF01.png b/static/image/menu/RF01.png new file mode 100644 index 0000000..4de6e93 Binary files /dev/null and b/static/image/menu/RF01.png differ diff --git a/static/image/menu/RF02.png b/static/image/menu/RF02.png new file mode 100644 index 0000000..450da60 Binary files /dev/null and b/static/image/menu/RF02.png differ diff --git a/static/image/menu/RF03.png b/static/image/menu/RF03.png new file mode 100644 index 0000000..44fa467 Binary files /dev/null and b/static/image/menu/RF03.png differ diff --git a/static/image/menu/RF04.png b/static/image/menu/RF04.png new file mode 100644 index 0000000..d2b969b Binary files /dev/null and b/static/image/menu/RF04.png differ diff --git a/static/image/menu/RF05.png b/static/image/menu/RF05.png new file mode 100644 index 0000000..775f2e8 Binary files /dev/null and b/static/image/menu/RF05.png differ diff --git a/static/image/menu/RF06.png b/static/image/menu/RF06.png new file mode 100644 index 0000000..af989ff Binary files /dev/null and b/static/image/menu/RF06.png differ diff --git a/static/image/menu/RF07.png b/static/image/menu/RF07.png new file mode 100644 index 0000000..796026f Binary files /dev/null and b/static/image/menu/RF07.png differ diff --git a/static/image/menu/RF08.png b/static/image/menu/RF08.png new file mode 100644 index 0000000..30c871f Binary files /dev/null and b/static/image/menu/RF08.png differ diff --git a/static/image/menu/RF09.png b/static/image/menu/RF09.png new file mode 100644 index 0000000..972a492 Binary files /dev/null and b/static/image/menu/RF09.png differ diff --git a/static/image/menu/RF10.png b/static/image/menu/RF10.png new file mode 100644 index 0000000..15c177a Binary files /dev/null and b/static/image/menu/RF10.png differ diff --git a/static/uni.ttf b/static/uni.ttf new file mode 100644 index 0000000..60a1968 Binary files /dev/null and b/static/uni.ttf differ diff --git a/uni.scss b/uni.scss new file mode 100644 index 0000000..a9a742d --- /dev/null +++ b/uni.scss @@ -0,0 +1,76 @@ +/** + * 这里是uni-app内置的常用样式变量 + * + * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量 + * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App + * + */ + +/** + * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能 + * + * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件 + */ + +/* 颜色变量 */ + +/* 行为相关颜色 */ +$uni-color-primary: #007aff; +$uni-color-success: #4cd964; +$uni-color-warning: #f0ad4e; +$uni-color-error: #dd524d; + +/* 文字基本颜色 */ +$uni-text-color:#333;//基本色 +$uni-text-color-inverse:#fff;//反色 +$uni-text-color-grey:#999;//辅助灰色,如加载更多的提示信息 +$uni-text-color-placeholder: #808080; +$uni-text-color-disable:#c0c0c0; + +/* 背景颜色 */ +$uni-bg-color:#ffffff; +$uni-bg-color-grey:#f8f8f8; +$uni-bg-color-hover:#f1f1f1;//点击状态颜色 +$uni-bg-color-mask:rgba(0, 0, 0, 0.4);//遮罩颜色 + +/* 边框颜色 */ +$uni-border-color:#c8c7cc; + +/* 尺寸变量 */ + +/* 文字尺寸 */ +$uni-font-size-sm:12px; +$uni-font-size-base:14px; +$uni-font-size-lg:16; + +/* 图片尺寸 */ +$uni-img-size-sm:20px; +$uni-img-size-base:26px; +$uni-img-size-lg:40px; + +/* Border Radius */ +$uni-border-radius-sm: 2px; +$uni-border-radius-base: 3px; +$uni-border-radius-lg: 6px; +$uni-border-radius-circle: 50%; + +/* 水平间距 */ +$uni-spacing-row-sm: 5px; +$uni-spacing-row-base: 10px; +$uni-spacing-row-lg: 15px; + +/* 垂直间距 */ +$uni-spacing-col-sm: 4px; +$uni-spacing-col-base: 8px; +$uni-spacing-col-lg: 12px; + +/* 透明度 */ +$uni-opacity-disabled: 0.3; // 组件禁用态的透明度 + +/* 文章场景相关 */ +$uni-color-title: #2C405A; // 文章标题颜色 +$uni-font-size-title:20px; +$uni-color-subtitle: #555555; // 二级标题颜色 +$uni-font-size-subtitle:26px; +$uni-color-paragraph: #3F536E; // 文章段落颜色 +$uni-font-size-paragraph:15px; diff --git a/uniCloud-aliyun/database/JQL查询.jql b/uniCloud-aliyun/database/JQL查询.jql new file mode 100644 index 0000000..35d21de --- /dev/null +++ b/uniCloud-aliyun/database/JQL查询.jql @@ -0,0 +1,12 @@ +// 本文件用于,使用JQL语法操作项目关联的uniCloud空间的数据库,方便开发调试和远程数据库管理 +// 编写clientDB的js API(也支持常规js语法,比如var),可以对云数据库进行增删改查操作。不支持uniCloud-db组件写法 +// 可以全部运行,也可以选中部分代码运行。点击工具栏上的运行按钮或者按下【F5】键运行代码 +// 如果文档中存在多条JQL语句,只有最后一条语句生效 +// 如果混写了普通js,最后一条语句需是数据库操作语句 +// 此处代码运行不受DB Schema的权限控制,移植代码到实际业务中注意在schema中配好permission +// 不支持clientDB的action +// 数据库查询有最大返回条数限制,详见:https://uniapp.dcloud.net.cn/uniCloud/cf-database.html#limit +// 详细JQL语法,请参考:https://uniapp.dcloud.net.cn/uniCloud/jql.html + +// 下面示例查询uni-id-users表的所有数据 +db.collection('uni-id-users').get(); diff --git a/uni_modules/uni-config-center/changelog.md b/uni_modules/uni-config-center/changelog.md new file mode 100644 index 0000000..4d2eb92 --- /dev/null +++ b/uni_modules/uni-config-center/changelog.md @@ -0,0 +1,4 @@ +## 0.0.2(2021-04-16) +- 修改插件package信息 +## 0.0.1(2021-03-15) +- 初始化项目 diff --git a/uni_modules/uni-config-center/package.json b/uni_modules/uni-config-center/package.json new file mode 100644 index 0000000..d97bd27 --- /dev/null +++ b/uni_modules/uni-config-center/package.json @@ -0,0 +1,80 @@ +{ + "id": "uni-config-center", + "displayName": "uni-config-center", + "version": "0.0.2", + "description": "uniCloud 配置中心", + "keywords": [ + "配置", + "配置中心" +], + "repository": "", + "engines": { + "HBuilderX": "^3.1.0" + }, + "dcloudext": { + "category": [ + "uniCloud", + "云函数模板" + ], + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "无", + "permissions": "无" + }, + "npmurl": "" + }, + "directories": { + "example": "../../../scripts/dist" + }, + "uni_modules": { + "dependencies": [], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y" + }, + "client": { + "App": { + "app-vue": "u", + "app-nvue": "u" + }, + "H5-mobile": { + "Safari": "u", + "Android Browser": "u", + "微信浏览器(Android)": "u", + "QQ浏览器(Android)": "u" + }, + "H5-pc": { + "Chrome": "u", + "IE": "u", + "Edge": "u", + "Firefox": "u", + "Safari": "u" + }, + "小程序": { + "微信": "u", + "阿里": "u", + "百度": "u", + "字节跳动": "u", + "QQ": "u" + }, + "快应用": { + "华为": "u", + "联盟": "u" + } + } + } + } +} diff --git a/uni_modules/uni-config-center/readme.md b/uni_modules/uni-config-center/readme.md new file mode 100644 index 0000000..0bd8ac4 --- /dev/null +++ b/uni_modules/uni-config-center/readme.md @@ -0,0 +1,93 @@ +# 为什么使用uni-config-center + +实际开发中很多插件需要配置文件才可以正常运行,如果每个插件都单独进行配置的话就会产生下面这样的目录结构 + +```bash +cloudfunctions +└─────common 公共模块 + ├─plugin-a // 插件A对应的目录 + │ ├─index.js + │ ├─config.json // plugin-a对应的配置文件 + │ └─other-file.cert // plugin-a依赖的其他文件 + └─plugin-b // plugin-b对应的目录 + ├─index.js + └─config.json // plugin-b对应的配置文件 +``` + +假设插件作者要发布一个项目模板,里面使用了很多需要配置的插件,无论是作者发布还是用户使用都是一个大麻烦。 + +uni-config-center就是用了统一管理这些配置文件的,使用uni-config-center后的目录结构如下 + +```bash +cloudfunctions +└─────common 公共模块 + ├─plugin-a // 插件A对应的目录 + │ └─index.js + ├─plugin-b // plugin-b对应的目录 + │ └─index.js + └─uni-config-center + ├─index.js // config-center入口文件 + ├─plugin-a + │ ├─config.json // plugin-a对应的配置文件 + │ └─other-file.cert // plugin-a依赖的其他文件 + └─plugin-b + └─config.json // plugin-b对应的配置文件 +``` + +使用uni-config-center后的优势 + +- 配置文件统一管理,分离插件主体和配置信息,更新插件更方便 +- 支持对config.json设置schema,插件使用者在HBuilderX内编写config.json文件时会有更好的提示(后续HBuilderX会提供支持) + +# 用法 + +在要使用uni-config-center的公共模块或云函数内引入uni-config-center依赖,请参考:[使用公共模块](https://uniapp.dcloud.net.cn/uniCloud/cf-common) + +```js +const createConfig = require('uni-config-center') + +const uniIdConfig = createConfig({ + pluginId: 'uni-id', // 插件id + defaultConfig: { // 默认配置 + tokenExpiresIn: 7200, + tokenExpiresThreshold: 600, + }, + customMerge: function(defaultConfig, userConfig) { // 自定义默认配置和用户配置的合并规则,不设置的情况侠会对默认配置和用户配置进行深度合并 + // defaudltConfig 默认配置 + // userConfig 用户配置 + return Object.assign(defaultConfig, userConfig) + } +}) + + +// 以如下配置为例 +// { +// "tokenExpiresIn": 7200, +// "passwordErrorLimit": 6, +// "bindTokenToDevice": false, +// "passwordErrorRetryTime": 3600, +// "app-plus": { +// "tokenExpiresIn": 2592000 +// }, +// "service": { +// "sms": { +// "codeExpiresIn": 300 +// } +// } +// } + +// 获取配置 +uniIdConfig.config() // 获取全部配置,注意:uni-config-center内不存在对应插件目录时会返回空对象 +uniIdConfig.config('tokenExpiresIn') // 指定键值获取配置,返回:7200 +uniIdConfig.config('service.sms.codeExpiresIn') // 指定键值获取配置,返回:300 +uniIdConfig.config('tokenExpiresThreshold', 600) // 指定键值获取配置,如果不存在则取传入的默认值,返回:600 + +// 获取文件绝对路径 +uniIdConfig.resolve('custom-token.js') // 获取uni-config-center/uni-id/custom-token.js文件的路径 + +// 引用文件(require) +uniIDConfig.requireFile('custom-token.js') // 使用require方式引用uni-config-center/uni-id/custom-token.js文件。文件不存在时返回undefined,文件内有其他错误导致require失败时会抛出错误。 + +// 判断是否包含某文件 +uniIDConfig.hasFile('custom-token.js') // 配置目录是否包含某文件,true: 文件存在,false: 文件不存在 +``` \ No newline at end of file diff --git a/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js b/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js new file mode 100644 index 0000000..e14fb3b --- /dev/null +++ b/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js @@ -0,0 +1 @@ +"use strict";var t=require("fs"),r=require("path");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=e(t),o=e(r),i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var u=function(t){var r={exports:{}};return t(r,r.exports),r.exports}((function(t,r){var e="__lodash_hash_undefined__",n=9007199254740991,o="[object Arguments]",u="[object Function]",c="[object Object]",a=/^\[object .+?Constructor\]$/,f=/^(?:0|[1-9]\d*)$/,s={};s["[object Float32Array]"]=s["[object Float64Array]"]=s["[object Int8Array]"]=s["[object Int16Array]"]=s["[object Int32Array]"]=s["[object Uint8Array]"]=s["[object Uint8ClampedArray]"]=s["[object Uint16Array]"]=s["[object Uint32Array]"]=!0,s[o]=s["[object Array]"]=s["[object ArrayBuffer]"]=s["[object Boolean]"]=s["[object DataView]"]=s["[object Date]"]=s["[object Error]"]=s[u]=s["[object Map]"]=s["[object Number]"]=s[c]=s["[object RegExp]"]=s["[object Set]"]=s["[object String]"]=s["[object WeakMap]"]=!1;var l="object"==typeof i&&i&&i.Object===Object&&i,h="object"==typeof self&&self&&self.Object===Object&&self,p=l||h||Function("return this")(),_=r&&!r.nodeType&&r,v=_&&t&&!t.nodeType&&t,d=v&&v.exports===_,y=d&&l.process,g=function(){try{var t=v&&v.require&&v.require("util").types;return t||y&&y.binding&&y.binding("util")}catch(t){}}(),b=g&&g.isTypedArray;function j(t,r,e){switch(e.length){case 0:return t.call(r);case 1:return t.call(r,e[0]);case 2:return t.call(r,e[0],e[1]);case 3:return t.call(r,e[0],e[1],e[2])}return t.apply(r,e)}var w,O,m,A=Array.prototype,z=Function.prototype,M=Object.prototype,x=p["__core-js_shared__"],C=z.toString,F=M.hasOwnProperty,U=(w=/[^.]+$/.exec(x&&x.keys&&x.keys.IE_PROTO||""))?"Symbol(src)_1."+w:"",S=M.toString,I=C.call(Object),P=RegExp("^"+C.call(F).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),T=d?p.Buffer:void 0,q=p.Symbol,E=p.Uint8Array,$=T?T.allocUnsafe:void 0,D=(O=Object.getPrototypeOf,m=Object,function(t){return O(m(t))}),k=Object.create,B=M.propertyIsEnumerable,N=A.splice,L=q?q.toStringTag:void 0,R=function(){try{var t=_t(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),G=T?T.isBuffer:void 0,V=Math.max,W=Date.now,H=_t(p,"Map"),J=_t(Object,"create"),K=function(){function t(){}return function(r){if(!Mt(r))return{};if(k)return k(r);t.prototype=r;var e=new t;return t.prototype=void 0,e}}();function Q(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},X.prototype.set=function(t,r){var e=this.__data__,n=nt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this},Y.prototype.clear=function(){this.size=0,this.__data__={hash:new Q,map:new(H||X),string:new Q}},Y.prototype.delete=function(t){var r=pt(this,t).delete(t);return this.size-=r?1:0,r},Y.prototype.get=function(t){return pt(this,t).get(t)},Y.prototype.has=function(t){return pt(this,t).has(t)},Y.prototype.set=function(t,r){var e=pt(this,t),n=e.size;return e.set(t,r),this.size+=e.size==n?0:1,this},Z.prototype.clear=function(){this.__data__=new X,this.size=0},Z.prototype.delete=function(t){var r=this.__data__,e=r.delete(t);return this.size=r.size,e},Z.prototype.get=function(t){return this.__data__.get(t)},Z.prototype.has=function(t){return this.__data__.has(t)},Z.prototype.set=function(t,r){var e=this.__data__;if(e instanceof X){var n=e.__data__;if(!H||n.length<199)return n.push([t,r]),this.size=++e.size,this;e=this.__data__=new Y(n)}return e.set(t,r),this.size=e.size,this};var it,ut=function(t,r,e){for(var n=-1,o=Object(t),i=e(t),u=i.length;u--;){var c=i[it?u:++n];if(!1===r(o[c],c,o))break}return t};function ct(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":L&&L in Object(t)?function(t){var r=F.call(t,L),e=t[L];try{t[L]=void 0;var n=!0}catch(t){}var o=S.call(t);n&&(r?t[L]=e:delete t[L]);return o}(t):function(t){return S.call(t)}(t)}function at(t){return xt(t)&&ct(t)==o}function ft(t){return!(!Mt(t)||function(t){return!!U&&U in t}(t))&&(At(t)?P:a).test(function(t){if(null!=t){try{return C.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function st(t){if(!Mt(t))return function(t){var r=[];if(null!=t)for(var e in Object(t))r.push(e);return r}(t);var r=dt(t),e=[];for(var n in t)("constructor"!=n||!r&&F.call(t,n))&&e.push(n);return e}function lt(t,r,e,n,o){t!==r&&ut(r,(function(i,u){if(o||(o=new Z),Mt(i))!function(t,r,e,n,o,i,u){var a=yt(t,e),f=yt(r,e),s=u.get(f);if(s)return void rt(t,e,s);var l=i?i(a,f,e+"",t,r,u):void 0,h=void 0===l;if(h){var p=wt(f),_=!p&&mt(f),v=!p&&!_&&Ct(f);l=f,p||_||v?wt(a)?l=a:xt(j=a)&&Ot(j)?l=function(t,r){var e=-1,n=t.length;r||(r=Array(n));for(;++e-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(R?function(t,r){return R(t,"toString",{configurable:!0,enumerable:!1,value:(e=r,function(){return e}),writable:!0});var e}:It);function bt(t,r){return t===r||t!=t&&r!=r}var jt=at(function(){return arguments}())?at:function(t){return xt(t)&&F.call(t,"callee")&&!B.call(t,"callee")},wt=Array.isArray;function Ot(t){return null!=t&&zt(t.length)&&!At(t)}var mt=G||function(){return!1};function At(t){if(!Mt(t))return!1;var r=ct(t);return r==u||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}function zt(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=n}function Mt(t){var r=typeof t;return null!=t&&("object"==r||"function"==r)}function xt(t){return null!=t&&"object"==typeof t}var Ct=b?function(t){return function(r){return t(r)}}(b):function(t){return xt(t)&&zt(t.length)&&!!s[ct(t)]};function Ft(t){return Ot(t)?tt(t,!0):st(t)}var Ut,St=(Ut=function(t,r,e){lt(t,r,e)},ht((function(t,r){var e=-1,n=r.length,o=n>1?r[n-1]:void 0,i=n>2?r[2]:void 0;for(o=Ut.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,r,e){if(!Mt(e))return!1;var n=typeof r;return!!("number"==n?Ot(e)&&vt(r,e.length):"string"==n&&r in e)&&bt(e[r],t)}(r[0],r[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++ec.call(t,r);class f{constructor({pluginId:t,defaultConfig:r={},customMerge:e,root:n}){this.pluginId=t,this.defaultConfig=r,this.pluginConfigPath=o.default.resolve(n||__dirname,t),this.customMerge=e,this._config=void 0}resolve(t){return o.default.resolve(this.pluginConfigPath,t)}hasFile(t){return n.default.existsSync(this.resolve(t))}requireFile(t){try{return require(this.resolve(t))}catch(t){if("MODULE_NOT_FOUND"===t.code)return;throw t}}_getUserConfig(){return this.requireFile("config.json")}config(t,r){this._config||(this._config=(this.customMerge||u)(this.defaultConfig,this._getUserConfig()));let e=this._config;return t?function(t,r,e){if("number"==typeof r)return t[r];if("symbol"==typeof r)return a(t,r)?t[r]:e;const n="string"!=typeof(o=r)?o:o.split(".").reduce(((t,r)=>(r.split(/\[([^}]+)\]/g).forEach((r=>r&&t.push(r))),t)),[]);var o;let i=t;for(let t=0;t + + {{label + ':'}} + + + + {{current}} + {{typePlaceholder}} + + + + + + + + + + {{emptyTips}} + + + {{formatItemName(item)}} + + + + + + + + + + + diff --git a/uni_modules/uni-data-select/package.json b/uni_modules/uni-data-select/package.json new file mode 100644 index 0000000..131c808 --- /dev/null +++ b/uni_modules/uni-data-select/package.json @@ -0,0 +1,88 @@ +{ + "id": "uni-data-select", + "displayName": "uni-data-select 下拉框选择器", + "version": "0.1.6", + "description": "通过数据驱动的下拉框选择器", + "keywords": [ + "uni-ui", + "select", + "uni-data-select", + "下拉框", + "下拉选" +], + "repository": "https://github.com/dcloudio/uni-ui", + "engines": { + "HBuilderX": "^3.1.1" + }, + "directories": { + "example": "../../temps/example_temps" + }, + "dcloudext": { + "category": [ + "前端组件", + "通用组件" + ], + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "无", + "permissions": "无" + }, + "npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui" + }, + "uni_modules": { + "dependencies": ["uni-load-more"], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y" + }, + "client": { + "App": { + "app-vue": "u", + "app-nvue": "n" + }, + "H5-mobile": { + "Safari": "y", + "Android Browser": "y", + "微信浏览器(Android)": "y", + "QQ浏览器(Android)": "y" + }, + "H5-pc": { + "Chrome": "y", + "IE": "y", + "Edge": "y", + "Firefox": "y", + "Safari": "y" + }, + "小程序": { + "微信": "y", + "阿里": "u", + "百度": "u", + "字节跳动": "u", + "QQ": "u", + "京东": "u" + }, + "快应用": { + "华为": "u", + "联盟": "u" + }, + "Vue": { + "vue2": "y", + "vue3": "y" + } + } + } + } +} diff --git a/uni_modules/uni-data-select/readme.md b/uni_modules/uni-data-select/readme.md new file mode 100644 index 0000000..eb58de3 --- /dev/null +++ b/uni_modules/uni-data-select/readme.md @@ -0,0 +1,8 @@ +## DataSelect 下拉框选择器 +> **组件名:uni-data-select** +> 代码块: `uDataSelect` + +当选项过多时,使用下拉菜单展示并选择内容 + +### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-data-select) +#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839 diff --git a/uni_modules/uni-icons/changelog.md b/uni_modules/uni-icons/changelog.md new file mode 100644 index 0000000..6449885 --- /dev/null +++ b/uni_modules/uni-icons/changelog.md @@ -0,0 +1,22 @@ +## 1.3.5(2022-01-24) +- 优化 size 属性可以传入不带单位的字符串数值 +## 1.3.4(2022-01-24) +- 优化 size 支持其他单位 +## 1.3.3(2022-01-17) +- 修复 nvue 有些图标不显示的bug,兼容老版本图标 +## 1.3.2(2021-12-01) +- 优化 示例可复制图标名称 +## 1.3.1(2021-11-23) +- 优化 兼容旧组件 type 值 +## 1.3.0(2021-11-19) +- 新增 更多图标 +- 优化 自定义图标使用方式 +- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource) +- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-icons](https://uniapp.dcloud.io/component/uniui/uni-icons) +## 1.1.7(2021-11-08) +## 1.2.0(2021-07-30) +- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834) +## 1.1.5(2021-05-12) +- 新增 组件示例地址 +## 1.1.4(2021-02-05) +- 调整为uni_modules目录规范 diff --git a/uni_modules/uni-icons/components/uni-icons/icons.js b/uni_modules/uni-icons/components/uni-icons/icons.js new file mode 100644 index 0000000..7889936 --- /dev/null +++ b/uni_modules/uni-icons/components/uni-icons/icons.js @@ -0,0 +1,1169 @@ +export default { + "id": "2852637", + "name": "uniui图标库", + "font_family": "uniicons", + "css_prefix_text": "uniui-", + "description": "", + "glyphs": [ + { + "icon_id": "25027049", + "name": "yanse", + "font_class": "color", + "unicode": "e6cf", + "unicode_decimal": 59087 + }, + { + "icon_id": "25027048", + "name": "wallet", + "font_class": "wallet", + "unicode": "e6b1", + "unicode_decimal": 59057 + }, + { + "icon_id": "25015720", + "name": "settings-filled", + "font_class": "settings-filled", + "unicode": "e6ce", + "unicode_decimal": 59086 + }, + { + "icon_id": "25015434", + "name": "shimingrenzheng-filled", + "font_class": "auth-filled", + "unicode": "e6cc", + "unicode_decimal": 59084 + }, + { + "icon_id": "24934246", + "name": "shop-filled", + "font_class": "shop-filled", + "unicode": "e6cd", + "unicode_decimal": 59085 + }, + { + "icon_id": "24934159", + "name": "staff-filled-01", + "font_class": "staff-filled", + "unicode": "e6cb", + "unicode_decimal": 59083 + }, + { + "icon_id": "24932461", + "name": "VIP-filled", + "font_class": "vip-filled", + "unicode": "e6c6", + "unicode_decimal": 59078 + }, + { + "icon_id": "24932462", + "name": "plus_circle_fill", + "font_class": "plus-filled", + "unicode": "e6c7", + "unicode_decimal": 59079 + }, + { + "icon_id": "24932463", + "name": "folder_add-filled", + "font_class": "folder-add-filled", + "unicode": "e6c8", + "unicode_decimal": 59080 + }, + { + "icon_id": "24932464", + "name": "yanse-filled", + "font_class": "color-filled", + "unicode": "e6c9", + "unicode_decimal": 59081 + }, + { + "icon_id": "24932465", + "name": "tune-filled", + "font_class": "tune-filled", + "unicode": "e6ca", + "unicode_decimal": 59082 + }, + { + "icon_id": "24932455", + "name": "a-rilidaka-filled", + "font_class": "calendar-filled", + "unicode": "e6c0", + "unicode_decimal": 59072 + }, + { + "icon_id": "24932456", + "name": "notification-filled", + "font_class": "notification-filled", + "unicode": "e6c1", + "unicode_decimal": 59073 + }, + { + "icon_id": "24932457", + "name": "wallet-filled", + "font_class": "wallet-filled", + "unicode": "e6c2", + "unicode_decimal": 59074 + }, + { + "icon_id": "24932458", + "name": "paihangbang-filled", + "font_class": "medal-filled", + "unicode": "e6c3", + "unicode_decimal": 59075 + }, + { + "icon_id": "24932459", + "name": "gift-filled", + "font_class": "gift-filled", + "unicode": "e6c4", + "unicode_decimal": 59076 + }, + { + "icon_id": "24932460", + "name": "fire-filled", + "font_class": "fire-filled", + "unicode": "e6c5", + "unicode_decimal": 59077 + }, + { + "icon_id": "24928001", + "name": "refreshempty", + "font_class": "refreshempty", + "unicode": "e6bf", + "unicode_decimal": 59071 + }, + { + "icon_id": "24926853", + "name": "location-ellipse", + "font_class": "location-filled", + "unicode": "e6af", + "unicode_decimal": 59055 + }, + { + "icon_id": "24926735", + "name": "person-filled", + "font_class": "person-filled", + "unicode": "e69d", + "unicode_decimal": 59037 + }, + { + "icon_id": "24926703", + "name": "personadd-filled", + "font_class": "personadd-filled", + "unicode": "e698", + "unicode_decimal": 59032 + }, + { + "icon_id": "24923351", + "name": "back", + "font_class": "back", + "unicode": "e6b9", + "unicode_decimal": 59065 + }, + { + "icon_id": "24923352", + "name": "forward", + "font_class": "forward", + "unicode": "e6ba", + "unicode_decimal": 59066 + }, + { + "icon_id": "24923353", + "name": "arrowthinright", + "font_class": "arrow-right", + "unicode": "e6bb", + "unicode_decimal": 59067 + }, + { + "icon_id": "24923353", + "name": "arrowthinright", + "font_class": "arrowthinright", + "unicode": "e6bb", + "unicode_decimal": 59067 + }, + { + "icon_id": "24923354", + "name": "arrowthinleft", + "font_class": "arrow-left", + "unicode": "e6bc", + "unicode_decimal": 59068 + }, + { + "icon_id": "24923354", + "name": "arrowthinleft", + "font_class": "arrowthinleft", + "unicode": "e6bc", + "unicode_decimal": 59068 + }, + { + "icon_id": "24923355", + "name": "arrowthinup", + "font_class": "arrow-up", + "unicode": "e6bd", + "unicode_decimal": 59069 + }, + { + "icon_id": "24923355", + "name": "arrowthinup", + "font_class": "arrowthinup", + "unicode": "e6bd", + "unicode_decimal": 59069 + }, + { + "icon_id": "24923356", + "name": "arrowthindown", + "font_class": "arrow-down", + "unicode": "e6be", + "unicode_decimal": 59070 + },{ + "icon_id": "24923356", + "name": "arrowthindown", + "font_class": "arrowthindown", + "unicode": "e6be", + "unicode_decimal": 59070 + }, + { + "icon_id": "24923349", + "name": "arrowdown", + "font_class": "bottom", + "unicode": "e6b8", + "unicode_decimal": 59064 + },{ + "icon_id": "24923349", + "name": "arrowdown", + "font_class": "arrowdown", + "unicode": "e6b8", + "unicode_decimal": 59064 + }, + { + "icon_id": "24923346", + "name": "arrowright", + "font_class": "right", + "unicode": "e6b5", + "unicode_decimal": 59061 + }, + { + "icon_id": "24923346", + "name": "arrowright", + "font_class": "arrowright", + "unicode": "e6b5", + "unicode_decimal": 59061 + }, + { + "icon_id": "24923347", + "name": "arrowup", + "font_class": "top", + "unicode": "e6b6", + "unicode_decimal": 59062 + }, + { + "icon_id": "24923347", + "name": "arrowup", + "font_class": "arrowup", + "unicode": "e6b6", + "unicode_decimal": 59062 + }, + { + "icon_id": "24923348", + "name": "arrowleft", + "font_class": "left", + "unicode": "e6b7", + "unicode_decimal": 59063 + }, + { + "icon_id": "24923348", + "name": "arrowleft", + "font_class": "arrowleft", + "unicode": "e6b7", + "unicode_decimal": 59063 + }, + { + "icon_id": "24923334", + "name": "eye", + "font_class": "eye", + "unicode": "e651", + "unicode_decimal": 58961 + }, + { + "icon_id": "24923335", + "name": "eye-filled", + "font_class": "eye-filled", + "unicode": "e66a", + "unicode_decimal": 58986 + }, + { + "icon_id": "24923336", + "name": "eye-slash", + "font_class": "eye-slash", + "unicode": "e6b3", + "unicode_decimal": 59059 + }, + { + "icon_id": "24923337", + "name": "eye-slash-filled", + "font_class": "eye-slash-filled", + "unicode": "e6b4", + "unicode_decimal": 59060 + }, + { + "icon_id": "24923305", + "name": "info-filled", + "font_class": "info-filled", + "unicode": "e649", + "unicode_decimal": 58953 + }, + { + "icon_id": "24923299", + "name": "reload-01", + "font_class": "reload", + "unicode": "e6b2", + "unicode_decimal": 59058 + }, + { + "icon_id": "24923195", + "name": "mic_slash_fill", + "font_class": "micoff-filled", + "unicode": "e6b0", + "unicode_decimal": 59056 + }, + { + "icon_id": "24923165", + "name": "map-pin-ellipse", + "font_class": "map-pin-ellipse", + "unicode": "e6ac", + "unicode_decimal": 59052 + }, + { + "icon_id": "24923166", + "name": "map-pin", + "font_class": "map-pin", + "unicode": "e6ad", + "unicode_decimal": 59053 + }, + { + "icon_id": "24923167", + "name": "location", + "font_class": "location", + "unicode": "e6ae", + "unicode_decimal": 59054 + }, + { + "icon_id": "24923064", + "name": "starhalf", + "font_class": "starhalf", + "unicode": "e683", + "unicode_decimal": 59011 + }, + { + "icon_id": "24923065", + "name": "star", + "font_class": "star", + "unicode": "e688", + "unicode_decimal": 59016 + }, + { + "icon_id": "24923066", + "name": "star-filled", + "font_class": "star-filled", + "unicode": "e68f", + "unicode_decimal": 59023 + }, + { + "icon_id": "24899646", + "name": "a-rilidaka", + "font_class": "calendar", + "unicode": "e6a0", + "unicode_decimal": 59040 + }, + { + "icon_id": "24899647", + "name": "fire", + "font_class": "fire", + "unicode": "e6a1", + "unicode_decimal": 59041 + }, + { + "icon_id": "24899648", + "name": "paihangbang", + "font_class": "medal", + "unicode": "e6a2", + "unicode_decimal": 59042 + }, + { + "icon_id": "24899649", + "name": "font", + "font_class": "font", + "unicode": "e6a3", + "unicode_decimal": 59043 + }, + { + "icon_id": "24899650", + "name": "gift", + "font_class": "gift", + "unicode": "e6a4", + "unicode_decimal": 59044 + }, + { + "icon_id": "24899651", + "name": "link", + "font_class": "link", + "unicode": "e6a5", + "unicode_decimal": 59045 + }, + { + "icon_id": "24899652", + "name": "notification", + "font_class": "notification", + "unicode": "e6a6", + "unicode_decimal": 59046 + }, + { + "icon_id": "24899653", + "name": "staff", + "font_class": "staff", + "unicode": "e6a7", + "unicode_decimal": 59047 + }, + { + "icon_id": "24899654", + "name": "VIP", + "font_class": "vip", + "unicode": "e6a8", + "unicode_decimal": 59048 + }, + { + "icon_id": "24899655", + "name": "folder_add", + "font_class": "folder-add", + "unicode": "e6a9", + "unicode_decimal": 59049 + }, + { + "icon_id": "24899656", + "name": "tune", + "font_class": "tune", + "unicode": "e6aa", + "unicode_decimal": 59050 + }, + { + "icon_id": "24899657", + "name": "shimingrenzheng", + "font_class": "auth", + "unicode": "e6ab", + "unicode_decimal": 59051 + }, + { + "icon_id": "24899565", + "name": "person", + "font_class": "person", + "unicode": "e699", + "unicode_decimal": 59033 + }, + { + "icon_id": "24899566", + "name": "email-filled", + "font_class": "email-filled", + "unicode": "e69a", + "unicode_decimal": 59034 + }, + { + "icon_id": "24899567", + "name": "phone-filled", + "font_class": "phone-filled", + "unicode": "e69b", + "unicode_decimal": 59035 + }, + { + "icon_id": "24899568", + "name": "phone", + "font_class": "phone", + "unicode": "e69c", + "unicode_decimal": 59036 + }, + { + "icon_id": "24899570", + "name": "email", + "font_class": "email", + "unicode": "e69e", + "unicode_decimal": 59038 + }, + { + "icon_id": "24899571", + "name": "personadd", + "font_class": "personadd", + "unicode": "e69f", + "unicode_decimal": 59039 + }, + { + "icon_id": "24899558", + "name": "chatboxes-filled", + "font_class": "chatboxes-filled", + "unicode": "e692", + "unicode_decimal": 59026 + }, + { + "icon_id": "24899559", + "name": "contact", + "font_class": "contact", + "unicode": "e693", + "unicode_decimal": 59027 + }, + { + "icon_id": "24899560", + "name": "chatbubble-filled", + "font_class": "chatbubble-filled", + "unicode": "e694", + "unicode_decimal": 59028 + }, + { + "icon_id": "24899561", + "name": "contact-filled", + "font_class": "contact-filled", + "unicode": "e695", + "unicode_decimal": 59029 + }, + { + "icon_id": "24899562", + "name": "chatboxes", + "font_class": "chatboxes", + "unicode": "e696", + "unicode_decimal": 59030 + }, + { + "icon_id": "24899563", + "name": "chatbubble", + "font_class": "chatbubble", + "unicode": "e697", + "unicode_decimal": 59031 + }, + { + "icon_id": "24881290", + "name": "upload-filled", + "font_class": "upload-filled", + "unicode": "e68e", + "unicode_decimal": 59022 + }, + { + "icon_id": "24881292", + "name": "upload", + "font_class": "upload", + "unicode": "e690", + "unicode_decimal": 59024 + }, + { + "icon_id": "24881293", + "name": "weixin", + "font_class": "weixin", + "unicode": "e691", + "unicode_decimal": 59025 + }, + { + "icon_id": "24881274", + "name": "compose", + "font_class": "compose", + "unicode": "e67f", + "unicode_decimal": 59007 + }, + { + "icon_id": "24881275", + "name": "qq", + "font_class": "qq", + "unicode": "e680", + "unicode_decimal": 59008 + }, + { + "icon_id": "24881276", + "name": "download-filled", + "font_class": "download-filled", + "unicode": "e681", + "unicode_decimal": 59009 + }, + { + "icon_id": "24881277", + "name": "pengyouquan", + "font_class": "pyq", + "unicode": "e682", + "unicode_decimal": 59010 + }, + { + "icon_id": "24881279", + "name": "sound", + "font_class": "sound", + "unicode": "e684", + "unicode_decimal": 59012 + }, + { + "icon_id": "24881280", + "name": "trash-filled", + "font_class": "trash-filled", + "unicode": "e685", + "unicode_decimal": 59013 + }, + { + "icon_id": "24881281", + "name": "sound-filled", + "font_class": "sound-filled", + "unicode": "e686", + "unicode_decimal": 59014 + }, + { + "icon_id": "24881282", + "name": "trash", + "font_class": "trash", + "unicode": "e687", + "unicode_decimal": 59015 + }, + { + "icon_id": "24881284", + "name": "videocam-filled", + "font_class": "videocam-filled", + "unicode": "e689", + "unicode_decimal": 59017 + }, + { + "icon_id": "24881285", + "name": "spinner-cycle", + "font_class": "spinner-cycle", + "unicode": "e68a", + "unicode_decimal": 59018 + }, + { + "icon_id": "24881286", + "name": "weibo", + "font_class": "weibo", + "unicode": "e68b", + "unicode_decimal": 59019 + }, + { + "icon_id": "24881288", + "name": "videocam", + "font_class": "videocam", + "unicode": "e68c", + "unicode_decimal": 59020 + }, + { + "icon_id": "24881289", + "name": "download", + "font_class": "download", + "unicode": "e68d", + "unicode_decimal": 59021 + }, + { + "icon_id": "24879601", + "name": "help", + "font_class": "help", + "unicode": "e679", + "unicode_decimal": 59001 + }, + { + "icon_id": "24879602", + "name": "navigate-filled", + "font_class": "navigate-filled", + "unicode": "e67a", + "unicode_decimal": 59002 + }, + { + "icon_id": "24879603", + "name": "plusempty", + "font_class": "plusempty", + "unicode": "e67b", + "unicode_decimal": 59003 + }, + { + "icon_id": "24879604", + "name": "smallcircle", + "font_class": "smallcircle", + "unicode": "e67c", + "unicode_decimal": 59004 + }, + { + "icon_id": "24879605", + "name": "minus-filled", + "font_class": "minus-filled", + "unicode": "e67d", + "unicode_decimal": 59005 + }, + { + "icon_id": "24879606", + "name": "micoff", + "font_class": "micoff", + "unicode": "e67e", + "unicode_decimal": 59006 + }, + { + "icon_id": "24879588", + "name": "closeempty", + "font_class": "closeempty", + "unicode": "e66c", + "unicode_decimal": 58988 + }, + { + "icon_id": "24879589", + "name": "clear", + "font_class": "clear", + "unicode": "e66d", + "unicode_decimal": 58989 + }, + { + "icon_id": "24879590", + "name": "navigate", + "font_class": "navigate", + "unicode": "e66e", + "unicode_decimal": 58990 + }, + { + "icon_id": "24879591", + "name": "minus", + "font_class": "minus", + "unicode": "e66f", + "unicode_decimal": 58991 + }, + { + "icon_id": "24879592", + "name": "image", + "font_class": "image", + "unicode": "e670", + "unicode_decimal": 58992 + }, + { + "icon_id": "24879593", + "name": "mic", + "font_class": "mic", + "unicode": "e671", + "unicode_decimal": 58993 + }, + { + "icon_id": "24879594", + "name": "paperplane", + "font_class": "paperplane", + "unicode": "e672", + "unicode_decimal": 58994 + }, + { + "icon_id": "24879595", + "name": "close", + "font_class": "close", + "unicode": "e673", + "unicode_decimal": 58995 + }, + { + "icon_id": "24879596", + "name": "help-filled", + "font_class": "help-filled", + "unicode": "e674", + "unicode_decimal": 58996 + }, + { + "icon_id": "24879597", + "name": "plus-filled", + "font_class": "paperplane-filled", + "unicode": "e675", + "unicode_decimal": 58997 + }, + { + "icon_id": "24879598", + "name": "plus", + "font_class": "plus", + "unicode": "e676", + "unicode_decimal": 58998 + }, + { + "icon_id": "24879599", + "name": "mic-filled", + "font_class": "mic-filled", + "unicode": "e677", + "unicode_decimal": 58999 + }, + { + "icon_id": "24879600", + "name": "image-filled", + "font_class": "image-filled", + "unicode": "e678", + "unicode_decimal": 59000 + }, + { + "icon_id": "24855900", + "name": "locked-filled", + "font_class": "locked-filled", + "unicode": "e668", + "unicode_decimal": 58984 + }, + { + "icon_id": "24855901", + "name": "info", + "font_class": "info", + "unicode": "e669", + "unicode_decimal": 58985 + }, + { + "icon_id": "24855903", + "name": "locked", + "font_class": "locked", + "unicode": "e66b", + "unicode_decimal": 58987 + }, + { + "icon_id": "24855884", + "name": "camera-filled", + "font_class": "camera-filled", + "unicode": "e658", + "unicode_decimal": 58968 + }, + { + "icon_id": "24855885", + "name": "chat-filled", + "font_class": "chat-filled", + "unicode": "e659", + "unicode_decimal": 58969 + }, + { + "icon_id": "24855886", + "name": "camera", + "font_class": "camera", + "unicode": "e65a", + "unicode_decimal": 58970 + }, + { + "icon_id": "24855887", + "name": "circle", + "font_class": "circle", + "unicode": "e65b", + "unicode_decimal": 58971 + }, + { + "icon_id": "24855888", + "name": "checkmarkempty", + "font_class": "checkmarkempty", + "unicode": "e65c", + "unicode_decimal": 58972 + }, + { + "icon_id": "24855889", + "name": "chat", + "font_class": "chat", + "unicode": "e65d", + "unicode_decimal": 58973 + }, + { + "icon_id": "24855890", + "name": "circle-filled", + "font_class": "circle-filled", + "unicode": "e65e", + "unicode_decimal": 58974 + }, + { + "icon_id": "24855891", + "name": "flag", + "font_class": "flag", + "unicode": "e65f", + "unicode_decimal": 58975 + }, + { + "icon_id": "24855892", + "name": "flag-filled", + "font_class": "flag-filled", + "unicode": "e660", + "unicode_decimal": 58976 + }, + { + "icon_id": "24855893", + "name": "gear-filled", + "font_class": "gear-filled", + "unicode": "e661", + "unicode_decimal": 58977 + }, + { + "icon_id": "24855894", + "name": "home", + "font_class": "home", + "unicode": "e662", + "unicode_decimal": 58978 + }, + { + "icon_id": "24855895", + "name": "home-filled", + "font_class": "home-filled", + "unicode": "e663", + "unicode_decimal": 58979 + }, + { + "icon_id": "24855896", + "name": "gear", + "font_class": "gear", + "unicode": "e664", + "unicode_decimal": 58980 + }, + { + "icon_id": "24855897", + "name": "smallcircle-filled", + "font_class": "smallcircle-filled", + "unicode": "e665", + "unicode_decimal": 58981 + }, + { + "icon_id": "24855898", + "name": "map-filled", + "font_class": "map-filled", + "unicode": "e666", + "unicode_decimal": 58982 + }, + { + "icon_id": "24855899", + "name": "map", + "font_class": "map", + "unicode": "e667", + "unicode_decimal": 58983 + }, + { + "icon_id": "24855825", + "name": "refresh-filled", + "font_class": "refresh-filled", + "unicode": "e656", + "unicode_decimal": 58966 + }, + { + "icon_id": "24855826", + "name": "refresh", + "font_class": "refresh", + "unicode": "e657", + "unicode_decimal": 58967 + }, + { + "icon_id": "24855808", + "name": "cloud-upload", + "font_class": "cloud-upload", + "unicode": "e645", + "unicode_decimal": 58949 + }, + { + "icon_id": "24855809", + "name": "cloud-download-filled", + "font_class": "cloud-download-filled", + "unicode": "e646", + "unicode_decimal": 58950 + }, + { + "icon_id": "24855810", + "name": "cloud-download", + "font_class": "cloud-download", + "unicode": "e647", + "unicode_decimal": 58951 + }, + { + "icon_id": "24855811", + "name": "cloud-upload-filled", + "font_class": "cloud-upload-filled", + "unicode": "e648", + "unicode_decimal": 58952 + }, + { + "icon_id": "24855813", + "name": "redo", + "font_class": "redo", + "unicode": "e64a", + "unicode_decimal": 58954 + }, + { + "icon_id": "24855814", + "name": "images-filled", + "font_class": "images-filled", + "unicode": "e64b", + "unicode_decimal": 58955 + }, + { + "icon_id": "24855815", + "name": "undo-filled", + "font_class": "undo-filled", + "unicode": "e64c", + "unicode_decimal": 58956 + }, + { + "icon_id": "24855816", + "name": "more", + "font_class": "more", + "unicode": "e64d", + "unicode_decimal": 58957 + }, + { + "icon_id": "24855817", + "name": "more-filled", + "font_class": "more-filled", + "unicode": "e64e", + "unicode_decimal": 58958 + }, + { + "icon_id": "24855818", + "name": "undo", + "font_class": "undo", + "unicode": "e64f", + "unicode_decimal": 58959 + }, + { + "icon_id": "24855819", + "name": "images", + "font_class": "images", + "unicode": "e650", + "unicode_decimal": 58960 + }, + { + "icon_id": "24855821", + "name": "paperclip", + "font_class": "paperclip", + "unicode": "e652", + "unicode_decimal": 58962 + }, + { + "icon_id": "24855822", + "name": "settings", + "font_class": "settings", + "unicode": "e653", + "unicode_decimal": 58963 + }, + { + "icon_id": "24855823", + "name": "search", + "font_class": "search", + "unicode": "e654", + "unicode_decimal": 58964 + }, + { + "icon_id": "24855824", + "name": "redo-filled", + "font_class": "redo-filled", + "unicode": "e655", + "unicode_decimal": 58965 + }, + { + "icon_id": "24841702", + "name": "list", + "font_class": "list", + "unicode": "e644", + "unicode_decimal": 58948 + }, + { + "icon_id": "24841489", + "name": "mail-open-filled", + "font_class": "mail-open-filled", + "unicode": "e63a", + "unicode_decimal": 58938 + }, + { + "icon_id": "24841491", + "name": "hand-thumbsdown-filled", + "font_class": "hand-down-filled", + "unicode": "e63c", + "unicode_decimal": 58940 + }, + { + "icon_id": "24841492", + "name": "hand-thumbsdown", + "font_class": "hand-down", + "unicode": "e63d", + "unicode_decimal": 58941 + }, + { + "icon_id": "24841493", + "name": "hand-thumbsup-filled", + "font_class": "hand-up-filled", + "unicode": "e63e", + "unicode_decimal": 58942 + }, + { + "icon_id": "24841494", + "name": "hand-thumbsup", + "font_class": "hand-up", + "unicode": "e63f", + "unicode_decimal": 58943 + }, + { + "icon_id": "24841496", + "name": "heart-filled", + "font_class": "heart-filled", + "unicode": "e641", + "unicode_decimal": 58945 + }, + { + "icon_id": "24841498", + "name": "mail-open", + "font_class": "mail-open", + "unicode": "e643", + "unicode_decimal": 58947 + }, + { + "icon_id": "24841488", + "name": "heart", + "font_class": "heart", + "unicode": "e639", + "unicode_decimal": 58937 + }, + { + "icon_id": "24839963", + "name": "loop", + "font_class": "loop", + "unicode": "e633", + "unicode_decimal": 58931 + }, + { + "icon_id": "24839866", + "name": "pulldown", + "font_class": "pulldown", + "unicode": "e632", + "unicode_decimal": 58930 + }, + { + "icon_id": "24813798", + "name": "scan", + "font_class": "scan", + "unicode": "e62a", + "unicode_decimal": 58922 + }, + { + "icon_id": "24813786", + "name": "bars", + "font_class": "bars", + "unicode": "e627", + "unicode_decimal": 58919 + }, + { + "icon_id": "24813788", + "name": "cart-filled", + "font_class": "cart-filled", + "unicode": "e629", + "unicode_decimal": 58921 + }, + { + "icon_id": "24813790", + "name": "checkbox", + "font_class": "checkbox", + "unicode": "e62b", + "unicode_decimal": 58923 + }, + { + "icon_id": "24813791", + "name": "checkbox-filled", + "font_class": "checkbox-filled", + "unicode": "e62c", + "unicode_decimal": 58924 + }, + { + "icon_id": "24813794", + "name": "shop", + "font_class": "shop", + "unicode": "e62f", + "unicode_decimal": 58927 + }, + { + "icon_id": "24813795", + "name": "headphones", + "font_class": "headphones", + "unicode": "e630", + "unicode_decimal": 58928 + }, + { + "icon_id": "24813796", + "name": "cart", + "font_class": "cart", + "unicode": "e631", + "unicode_decimal": 58929 + } + ] +} diff --git a/uni_modules/uni-icons/components/uni-icons/uni-icons.vue b/uni_modules/uni-icons/components/uni-icons/uni-icons.vue new file mode 100644 index 0000000..a87f68e --- /dev/null +++ b/uni_modules/uni-icons/components/uni-icons/uni-icons.vue @@ -0,0 +1,96 @@ + + + + + diff --git a/uni_modules/uni-icons/components/uni-icons/uni.ttf b/uni_modules/uni-icons/components/uni-icons/uni.ttf new file mode 100644 index 0000000..60a1968 Binary files /dev/null and b/uni_modules/uni-icons/components/uni-icons/uni.ttf differ diff --git a/uni_modules/uni-icons/components/uni-icons/uniicons.css b/uni_modules/uni-icons/components/uni-icons/uniicons.css new file mode 100644 index 0000000..2f56eab --- /dev/null +++ b/uni_modules/uni-icons/components/uni-icons/uniicons.css @@ -0,0 +1,663 @@ +.uniui-color:before { + content: "\e6cf"; +} + +.uniui-wallet:before { + content: "\e6b1"; +} + +.uniui-settings-filled:before { + content: "\e6ce"; +} + +.uniui-auth-filled:before { + content: "\e6cc"; +} + +.uniui-shop-filled:before { + content: "\e6cd"; +} + +.uniui-staff-filled:before { + content: "\e6cb"; +} + +.uniui-vip-filled:before { + content: "\e6c6"; +} + +.uniui-plus-filled:before { + content: "\e6c7"; +} + +.uniui-folder-add-filled:before { + content: "\e6c8"; +} + +.uniui-color-filled:before { + content: "\e6c9"; +} + +.uniui-tune-filled:before { + content: "\e6ca"; +} + +.uniui-calendar-filled:before { + content: "\e6c0"; +} + +.uniui-notification-filled:before { + content: "\e6c1"; +} + +.uniui-wallet-filled:before { + content: "\e6c2"; +} + +.uniui-medal-filled:before { + content: "\e6c3"; +} + +.uniui-gift-filled:before { + content: "\e6c4"; +} + +.uniui-fire-filled:before { + content: "\e6c5"; +} + +.uniui-refreshempty:before { + content: "\e6bf"; +} + +.uniui-location-filled:before { + content: "\e6af"; +} + +.uniui-person-filled:before { + content: "\e69d"; +} + +.uniui-personadd-filled:before { + content: "\e698"; +} + +.uniui-back:before { + content: "\e6b9"; +} + +.uniui-forward:before { + content: "\e6ba"; +} + +.uniui-arrow-right:before { + content: "\e6bb"; +} + +.uniui-arrowthinright:before { + content: "\e6bb"; +} + +.uniui-arrow-left:before { + content: "\e6bc"; +} + +.uniui-arrowthinleft:before { + content: "\e6bc"; +} + +.uniui-arrow-up:before { + content: "\e6bd"; +} + +.uniui-arrowthinup:before { + content: "\e6bd"; +} + +.uniui-arrow-down:before { + content: "\e6be"; +} + +.uniui-arrowthindown:before { + content: "\e6be"; +} + +.uniui-bottom:before { + content: "\e6b8"; +} + +.uniui-arrowdown:before { + content: "\e6b8"; +} + +.uniui-right:before { + content: "\e6b5"; +} + +.uniui-arrowright:before { + content: "\e6b5"; +} + +.uniui-top:before { + content: "\e6b6"; +} + +.uniui-arrowup:before { + content: "\e6b6"; +} + +.uniui-left:before { + content: "\e6b7"; +} + +.uniui-arrowleft:before { + content: "\e6b7"; +} + +.uniui-eye:before { + content: "\e651"; +} + +.uniui-eye-filled:before { + content: "\e66a"; +} + +.uniui-eye-slash:before { + content: "\e6b3"; +} + +.uniui-eye-slash-filled:before { + content: "\e6b4"; +} + +.uniui-info-filled:before { + content: "\e649"; +} + +.uniui-reload:before { + content: "\e6b2"; +} + +.uniui-micoff-filled:before { + content: "\e6b0"; +} + +.uniui-map-pin-ellipse:before { + content: "\e6ac"; +} + +.uniui-map-pin:before { + content: "\e6ad"; +} + +.uniui-location:before { + content: "\e6ae"; +} + +.uniui-starhalf:before { + content: "\e683"; +} + +.uniui-star:before { + content: "\e688"; +} + +.uniui-star-filled:before { + content: "\e68f"; +} + +.uniui-calendar:before { + content: "\e6a0"; +} + +.uniui-fire:before { + content: "\e6a1"; +} + +.uniui-medal:before { + content: "\e6a2"; +} + +.uniui-font:before { + content: "\e6a3"; +} + +.uniui-gift:before { + content: "\e6a4"; +} + +.uniui-link:before { + content: "\e6a5"; +} + +.uniui-notification:before { + content: "\e6a6"; +} + +.uniui-staff:before { + content: "\e6a7"; +} + +.uniui-vip:before { + content: "\e6a8"; +} + +.uniui-folder-add:before { + content: "\e6a9"; +} + +.uniui-tune:before { + content: "\e6aa"; +} + +.uniui-auth:before { + content: "\e6ab"; +} + +.uniui-person:before { + content: "\e699"; +} + +.uniui-email-filled:before { + content: "\e69a"; +} + +.uniui-phone-filled:before { + content: "\e69b"; +} + +.uniui-phone:before { + content: "\e69c"; +} + +.uniui-email:before { + content: "\e69e"; +} + +.uniui-personadd:before { + content: "\e69f"; +} + +.uniui-chatboxes-filled:before { + content: "\e692"; +} + +.uniui-contact:before { + content: "\e693"; +} + +.uniui-chatbubble-filled:before { + content: "\e694"; +} + +.uniui-contact-filled:before { + content: "\e695"; +} + +.uniui-chatboxes:before { + content: "\e696"; +} + +.uniui-chatbubble:before { + content: "\e697"; +} + +.uniui-upload-filled:before { + content: "\e68e"; +} + +.uniui-upload:before { + content: "\e690"; +} + +.uniui-weixin:before { + content: "\e691"; +} + +.uniui-compose:before { + content: "\e67f"; +} + +.uniui-qq:before { + content: "\e680"; +} + +.uniui-download-filled:before { + content: "\e681"; +} + +.uniui-pyq:before { + content: "\e682"; +} + +.uniui-sound:before { + content: "\e684"; +} + +.uniui-trash-filled:before { + content: "\e685"; +} + +.uniui-sound-filled:before { + content: "\e686"; +} + +.uniui-trash:before { + content: "\e687"; +} + +.uniui-videocam-filled:before { + content: "\e689"; +} + +.uniui-spinner-cycle:before { + content: "\e68a"; +} + +.uniui-weibo:before { + content: "\e68b"; +} + +.uniui-videocam:before { + content: "\e68c"; +} + +.uniui-download:before { + content: "\e68d"; +} + +.uniui-help:before { + content: "\e679"; +} + +.uniui-navigate-filled:before { + content: "\e67a"; +} + +.uniui-plusempty:before { + content: "\e67b"; +} + +.uniui-smallcircle:before { + content: "\e67c"; +} + +.uniui-minus-filled:before { + content: "\e67d"; +} + +.uniui-micoff:before { + content: "\e67e"; +} + +.uniui-closeempty:before { + content: "\e66c"; +} + +.uniui-clear:before { + content: "\e66d"; +} + +.uniui-navigate:before { + content: "\e66e"; +} + +.uniui-minus:before { + content: "\e66f"; +} + +.uniui-image:before { + content: "\e670"; +} + +.uniui-mic:before { + content: "\e671"; +} + +.uniui-paperplane:before { + content: "\e672"; +} + +.uniui-close:before { + content: "\e673"; +} + +.uniui-help-filled:before { + content: "\e674"; +} + +.uniui-paperplane-filled:before { + content: "\e675"; +} + +.uniui-plus:before { + content: "\e676"; +} + +.uniui-mic-filled:before { + content: "\e677"; +} + +.uniui-image-filled:before { + content: "\e678"; +} + +.uniui-locked-filled:before { + content: "\e668"; +} + +.uniui-info:before { + content: "\e669"; +} + +.uniui-locked:before { + content: "\e66b"; +} + +.uniui-camera-filled:before { + content: "\e658"; +} + +.uniui-chat-filled:before { + content: "\e659"; +} + +.uniui-camera:before { + content: "\e65a"; +} + +.uniui-circle:before { + content: "\e65b"; +} + +.uniui-checkmarkempty:before { + content: "\e65c"; +} + +.uniui-chat:before { + content: "\e65d"; +} + +.uniui-circle-filled:before { + content: "\e65e"; +} + +.uniui-flag:before { + content: "\e65f"; +} + +.uniui-flag-filled:before { + content: "\e660"; +} + +.uniui-gear-filled:before { + content: "\e661"; +} + +.uniui-home:before { + content: "\e662"; +} + +.uniui-home-filled:before { + content: "\e663"; +} + +.uniui-gear:before { + content: "\e664"; +} + +.uniui-smallcircle-filled:before { + content: "\e665"; +} + +.uniui-map-filled:before { + content: "\e666"; +} + +.uniui-map:before { + content: "\e667"; +} + +.uniui-refresh-filled:before { + content: "\e656"; +} + +.uniui-refresh:before { + content: "\e657"; +} + +.uniui-cloud-upload:before { + content: "\e645"; +} + +.uniui-cloud-download-filled:before { + content: "\e646"; +} + +.uniui-cloud-download:before { + content: "\e647"; +} + +.uniui-cloud-upload-filled:before { + content: "\e648"; +} + +.uniui-redo:before { + content: "\e64a"; +} + +.uniui-images-filled:before { + content: "\e64b"; +} + +.uniui-undo-filled:before { + content: "\e64c"; +} + +.uniui-more:before { + content: "\e64d"; +} + +.uniui-more-filled:before { + content: "\e64e"; +} + +.uniui-undo:before { + content: "\e64f"; +} + +.uniui-images:before { + content: "\e650"; +} + +.uniui-paperclip:before { + content: "\e652"; +} + +.uniui-settings:before { + content: "\e653"; +} + +.uniui-search:before { + content: "\e654"; +} + +.uniui-redo-filled:before { + content: "\e655"; +} + +.uniui-list:before { + content: "\e644"; +} + +.uniui-mail-open-filled:before { + content: "\e63a"; +} + +.uniui-hand-down-filled:before { + content: "\e63c"; +} + +.uniui-hand-down:before { + content: "\e63d"; +} + +.uniui-hand-up-filled:before { + content: "\e63e"; +} + +.uniui-hand-up:before { + content: "\e63f"; +} + +.uniui-heart-filled:before { + content: "\e641"; +} + +.uniui-mail-open:before { + content: "\e643"; +} + +.uniui-heart:before { + content: "\e639"; +} + +.uniui-loop:before { + content: "\e633"; +} + +.uniui-pulldown:before { + content: "\e632"; +} + +.uniui-scan:before { + content: "\e62a"; +} + +.uniui-bars:before { + content: "\e627"; +} + +.uniui-cart-filled:before { + content: "\e629"; +} + +.uniui-checkbox:before { + content: "\e62b"; +} + +.uniui-checkbox-filled:before { + content: "\e62c"; +} + +.uniui-shop:before { + content: "\e62f"; +} + +.uniui-headphones:before { + content: "\e630"; +} + +.uniui-cart:before { + content: "\e631"; +} diff --git a/uni_modules/uni-icons/components/uni-icons/uniicons.ttf b/uni_modules/uni-icons/components/uni-icons/uniicons.ttf new file mode 100644 index 0000000..835f33b Binary files /dev/null and b/uni_modules/uni-icons/components/uni-icons/uniicons.ttf differ diff --git a/uni_modules/uni-icons/package.json b/uni_modules/uni-icons/package.json new file mode 100644 index 0000000..d1c4e77 --- /dev/null +++ b/uni_modules/uni-icons/package.json @@ -0,0 +1,86 @@ +{ + "id": "uni-icons", + "displayName": "uni-icons 图标", + "version": "1.3.5", + "description": "图标组件,用于展示移动端常见的图标,可自定义颜色、大小。", + "keywords": [ + "uni-ui", + "uniui", + "icon", + "图标" +], + "repository": "https://github.com/dcloudio/uni-ui", + "engines": { + "HBuilderX": "^3.2.14" + }, + "directories": { + "example": "../../temps/example_temps" + }, + "dcloudext": { + "category": [ + "前端组件", + "通用组件" + ], + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "无", + "permissions": "无" + }, + "npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui" + }, + "uni_modules": { + "dependencies": ["uni-scss"], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y" + }, + "client": { + "App": { + "app-vue": "y", + "app-nvue": "y" + }, + "H5-mobile": { + "Safari": "y", + "Android Browser": "y", + "微信浏览器(Android)": "y", + "QQ浏览器(Android)": "y" + }, + "H5-pc": { + "Chrome": "y", + "IE": "y", + "Edge": "y", + "Firefox": "y", + "Safari": "y" + }, + "小程序": { + "微信": "y", + "阿里": "y", + "百度": "y", + "字节跳动": "y", + "QQ": "y" + }, + "快应用": { + "华为": "u", + "联盟": "u" + }, + "Vue": { + "vue2": "y", + "vue3": "y" + } + } + } + } +} \ No newline at end of file diff --git a/uni_modules/uni-icons/readme.md b/uni_modules/uni-icons/readme.md new file mode 100644 index 0000000..86234ba --- /dev/null +++ b/uni_modules/uni-icons/readme.md @@ -0,0 +1,8 @@ +## Icons 图标 +> **组件名:uni-icons** +> 代码块: `uIcons` + +用于展示 icons 图标 。 + +### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-icons) +#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839 diff --git a/uni_modules/uni-id/changelog.md b/uni_modules/uni-id/changelog.md new file mode 100644 index 0000000..2f523bb --- /dev/null +++ b/uni_modules/uni-id/changelog.md @@ -0,0 +1,111 @@ +## 3.3.28(2022-07-27) +- 修复 app端微信登录返回的accessToken过期时间(expired)不正确的Bug +## 3.3.27(2022-07-27) +- 短信发送失败、微信登录失败等场景下输出原始错误方便排查错误 +## 3.3.26(2022-07-08) +- 兼容配置放在uni-id下的逻辑,但是仍推荐使用uni-config-center +## 3.3.25(2022-06-30) +- 修复config文件不合法时未抛出具体错误的Bug +## 3.3.24(2022-06-28) +- 修复3.3.12引出的使用多应用配置时报错的Bug +## 3.3.23(2022-06-13) +- 修复上版本引出的部分依赖未找到的Bug +## 3.3.22(2022-06-13) +- 新增 preferedWebPlatform 配置用于解决HBuilderX 3.4.9版本起web端platform不一致的问题 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=prefered-web-platform) +## 3.3.21(2022-05-24) +- 修复createInstance传入clientInfo无效的Bug +## 3.3.20(2022-05-19) +- 调整以下错误码(账号已注册[uni-id-account-exists]、账号不存在[uni-id-account-not-exists]、账号已绑定[uni-id-account-bound]) +## 3.3.19(2022-05-19) +- 修复 addUser 部分情况下会创建出重复账号的Bug +## 3.3.18(2022-05-12) +- 调整绑定、解绑邮箱手机号接口,只要传递code参数就进行验证码校验即使传递的值为undefined +## 3.3.17(2022-05-09) +- register_env内增加os_name字段用于区分注册时的客户端系统类型 +## 3.3.16(2022-05-09) +- 修复 addUser接口添加的用户无法使用密码登录的Bug [详情](https://ask.dcloud.net.cn/question/144670) +## 3.3.15(2022-05-08) +- 修复config文件语法错误时报`this.t is not a function`的Bug 感谢@寒暄 +## 3.3.14(2022-05-08) +- 新增 getWeixinUserInfo接口 用于获取app平台微信登录用户的用户信息 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id.html#get-weixin-user-info) +- 新增 addUser接口 用于手动添加用户 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id.html#add-user) +- 新增 resetPwdBySms接口 用于使用短信验证码重置密码 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id.html#reset-pwd-by-sms) +- 新增 refreshToken接口 用于主动刷新用户token [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id.html#refresh-token) +- 调整 用户注册时记录用户注册环境到 register_env 字段 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id.html#user-table) +- 调整 用户注册时将注册 ip 移至 register_env 内 + +## 3.3.13(2022-03-04) +- createInstance方法支持传递clientInfo [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id.html#create-instance) +- 修复`this.t is not a function`报错 +## 3.3.12(2022-01-15) +- 新增 preferedAppPlatform 配置用于解决uni-app vue2版本vue3版本获取platform不一致的问题 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=prefered-app-platform) +- 修复 checkToken 未返回自定义token内容的Bug +## 3.3.11(2022-01-11) +- 修复用户名密码登录时多个应用出现重复用户名登录报错的Bug +## 3.3.10(2022-01-07) +- 新增 自定义国际化语言支持 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=custom-i8n) +- 修复 一键登录时未校验重复手机号是否已验证的Bug +- 修复 Apple登录时用户邮箱为空时报错的Bug +- 修复 登录接口未传username时错误提示不正确的Bug +## 3.3.9(2021-11-09) +- 去除重复的context.xxx未找到的提示语 +## 3.3.8(2021-10-28) +- 新增 用户账户封禁接口 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=ban-account) +- 新增 用户账户注销接口 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=close-account) +- 修复 未传appid时用户重复注册的Bug +## 3.3.7(2021-10-08) +- 移除部分接口的废弃提示 +## 3.3.6(2021-09-08) +- 修复 邀请码可能重复的Bug +## 3.3.5(2021-08-10) +- 修复版本号错误 +## 3.3.4(2021-08-10) +- 微信、QQ、支付宝登录新增type参数用于指定当前是登录还是注册 +## 3.3.3(2021-08-04) +- 修复使用数组形式的配置文件报错的Bug +## 3.3.2(2021-08-03) +- 修复上3.3.0版本引出的createInstance接口传入配置不生效的Bug 感谢[hmh](https://gitee.com/hmh) +## 3.3.1(2021-07-30) +- 修复 将设置用户允许登录的应用列表时传入空数组报错的Bug +## 3.3.0(2021-07-30) +- 新增 不同端应用配置隔离 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=isolate-config) +- 新增 不同端用户隔离 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=isolate-user) + + 此版本升级需要开发者处理一下用户数据,请参考 [补齐用户dcloud_appid字段](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=makeup-dcloud-appid) +- 新增 QQ登录、注册相关功能 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=qq) +- 调整 不再支持绑定手机、邮箱时不填验证码直接绑定 +## 3.2.1(2021-07-09) +- 撤销3.2.0版本所做的调整 +## 3.2.0(2021-07-09) +- 【重要】支持不同端(管理端、用户端等)用户隔离 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=isolate-user) +- 支持不同端(管理端、用户端等)配置文件隔离 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=isolate-config) +## 3.1.3(2021-07-08) +- 移除插件内误传的node_modules +## 3.1.2(2021-07-08) +- 修复 微信小程序绑定微信账号时报错的Bug +## 3.1.1(2021-07-01) +- 使用新的错误码规范,兼容旧版 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=errcode) +- 修复微信登录、绑定时未返回用户accessToken的Bug +## 3.1.0(2021-04-19) +- 增加对用户名、邮箱、密码字段的两端去空格 +- 默认忽略用户名、邮箱的大小写 [详情](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=case-sensitive) +- 修复 customToken导出async方法报错的Bug +## 3.0.12(2021-04-13) +- 调整bindTokenToDevice默认值为false +## 3.0.11(2021-04-12) +- 修复3.0.7版本引出的多个用户访问时可能出现30201报错的Bug +## 3.0.10(2021-04-08) +- 优化错误提示 +## 3.0.9(2021-04-08) +- bindMobile接口支持通过一键登录的方式绑定 +- 优化错误提示 +## 3.0.8(2021-03-19) +- 修复 3.0.7版本某些情况下生成token报错的Bug +## 3.0.7(2021-03-19) +- 新增 支持uni-config-center,更新uni-id无须再担心配置被覆盖 [详情](https://uniapp.dcloud.io/uniCloud/uni-id?id=uni-config-center) +- 新增 自定义token内容,可以缓存角色权限之外的更多信息到客户端 [详情](https://uniapp.dcloud.io/uniCloud/uni-id?id=custom-token) +- 新增 支持传入context获取uni-id实例,防止单实例多并发时全局context混乱 [详情](https://uniapp.dcloud.io/uniCloud/uni-id?id=create-instance) +## 3.0.6(2021-03-05) +- 新增[uniID.wxBizDataCrypt](https://uniapp.dcloud.io/uniCloud/uni-id?id=%e5%be%ae%e4%bf%a1%e6%95%b0%e6%8d%ae%e8%a7%a3%e5%af%86)方法 +- 优化loginByApple方法,提高接口响应速度 +## 3.0.5(2021-02-03) +- 调整为uni_modules目录规范 diff --git a/uni_modules/uni-id/package.json b/uni_modules/uni-id/package.json new file mode 100644 index 0000000..144a9f1 --- /dev/null +++ b/uni_modules/uni-id/package.json @@ -0,0 +1,85 @@ +{ + "id": "uni-id", + "displayName": "uni-id", + "version": "3.3.28", + "description": "简单、统一、可扩展的用户中心", + "keywords": [ + "uniid", + "uni-id", + "用户管理", + "用户中心", + "短信验证码" +], + "repository": "https://gitee.com/dcloud/uni-id.git", + "engines": { + "HBuilderX": "^3.1.0" + }, +"dcloudext": { + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "无", + "permissions": "无" + }, + "npmurl": "", + "type": "unicloud-template-function" + }, + "uni_modules": { + "dependencies": ["uni-config-center"], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y" + }, + "client": { + "App": { + "app-vue": "u", + "app-nvue": "u" + }, + "H5-mobile": { + "Safari": "u", + "Android Browser": "u", + "微信浏览器(Android)": "u", + "QQ浏览器(Android)": "u" + }, + "H5-pc": { + "Chrome": "u", + "IE": "u", + "Edge": "u", + "Firefox": "u", + "Safari": "u" + }, + "小程序": { + "微信": "u", + "阿里": "u", + "百度": "u", + "字节跳动": "u", + "QQ": "u", + "钉钉": "u", + "快手": "u", + "飞书": "u", + "京东": "u" + }, + "快应用": { + "华为": "u", + "联盟": "u" + }, + "Vue": { + "vue2": "y", + "vue3": "u" + } + } + } + } +} \ No newline at end of file diff --git a/uni_modules/uni-id/readme.md b/uni_modules/uni-id/readme.md new file mode 100644 index 0000000..6890121 --- /dev/null +++ b/uni_modules/uni-id/readme.md @@ -0,0 +1,33 @@ +**文档已移至[uni-id文档](https://uniapp.dcloud.net.cn/uniCloud/uni-id)** + +> 一般uni-id升级大版本时为不兼容更新,从低版本迁移到高版本请参考:[uni-id迁移指南](https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=migration) + +## 重要升级说明 + +**uni-id 3.x版本,搭配的uniCloud admin版本需大于1.2.10。** + +### 缓存角色权限 + +自`uni-id 3.0.0`起,支持在token内缓存用户的角色权限,默认开启此功能,各登录接口的needPermission参数不再生效。如需关闭请在config内配置`"removePermissionAndRoleFromToken": true`。 + +为什么要缓存角色权限?要知道云数据库是按照读写次数来收取费用的,并且读写数据库会拖慢接口响应速度。未配置`"removePermissionAndRoleFromToken": true`的情况下,可以在调用checkToken接口时不查询数据库获取用户角色权限。 + +详细checkToken流程如下: + +![](https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/ed45d350-5a4d-11eb-b997-9918a5dda011.jpg) + +可以看出,旧版token(removePermissionAndRoleFromToken为true时生成的)在checkToken时如需返回权限需要进行两次数据库查询。新版token不需要查库即可返回权限信息。 + +**注意** + +- 由于角色权限缓存在token内,可能会存在权限已经更新但是用户token未过期之前依然是旧版角色权限的情况。可以调短一些token过期时间来减少这种情况的影响。 +- admin角色token内不包含permission,如需自行判断用户是否有某个权限,要注意admin角色需要额外判断一下,写法如下 + ```js + const { + role, + permission + } = await uniID.checkToken(event.uniIdToken) + if(role.includes('admin') || permission.includes('your permission id')) { + // 当前角色拥有'your permission id'对应的权限 + } + ``` \ No newline at end of file diff --git a/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/LICENSE.md b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/LICENSE.md new file mode 100644 index 0000000..29f81d8 --- /dev/null +++ b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/index.js b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/index.js new file mode 100644 index 0000000..5003d30 --- /dev/null +++ b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/index.js @@ -0,0 +1 @@ +"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("crypto")),r=e(require("buffer")),n=e(require("stream")),i=e(require("util"));const o={PARAM_ERROR:{errCode:"param-error"},PARAM_REQUIRED:{errCode:"param-required"},USER_NOT_EXIST:{errCode:"user-not-exist"},ROLE_NOT_EXIST:{errCode:"role-not-exist"},PERMISSION_NOT_EXIST:{errCode:"permission-not-exist"},MULTI_USER_MATCHED:{errCode:"multi-user-matched"},USER_INFO_ERROR:{errCode:"user-info-error"},USER_ACCOUNT_CONFLICT:{errCode:"user-account-conflict"},USER_ACCOUNT_CLOSED:{errCode:"user-account-closed"},ACCOUNT_EXISTS:{errCode:"account-exists"},ACCOUNT_NOT_EXISTS:{errCode:"account-not-exists"},ACCOUNT_BOUND:{errCode:"account-bound"},UNBIND_FAILED:{errCode:"unbind-failed"},INVALID_INVITE_CODE:{errCode:"invalid-invite-code"},SET_INVITE_CODE_FAILED:{errCode:"set-invite-code-failed"},GET_THIRD_PARTY_ACCOUNT_FAILED:{errCode:"get-third-party-account-failed"},GET_THIRD_PARTY_USER_INFO_FAILED:{errCode:"get-third-party-user-info-failed"}},s={0:{errCode:0,errMsg:""},10001:{errCode:"account-banned"},10002:o.USER_NOT_EXIST,10003:o.MULTI_USER_MATCHED,10004:o.USER_INFO_ERROR,10005:o.USER_ACCOUNT_CONFLICT,10006:o.USER_ACCOUNT_CLOSED,10102:{errCode:"password-error"},10103:{errCode:"password-error-exceed-limit"},10201:o.ACCOUNT_EXISTS,10202:o.ACCOUNT_NOT_EXISTS,10203:o.INVALID_INVITE_CODE,10301:o.ACCOUNT_EXISTS,10302:o.ACCOUNT_NOT_EXISTS,10401:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10402:o.ACCOUNT_EXISTS,10403:o.ACCOUNT_NOT_EXISTS,10501:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10502:o.ACCOUNT_EXISTS,10503:o.ACCOUNT_NOT_EXISTS,10601:o.ACCOUNT_EXISTS,10602:o.ACCOUNT_NOT_EXISTS,10701:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10702:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10703:o.ACCOUNT_EXISTS,10704:o.ACCOUNT_NOT_EXISTS,10705:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10706:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10801:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10802:o.ACCOUNT_EXISTS,10803:o.ACCOUNT_NOT_EXISTS,20101:o.PARAM_REQUIRED,20102:o.ACCOUNT_EXISTS,30101:o.PARAM_REQUIRED,30201:{errCode:"check-device-feature-failed"},30202:{errCode:"token-not-exist"},30203:{errCode:"token-expired"},30204:{errCode:"check-token-failed"},40201:o.USER_NOT_EXIST,40202:{errCode:"invalid-old-password"},50101:o.PARAM_REQUIRED,50102:o.PARAM_ERROR,50201:o.PARAM_REQUIRED,50203:o.PARAM_ERROR,50202:{errCode:"invalid-verify-code"},50301:{errCode:"send-sms-code-failed"},60101:o.ACCOUNT_BOUND,60201:o.ACCOUNT_BOUND,60301:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60302:o.ACCOUNT_BOUND,60401:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60402:o.ACCOUNT_BOUND,60501:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60502:o.ACCOUNT_BOUND,70101:o.UNBIND_FAILED,70201:o.UNBIND_FAILED,70301:o.UNBIND_FAILED,70401:o.UNBIND_FAILED,70501:o.UNBIND_FAILED,80301:o.USER_NOT_EXIST,80401:o.SET_INVITE_CODE_FAILED,80402:o.SET_INVITE_CODE_FAILED,80501:o.INVALID_INVITE_CODE,80502:o.USER_NOT_EXIST,80503:{errCode:"modify-invite-code-is-not-allowed"},80601:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80602:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80701:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80702:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80801:{errCode:"decrypt-weixin-data-failed"},80802:{errCode:"decrypt-weixin-data-failed"},80803:{errCode:"invalid-weixin-appid"},80804:o.PARAM_REQUIRED,80805:o.PARAM_REQUIRED,80806:o.PARAM_REQUIRED,80901:o.GET_THIRD_PARTY_USER_INFO_FAILED,90001:{errCode:"database-operation-failed"},90002:o.PARAM_REQUIRED,90003:o.PARAM_ERROR,90004:o.USER_NOT_EXIST,90005:o.ROLE_NOT_EXIST,90006:o.PERMISSION_NOT_EXIST};class a extends Error{constructor(e){super(e.message),this.errMsg=e.message||"",Object.defineProperties(this,{message:{get(){return`errCode: ${e.code||""} | errMsg: `+this.errMsg},set(e){this.errMsg=e}}})}}const c=Object.prototype.toString,u=Object.prototype.hasOwnProperty;function d(e,t){return u.call(e,t)}function p(e){return"[object Object]"===c.call(e)}function l(e){return"function"==typeof e}function f(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}function m(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}const h=/_(\w)/g,g=/[A-Z]/g;function y(e){return e.replace(h,(e,t)=>t?t.toUpperCase():"")}function w(e){return e.replace(g,e=>"_"+e.toLowerCase())}function v(e,t){let r,n;switch(t){case"snake2camel":n=y,r=h;break;case"camel2snake":n=w,r=g}for(const i in e)if(d(e,i)&&r.test(i)){const r=n(i);e[r]=e[i],delete e[i],p(e[r])?e[r]=v(e[r],t):Array.isArray(e[r])&&(e[r]=e[r].map(e=>v(e,t)))}return e}function _(e){return v(e,"snake2camel")}function b(e){return v(e,"camel2snake")}function T(e){return function(e,t="-"){e=e||new Date;const r=[];return r.push(e.getFullYear()),r.push(("00"+(e.getMonth()+1)).substr(-2)),r.push(("00"+e.getDate()).substr(-2)),r.join(t)}(e=e||new Date)+" "+function(e,t=":"){e=e||new Date;const r=[];return r.push(("00"+e.getHours()).substr(-2)),r.push(("00"+e.getMinutes()).substr(-2)),r.push(("00"+e.getSeconds()).substr(-2)),r.join(t)}(e)}function E(){"development"===process.env.NODE_ENV&&console.log(...arguments)}function C(e=6){let t="";for(let r=0;r-1?"&":"?"}access_token=${t.accessToken}`}return`${e}${r}`}class G{constructor(e){this.options=Object.assign({baseUrl:"https://api.weixin.qq.com",timeout:5e3},e)}async _requestWxOpenapi({name:e,url:t,data:r,options:n}){const i={method:"GET",dataType:"json",dataAsQueryString:!0,timeout:this.options.timeout};return await H({name:"auth."+e,url:`${this.options.baseUrl}${K(t,r)}`,data:r,options:n,defaultOptions:i})}async code2Session(e){return await this._requestWxOpenapi({name:"code2Session",url:"/sns/jscode2session",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,js_code:e}})}async getOauthAccessToken(e){const t=await this._requestWxOpenapi({name:"getOauthAccessToken",url:"/sns/oauth2/access_token",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,code:e}});return t.expiresIn&&(t.expired=Date.now()+1e3*t.expiresIn),t}async getUserInfo({accessToken:e,openid:t}={}){const{nickname:r,headimgurl:n}=await this._requestWxOpenapi({name:"getUserInfo",url:"/sns/userinfo",data:{accessToken:e,openid:t,appid:this.options.appId,secret:this.options.secret,scope:"snsapi_userinfo"}});return{nickname:r,avatar:n}}}async function Q({name:e,url:t,data:r,options:n,defaultOptions:i}){let o;n=Object.assign({},i,n,{data:b(Object.assign({},r))});try{o=await uniCloud.httpclient.request(t,n)}catch(t){return function(e,t){throw new a({code:t.code||-2,message:t.message||e+" fail"})}(e,t)}let s=o.data;const c=o.headers["content-type"];if(!Buffer.isBuffer(s)||0!==c.indexOf("text/plain")&&0!==c.indexOf("application/json"))Buffer.isBuffer(s)&&(s={buffer:s,contentType:c});else try{s=JSON.parse(s.toString())}catch(e){s=s.toString()}return _(function(e,t){if(t.ret||t.error){const r=t.ret||t.error||t.errcode||-2,n=t.msg||t.error_description||t.errmsg||e+" fail";throw new a({code:r,message:n})}return delete t.ret,delete t.msg,delete t.error,delete t.error_description,delete t.errcode,delete t.errmsg,{...t,errMsg:e+" ok",errCode:0}}(e,s||{errCode:-2,errMsg:"Request failed"}))}class X{constructor(e){this.options=Object.assign({baseUrl:"https://graph.qq.com",timeout:5e3},e)}async _requestQQOpenapi({name:e,url:t,data:r,options:n}){const i={method:"GET",dataType:"json",dataAsQueryString:!0,timeout:this.options.timeout};var o,s;return await Q({name:"auth."+e,url:(o=this.options.baseUrl,s=t,/^https?:/.test(s)?s:o+s),data:r,options:n,defaultOptions:i})}async getOpenidByToken({accessToken:e}={}){const t=await this._requestQQOpenapi({name:"getOpenidByToken",url:"/oauth2.0/me",data:{accessToken:e,unionid:1,fmt:"json"}});if(t.clientId!==this.options.appId)throw new a({code:"APPID_NOT_MATCH",message:"appid not match"});return{openid:t.openid,unionid:t.unionid}}async code2Session({code:e}={}){return await this._requestQQOpenapi({name:"getOpenidByToken",url:"https://api.q.qq.com/sns/jscode2session",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,js_code:e}})}}const Y={RSA:"RSA-SHA1",RSA2:"RSA-SHA256"};var z={code2Session:{returnValue:{openid:"userId"}}};class W extends class{constructor(e={}){if(!e.appId)throw new Error("appId required");if(!e.privateKey)throw new Error("privateKey required");const t={gateway:"https://openapi.alipay.com/gateway.do",timeout:5e3,charset:"utf-8",version:"1.0",signType:"RSA2",timeOffset:-(new Date).getTimezoneOffset()/60,keyType:"PKCS8"};e.sandbox&&(e.gateway="https://openapi.alipaydev.com/gateway.do"),this.options=Object.assign({},t,e);const r="PKCS8"===this.options.keyType?"PRIVATE KEY":"RSA PRIVATE KEY";this.options.privateKey=this._formatKey(this.options.privateKey,r),this.options.alipayPublicKey&&(this.options.alipayPublicKey=this._formatKey(this.options.alipayPublicKey,"PUBLIC KEY"))}_formatKey(e,t){return`-----BEGIN ${t}-----\n${e}\n-----END ${t}-----`}_formatUrl(e,t){let r=e;const n=["app_id","method","format","charset","sign_type","sign","timestamp","version","notify_url","return_url","auth_token","app_auth_token"];for(const e in t)if(n.indexOf(e)>-1){const n=encodeURIComponent(t[e]);r=`${r}${r.includes("?")?"&":"?"}${e}=${n}`,delete t[e]}return{execParams:t,url:r}}_getSign(e,r){const n=r.bizContent||null;delete r.bizContent;const i=Object.assign({method:e,appId:this.options.appId,charset:this.options.charset,version:this.options.version,signType:this.options.signType,timestamp:T((o=this.options.timeOffset,new Date(Date.now()+6e4*((new Date).getTimezoneOffset()+60*(o||0)))))},r);var o;n&&(i.bizContent=JSON.stringify(b(n)));const s=b(i),a=Object.keys(s).sort().map(e=>{let t=s[e];return"[object String]"!==Array.prototype.toString.call(t)&&(t=JSON.stringify(t)),`${e}=${t}`}).join("&"),c=t.createSign(Y[this.options.signType]).update(a,"utf8").sign(this.options.privateKey,"base64");return Object.assign(s,{sign:c})}async _exec(e,t={},r={}){const n=this._getSign(e,t),{url:i,execParams:o}=this._formatUrl(this.options.gateway,n),{status:s,data:a}=await uniCloud.httpclient.request(i,{method:"POST",data:o,dataType:"text",timeout:this.options.timeout});if(200!==s)throw new Error("request fail");const c=JSON.parse(a),u=e.replace(/\./g,"_")+"_response",d=c[u],p=c.error_response;if(d){if(!r.validateSign||this._checkResponseSign(a,u)){if(!d.code||"10000"===d.code){return{errCode:0,errMsg:d.msg||"",..._(d)}}const e=d.sub_code?`${d.sub_code} ${d.sub_msg}`:""+(d.msg||"unkonwn error");throw new Error(e)}throw new Error("check sign error")}if(p)throw new Error(p.sub_msg||p.msg||"request fail");throw new Error("request fail")}_checkResponseSign(e,r){if(!this.options.alipayPublicKey||""===this.options.alipayPublicKey)return console.warn("options.alipayPublicKey is empty"),!0;if(!e)return!1;const n=this._getSignStr(e,r),i=JSON.parse(e).sign,o=t.createVerify(Y[this.options.signType]);return o.update(n,"utf8"),o.verify(this.options.alipayPublicKey,i,"base64")}_getSignStr(e,t){let r=e.trim();const n=e.indexOf(t+'"'),i=e.lastIndexOf('"sign"');return r=r.substr(n+t.length+1),r=r.substr(0,i),r=r.replace(/^[^{]*{/g,"{"),r=r.replace(/\}([^}]*)$/g,"}"),r}}{constructor(e){super(e),this._protocols=z}async code2Session(e){return await this._exec("alipay.system.oauth.token",{grantType:"authorization_code",code:e})}}function J(e){var t=e[0];return t<"0"||t>"7"?"00"+e:e}function Z(e){var t=e.toString(16);return t.length%2?"0"+t:t}function ee(e){if(e<=127)return Z(e);var t=Z(e);return Z(128+t.length/2)+t}function te(e,t){return e(t={exports:{}},t.exports),t.exports}var re=te((function(e,t){var n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=n(e);return void 0!==t?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}})),ne=(re.Buffer,re.Buffer);function ie(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=ne.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=ne.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof e+")")}i.inherits(ie,n),ie.prototype.write=function(e){this.buffer=ne.concat([this.buffer,ne.from(e)]),this.emit("data",e)},ie.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};var oe=ie,se=r.Buffer,ae=r.SlowBuffer,ce=ue;function ue(e,t){if(!se.isBuffer(e)||!se.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(var r=0,n=0;n=128&&--n,n}var we={derToJose:function(e,t){e=ge(e);var r=me(t),n=r+1,i=e.length,o=0;if(48!==e[o++])throw new Error('Could not find expected "seq"');var s=e[o++];if(129===s&&(s=e[o++]),i-o0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return r*mt;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ft;case"minutes":case"minute":case"mins":case"min":case"m":return r*lt;case"seconds":case"second":case"secs":case"sec":case"s":return r*pt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=mt)return gt(e,t,mt,"day");if(t>=ft)return gt(e,t,ft,"hour");if(t>=lt)return gt(e,t,lt,"minute");if(t>=pt)return gt(e,t,pt,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=mt)return Math.round(e/mt)+"d";if(t>=ft)return Math.round(e/ft)+"h";if(t>=lt)return Math.round(e/lt)+"m";if(t>=pt)return Math.round(e/pt)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function gt(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}var yt=function(e,t){var r=t||Math.floor(Date.now()/1e3);if("string"==typeof e){var n=ht(e);if(void 0===n)return;return Math.floor(r+n/1e3)}return"number"==typeof e?r+e:void 0},wt=te((function(e,t){var r;t=e.exports=G,r="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";var n=Number.MAX_SAFE_INTEGER||9007199254740991,i=t.re=[],o=t.src=[],s=0,a=s++;o[a]="0|[1-9]\\d*";var c=s++;o[c]="[0-9]+";var u=s++;o[u]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var d=s++;o[d]="("+o[a]+")\\.("+o[a]+")\\.("+o[a]+")";var p=s++;o[p]="("+o[c]+")\\.("+o[c]+")\\.("+o[c]+")";var l=s++;o[l]="(?:"+o[a]+"|"+o[u]+")";var f=s++;o[f]="(?:"+o[c]+"|"+o[u]+")";var m=s++;o[m]="(?:-("+o[l]+"(?:\\."+o[l]+")*))";var h=s++;o[h]="(?:-?("+o[f]+"(?:\\."+o[f]+")*))";var g=s++;o[g]="[0-9A-Za-z-]+";var y=s++;o[y]="(?:\\+("+o[g]+"(?:\\."+o[g]+")*))";var w=s++,v="v?"+o[d]+o[m]+"?"+o[y]+"?";o[w]="^"+v+"$";var _="[v=\\s]*"+o[p]+o[h]+"?"+o[y]+"?",b=s++;o[b]="^"+_+"$";var T=s++;o[T]="((?:<|>)?=?)";var E=s++;o[E]=o[c]+"|x|X|\\*";var C=s++;o[C]=o[a]+"|x|X|\\*";var A=s++;o[A]="[v=\\s]*("+o[C]+")(?:\\.("+o[C]+")(?:\\.("+o[C]+")(?:"+o[m]+")?"+o[y]+"?)?)?";var I=s++;o[I]="[v=\\s]*("+o[E]+")(?:\\.("+o[E]+")(?:\\.("+o[E]+")(?:"+o[h]+")?"+o[y]+"?)?)?";var S=s++;o[S]="^"+o[T]+"\\s*"+o[A]+"$";var x=s++;o[x]="^"+o[T]+"\\s*"+o[I]+"$";var k=s++;o[k]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var O=s++;o[O]="(?:~>?)";var P=s++;o[P]="(\\s*)"+o[O]+"\\s+",i[P]=new RegExp(o[P],"g");var R=s++;o[R]="^"+o[O]+o[A]+"$";var j=s++;o[j]="^"+o[O]+o[I]+"$";var D=s++;o[D]="(?:\\^)";var q=s++;o[q]="(\\s*)"+o[D]+"\\s+",i[q]=new RegExp(o[q],"g");var N=s++;o[N]="^"+o[D]+o[A]+"$";var U=s++;o[U]="^"+o[D]+o[I]+"$";var L=s++;o[L]="^"+o[T]+"\\s*("+_+")$|^$";var V=s++;o[V]="^"+o[T]+"\\s*("+v+")$|^$";var M=s++;o[M]="(\\s*)"+o[T]+"\\s*("+_+"|"+o[A]+")",i[M]=new RegExp(o[M],"g");var B=s++;o[B]="^\\s*("+o[A]+")\\s+-\\s+("+o[A]+")\\s*$";var F=s++;o[F]="^\\s*("+o[I]+")\\s+-\\s+("+o[I]+")\\s*$";var $=s++;o[$]="(<|>)?=?\\s*\\*";for(var H=0;H<35;H++)r(H,o[H]),i[H]||(i[H]=new RegExp(o[H]));function K(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof G)return e;if("string"!=typeof e)return null;if(e.length>256)return null;if(!(t.loose?i[b]:i[w]).test(e))return null;try{return new G(e,t)}catch(e){return null}}function G(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof G){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>256)throw new TypeError("version is longer than 256 characters");if(!(this instanceof G))return new G(e,t);r("SemVer",e,t),this.options=t,this.loose=!!t.loose;var o=e.trim().match(t.loose?i[b]:i[w]);if(!o)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);-1===r&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},t.inc=function(e,t,r,n){"string"==typeof r&&(n=r,r=void 0);try{return new G(e,r).inc(t,n).version}catch(e){return null}},t.diff=function(e,t){if(J(e,t))return null;var r=K(e),n=K(t),i="";if(r.prerelease.length||n.prerelease.length){i="pre";var o="prerelease"}for(var s in r)if(("major"===s||"minor"===s||"patch"===s)&&r[s]!==n[s])return i+s;return o},t.compareIdentifiers=X;var Q=/^[0-9]+$/;function X(e,t){var r=Q.test(e),n=Q.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e0}function W(e,t,r){return Y(e,t,r)<0}function J(e,t,r){return 0===Y(e,t,r)}function Z(e,t,r){return 0!==Y(e,t,r)}function ee(e,t,r){return Y(e,t,r)>=0}function te(e,t,r){return Y(e,t,r)<=0}function re(e,t,r,n){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return J(e,r,n);case"!=":return Z(e,r,n);case">":return z(e,r,n);case">=":return ee(e,r,n);case"<":return W(e,r,n);case"<=":return te(e,r,n);default:throw new TypeError("Invalid operator: "+t)}}function ne(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof ne){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof ne))return new ne(e,t);r("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ie?this.value="":this.value=this.operator+this.semver.version,r("comp",this)}t.rcompareIdentifiers=function(e,t){return X(t,e)},t.major=function(e,t){return new G(e,t).major},t.minor=function(e,t){return new G(e,t).minor},t.patch=function(e,t){return new G(e,t).patch},t.compare=Y,t.compareLoose=function(e,t){return Y(e,t,!0)},t.rcompare=function(e,t,r){return Y(t,e,r)},t.sort=function(e,r){return e.sort((function(e,n){return t.compare(e,n,r)}))},t.rsort=function(e,r){return e.sort((function(e,n){return t.rcompare(e,n,r)}))},t.gt=z,t.lt=W,t.eq=J,t.neq=Z,t.gte=ee,t.lte=te,t.cmp=re,t.Comparator=ne;var ie={};function oe(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof oe)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new oe(e.raw,t);if(e instanceof ne)return new oe(e.value,t);if(!(this instanceof oe))return new oe(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){return this.parseRange(e.trim())}),this).filter((function(e){return e.length})),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function se(e){return!e||"x"===e.toLowerCase()||"*"===e}function ae(e,t,r,n,i,o,s,a,c,u,d,p,l){return((t=se(r)?"":se(n)?">="+r+".0.0":se(i)?">="+r+"."+n+".0":">="+t)+" "+(a=se(c)?"":se(u)?"<"+(+c+1)+".0.0":se(d)?"<"+c+"."+(+u+1)+".0":p?"<="+c+"."+u+"."+d+"-"+p:"<="+a)).trim()}function ce(e,t,n){for(var i=0;i0){var o=e[i].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}function ue(e,t,r){try{t=new oe(t,r)}catch(e){return!1}return t.test(e)}function de(e,t,r,n){var i,o,s,a,c;switch(e=new G(e,n),t=new oe(t,n),r){case">":i=z,o=te,s=W,a=">",c=">=";break;case"<":i=W,o=ee,s=z,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(ue(e,t,n))return!1;for(var u=0;u=0.0.0")),p=p||e,l=l||e,i(e.semver,p.semver,n)?p=e:s(e.semver,l.semver,n)&&(l=e)})),p.operator===a||p.operator===c)return!1;if((!l.operator||l.operator===a)&&o(e,l.semver))return!1;if(l.operator===c&&s(e,l.semver))return!1}return!0}ne.prototype.parse=function(e){var t=this.options.loose?i[L]:i[V],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1],"="===this.operator&&(this.operator=""),r[2]?this.semver=new G(r[2],this.options.loose):this.semver=ie},ne.prototype.toString=function(){return this.value},ne.prototype.test=function(e){return r("Comparator.test",e,this.options.loose),this.semver===ie||("string"==typeof e&&(e=new G(e,this.options)),re(e,this.operator,this.semver,this.options))},ne.prototype.intersects=function(e,t){if(!(e instanceof ne))throw new TypeError("a Comparator is required");var r;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return r=new oe(e.value,t),ue(this.value,r,t);if(""===e.operator)return r=new oe(this.value,t),ue(e.semver,r,t);var n=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),i=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),o=this.semver.version===e.semver.version,s=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=re(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=re(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return n||i||o&&s||a||c},t.Range=oe,oe.prototype.format=function(){return this.range=this.set.map((function(e){return e.join(" ").trim()})).join("||").trim(),this.range},oe.prototype.toString=function(){return this.range},oe.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var n=t?i[F]:i[B];e=e.replace(n,ae),r("hyphen replace",e),e=e.replace(i[M],"$1$2$3"),r("comparator trim",e,i[M]),e=(e=(e=e.replace(i[P],"$1~")).replace(i[q],"$1^")).split(/\s+/).join(" ");var o=t?i[L]:i[V],s=e.split(" ").map((function(e){return function(e,t){return r("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){r("caret",e,t);var n=t.loose?i[U]:i[N];return e.replace(n,(function(t,n,i,o,s){var a;return r("caret",e,t,n,i,o,s),se(n)?a="":se(i)?a=">="+n+".0.0 <"+(+n+1)+".0.0":se(o)?a="0"===n?">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":">="+n+"."+i+".0 <"+(+n+1)+".0.0":s?(r("replaceCaret pr",s),a="0"===n?"0"===i?">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+i+"."+(+o+1):">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+o+"-"+s+" <"+(+n+1)+".0.0"):(r("no pr"),a="0"===n?"0"===i?">="+n+"."+i+"."+o+" <"+n+"."+i+"."+(+o+1):">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+o+" <"+(+n+1)+".0.0"),r("caret return",a),a}))}(e,t)})).join(" ")}(e,t),r("caret",e),e=function(e,t){return e.trim().split(/\s+/).map((function(e){return function(e,t){var n=t.loose?i[j]:i[R];return e.replace(n,(function(t,n,i,o,s){var a;return r("tilde",e,t,n,i,o,s),se(n)?a="":se(i)?a=">="+n+".0.0 <"+(+n+1)+".0.0":se(o)?a=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":s?(r("replaceTilde pr",s),a=">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0"):a=">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0",r("tilde return",a),a}))}(e,t)})).join(" ")}(e,t),r("tildes",e),e=function(e,t){return r("replaceXRanges",e,t),e.split(/\s+/).map((function(e){return function(e,t){e=e.trim();var n=t.loose?i[x]:i[S];return e.replace(n,(function(t,n,i,o,s,a){r("xRange",e,t,n,i,o,s,a);var c=se(i),u=c||se(o),d=u||se(s);return"="===n&&d&&(n=""),c?t=">"===n||"<"===n?"<0.0.0":"*":n&&d?(u&&(o=0),s=0,">"===n?(n=">=",u?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",u?i=+i+1:o=+o+1),t=n+i+"."+o+"."+s):u?t=">="+i+".0.0 <"+(+i+1)+".0.0":d&&(t=">="+i+"."+o+".0 <"+i+"."+(+o+1)+".0"),r("xRange return",t),t}))}(e,t)})).join(" ")}(e,t),r("xrange",e),e=function(e,t){return r("replaceStars",e,t),e.trim().replace(i[$],"")}(e,t),r("stars",e),e}(e,this.options)}),this).join(" ").split(/\s+/);return this.options.loose&&(s=s.filter((function(e){return!!e.match(o)}))),s=s.map((function(e){return new ne(e,this.options)}),this)},oe.prototype.intersects=function(e,t){if(!(e instanceof oe))throw new TypeError("a Range is required");return this.set.some((function(r){return r.every((function(r){return e.set.some((function(e){return e.every((function(e){return r.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){return new oe(e,t).set.map((function(e){return e.map((function(e){return e.value})).join(" ").trim().split(" ")}))},oe.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new G(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":r&&!z(r,t)||(r=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}}))}if(r&&e.test(r))return r;return null},t.validRange=function(e,t){try{return new oe(e,t).range||"*"}catch(e){return null}},t.ltr=function(e,t,r){return de(e,t,"<",r)},t.gtr=function(e,t,r){return de(e,t,">",r)},t.outside=de,t.prerelease=function(e,t){var r=K(e,t);return r&&r.prerelease.length?r.prerelease:null},t.intersects=function(e,t,r){return e=new oe(e,r),t=new oe(t,r),e.intersects(t)},t.coerce=function(e){if(e instanceof G)return e;if("string"!=typeof e)return null;var t=e.match(i[k]);if(null==t)return null;return K(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}})),vt=(wt.SEMVER_SPEC_VERSION,wt.re,wt.src,wt.parse,wt.valid,wt.clean,wt.SemVer,wt.inc,wt.diff,wt.compareIdentifiers,wt.rcompareIdentifiers,wt.major,wt.minor,wt.patch,wt.compare,wt.compareLoose,wt.rcompare,wt.sort,wt.rsort,wt.gt,wt.lt,wt.eq,wt.neq,wt.gte,wt.lte,wt.cmp,wt.Comparator,wt.Range,wt.toComparators,wt.satisfies,wt.maxSatisfying,wt.minSatisfying,wt.minVersion,wt.validRange,wt.ltr,wt.gtr,wt.outside,wt.prerelease,wt.intersects,wt.coerce,wt.satisfies(process.version,"^6.12.0 || >=8.0.0")),_t=["RS256","RS384","RS512","ES256","ES384","ES512"],bt=["RS256","RS384","RS512"],Tt=["HS256","HS384","HS512"];vt&&(_t.splice(3,0,"PS256","PS384","PS512"),bt.splice(3,0,"PS256","PS384","PS512"));var Et=/^\s+|\s+$/g,Ct=/^[-+]0x[0-9a-f]+$/i,At=/^0b[01]+$/i,It=/^0o[0-7]+$/i,St=/^(?:0|[1-9]\d*)$/,xt=parseInt;function kt(e){return e!=e}function Ot(e,t){return function(e,t){for(var r=-1,n=e?e.length:0,i=Array(n);++r-1&&e%1==0&&e-1&&e%1==0&&e<=9007199254740991}(e.length)&&!function(e){var t=Ht(e)?qt.call(e):"";return"[object Function]"==t||"[object GeneratorFunction]"==t}(e)}function Ht(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Kt(e){return!!e&&"object"==typeof e}var Gt=function(e,t,r,n){var i;e=$t(e)?e:(i=e)?Ot(i,function(e){return $t(e)?Vt(e):Mt(e)}(i)):[],r=r&&!n?function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||Kt(e)&&"[object Symbol]"==qt.call(e)}(e))return NaN;if(Ht(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Ht(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Et,"");var r=At.test(e);return r||It.test(e)?xt(e.slice(2),r?2:8):Ct.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(r):0;var o=e.length;return r<0&&(r=Lt(o+r,0)),function(e){return"string"==typeof e||!Ft(e)&&Kt(e)&&"[object String]"==qt.call(e)}(e)?r<=o&&e.indexOf(t,r)>-1:!!o&&function(e,t,r){if(t!=t)return function(e,t,r,n){for(var i=e.length,o=r+(n?1:-1);n?o--:++o-1},Qt=Object.prototype.toString;var Xt=function(e){return!0===e||!1===e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Boolean]"==Qt.call(e)},Yt=/^\s+|\s+$/g,zt=/^[-+]0x[0-9a-f]+$/i,Wt=/^0b[01]+$/i,Jt=/^0o[0-7]+$/i,Zt=parseInt,er=Object.prototype.toString;function tr(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}var rr=function(e){return"number"==typeof e&&e==function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==er.call(e)}(e))return NaN;if(tr(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=tr(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(Yt,"");var r=Wt.test(e);return r||Jt.test(e)?Zt(e.slice(2),r?2:8):zt.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(e)},nr=Object.prototype.toString;var ir=function(e){return"number"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Number]"==nr.call(e)};var or=Function.prototype,sr=Object.prototype,ar=or.toString,cr=sr.hasOwnProperty,ur=ar.call(Object),dr=sr.toString,pr=function(e,t){return function(r){return e(t(r))}}(Object.getPrototypeOf,Object);var lr=function(e){if(!function(e){return!!e&&"object"==typeof e}(e)||"[object Object]"!=dr.call(e)||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e))return!1;var t=pr(e);if(null===t)return!0;var r=cr.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&ar.call(r)==ur},fr=Object.prototype.toString,mr=Array.isArray;var hr=function(e){return"string"==typeof e||!mr(e)&&function(e){return!!e&&"object"==typeof e}(e)&&"[object String]"==fr.call(e)},gr=/^\s+|\s+$/g,yr=/^[-+]0x[0-9a-f]+$/i,wr=/^0b[01]+$/i,vr=/^0o[0-7]+$/i,_r=parseInt,br=Object.prototype.toString;function Tr(e,t){var r;if("function"!=typeof t)throw new TypeError("Expected a function");return e=function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&"[object Symbol]"==br.call(e)}(e))return NaN;if(Er(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=Er(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(gr,"");var r=wr.test(e);return r||vr.test(e)?_r(e.slice(2),r?2:8):yr.test(e)?NaN:+e}(e))===1/0||e===-1/0){return 17976931348623157e292*(e<0?-1:1)}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function Er(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}var Cr=function(e){return Tr(2,e)},Ar=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];vt&&Ar.splice(3,0,"PS256","PS384","PS512");var Ir={expiresIn:{isValid:function(e){return rr(e)||hr(e)&&e},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(e){return rr(e)||hr(e)&&e},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(e){return hr(e)||Array.isArray(e)},message:'"audience" must be a string or array'},algorithm:{isValid:Gt.bind(null,Ar),message:'"algorithm" must be a valid string enum value'},header:{isValid:lr,message:'"header" must be an object'},encoding:{isValid:hr,message:'"encoding" must be a string'},issuer:{isValid:hr,message:'"issuer" must be a string'},subject:{isValid:hr,message:'"subject" must be a string'},jwtid:{isValid:hr,message:'"jwtid" must be a string'},noTimestamp:{isValid:Xt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:hr,message:'"keyid" must be a string'},mutatePayload:{isValid:Xt,message:'"mutatePayload" must be a boolean'}},Sr={iat:{isValid:ir,message:'"iat" should be a number of seconds'},exp:{isValid:ir,message:'"exp" should be a number of seconds'},nbf:{isValid:ir,message:'"nbf" should be a number of seconds'}};function xr(e,t,r,n){if(!lr(r))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(r).forEach((function(i){var o=e[i];if(o){if(!o.isValid(r[i]))throw new Error(o.message)}else if(!t)throw new Error('"'+i+'" is not allowed in "'+n+'"')}))}var kr={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},Or=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"],Pr=function(e,t,r,n){var i;if("function"!=typeof r||n||(n=r,r={}),r||(r={}),r=Object.assign({},r),i=n||function(e,t){if(e)throw e;return t},r.clockTimestamp&&"number"!=typeof r.clockTimestamp)return i(new st("clockTimestamp must be a number"));if(void 0!==r.nonce&&("string"!=typeof r.nonce||""===r.nonce.trim()))return i(new st("nonce must be a non-empty string"));var o=r.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return i(new st("jwt must be provided"));if("string"!=typeof e)return i(new st("jwt must be a string"));var s,a=e.split(".");if(3!==a.length)return i(new st("jwt malformed"));try{s=it(e,{complete:!0})}catch(e){return i(e)}if(!s)return i(new st("invalid token"));var c,u=s.header;if("function"==typeof t){if(!n)return i(new st("verify must be called asynchronous if secret or public key is provided as a callback"));c=t}else c=function(e,r){return r(null,t)};return c(u,(function(t,n){if(t)return i(new st("error in secret or public key callback: "+t.message));var c,d=""!==a[2].trim();if(!d&&n)return i(new st("jwt signature is required"));if(d&&!n)return i(new st("secret or public key must be provided"));if(d||r.algorithms||(r.algorithms=["none"]),r.algorithms||(r.algorithms=~n.toString().indexOf("BEGIN CERTIFICATE")||~n.toString().indexOf("BEGIN PUBLIC KEY")?_t:~n.toString().indexOf("BEGIN RSA PUBLIC KEY")?bt:Tt),!~r.algorithms.indexOf(s.header.alg))return i(new st("invalid algorithm"));try{c=nt.verify(e,s.header.alg,n)}catch(e){return i(e)}if(!c)return i(new st("invalid signature"));var p=s.payload;if(void 0!==p.nbf&&!r.ignoreNotBefore){if("number"!=typeof p.nbf)return i(new st("invalid nbf value"));if(p.nbf>o+(r.clockTolerance||0))return i(new ct("jwt not active",new Date(1e3*p.nbf)))}if(void 0!==p.exp&&!r.ignoreExpiration){if("number"!=typeof p.exp)return i(new st("invalid exp value"));if(o>=p.exp+(r.clockTolerance||0))return i(new dt("jwt expired",new Date(1e3*p.exp)))}if(r.audience){var l=Array.isArray(r.audience)?r.audience:[r.audience];if(!(Array.isArray(p.aud)?p.aud:[p.aud]).some((function(e){return l.some((function(t){return t instanceof RegExp?t.test(e):t===e}))})))return i(new st("jwt audience invalid. expected: "+l.join(" or ")))}if(r.issuer&&("string"==typeof r.issuer&&p.iss!==r.issuer||Array.isArray(r.issuer)&&-1===r.issuer.indexOf(p.iss)))return i(new st("jwt issuer invalid. expected: "+r.issuer));if(r.subject&&p.sub!==r.subject)return i(new st("jwt subject invalid. expected: "+r.subject));if(r.jwtid&&p.jti!==r.jwtid)return i(new st("jwt jwtid invalid. expected: "+r.jwtid));if(r.nonce&&p.nonce!==r.nonce)return i(new st("jwt nonce invalid. expected: "+r.nonce));if(r.maxAge){if("number"!=typeof p.iat)return i(new st("iat required when maxAge is specified"));var f=yt(r.maxAge,p.iat);if(void 0===f)return i(new st('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(o>=f+(r.clockTolerance||0))return i(new dt("maxAge exceeded",new Date(1e3*f)))}if(!0===r.complete){var m=s.signature;return i(null,{header:u,payload:p,signature:m})}return i(null,p)}))},Rr=function(e,t,r,n){"function"==typeof r?(n=r,r={}):r=r||{};var i="object"==typeof e&&!Buffer.isBuffer(e),o=Object.assign({alg:r.algorithm||"HS256",typ:i?"JWT":void 0,kid:r.keyid},r.header);function s(e){if(n)return n(e);throw e}if(!t&&"none"!==r.algorithm)return s(new Error("secretOrPrivateKey must have a value"));if(void 0===e)return s(new Error("payload is required"));if(i){try{!function(e){xr(Sr,!0,e,"payload")}(e)}catch(e){return s(e)}r.mutatePayload||(e=Object.assign({},e))}else{var a=Or.filter((function(e){return void 0!==r[e]}));if(a.length>0)return s(new Error("invalid "+a.join(",")+" option for "+typeof e+" payload"))}if(void 0!==e.exp&&void 0!==r.expiresIn)return s(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(void 0!==e.nbf&&void 0!==r.notBefore)return s(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{!function(e){xr(Ir,!1,e,"options")}(r)}catch(e){return s(e)}var c=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?delete e.iat:i&&(e.iat=c),void 0!==r.notBefore){try{e.nbf=yt(r.notBefore,c)}catch(e){return s(e)}if(void 0===e.nbf)return s(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(void 0!==r.expiresIn&&"object"==typeof e){try{e.exp=yt(r.expiresIn,c)}catch(e){return s(e)}if(void 0===e.exp)return s(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(kr).forEach((function(t){var n=kr[t];if(void 0!==r[t]){if(void 0!==e[n])return s(new Error('Bad "options.'+t+'" option. The payload already has an "'+n+'" property.'));e[n]=r[t]}}));var u=r.encoding||"utf8";if("function"!=typeof n)return nt.sign({header:o,payload:e,secret:t,encoding:u});n=n&&Cr(n),nt.createSign({header:o,privateKey:t,payload:e,encoding:u}).once("error",n).once("done",(function(e){n(null,e)}))};let jr=[];class Dr{constructor(e){this.options=Object.assign({baseUrl:"https://appleid.apple.com",timeout:1e4},e)}async _fetch(e,t){const{baseUrl:r}=this.options;return uniCloud.httpclient.request(r+e,t)}async verifyIdentityToken(e){const t=e.split(".")[0],{kid:r}=JSON.parse(Buffer.from(t,"base64").toString());if(!jr.length)try{jr=await this.getAuthKeys()}catch(e){return{code:10705,msg:e.message}}const n=this.getUsedKey(jr,r);if(!Object.keys(n).length&&!this.fetched)try{jr=await this.getAuthKeys()}catch(e){return{code:10705,msg:e.message}}let i=null;try{i=Pr(e,function(e,t){var r=Buffer.from(e,"base64"),n=Buffer.from(t,"base64"),i=r.toString("hex"),o=n.toString("hex");i=J(i),o=J(o);var s=i.length/2,a=o.length/2,c=ee(s),u=ee(a),d="30"+ee(s+a+c.length/2+u.length/2+2)+"02"+c+i+"02"+u+o;return"-----BEGIN RSA PUBLIC KEY-----\n"+Buffer.from(d,"hex").toString("base64").match(/.{1,64}/g).join("\n")+"\n-----END RSA PUBLIC KEY-----\n"}(n.n,n.e),{algorithms:n.alg})}catch(e){return{code:10705,msg:e.message}}return{code:0,msg:i}}async getAuthKeys(){const{status:e,data:t}=await this._fetch("/auth/keys",{method:"GET",dataType:"json",timeout:this.options.timeout});if(200!==e)throw new Error("request https://appleid.apple.com/auth/keys fail");return t.keys}getUsedKey(e,t){let r={};for(let n=0;nvoid 0===e))return{code:N,messageValues:{param:this.t("dcloud-appid")}};const r=await P.doc(e).get(),n=r&&r.data&&r.data[0];if(!n)return{code:10002};const i=Object.keys(q).reduce((e,t)=>{const r=t,i=function(e,t){return t.split(".").reduce((e,t)=>e&&e[t],e)}(n,t);return i&&e.push({[r]:i}),e},[]);let o;const s={dcloud_appid:Mr.in(t),_id:Mr.neq(n._id)},a={dcloud_appid:Mr.exists(!1),_id:Mr.neq(n._id)};switch(i.length){case 0:return{code:10004};case 1:o=Mr.or([Mr.and([i[0],s]),Mr.and([i[0],a])]);break;default:o=Mr.or([Mr.and([Mr.or(i),s]),Mr.and([Mr.or(i),a])])}const c=await P.where(o).limit(1).get();return c&&c.data&&c.data[0]?{code:10005}:{code:0}}const Fr=uniCloud.database().command;const $r=uniCloud.database();const Hr=uniCloud.database();const Kr=uniCloud.database();async function Gr(e){const t=["apiKey","apiSecret"];for(let r=0,n=t.length;r0){u=a.and(a.or(c),a.or({dcloud_appid:a.in(s)},{dcloud_appid:a.exists(!1)}));if((await P.where(u).limit(1).get()).data.length>0)return{code:10201,messageValues:{type:this.t("username")}}}const d={role:o,nickname:t,dcloud_appid:s,register_date:Date.now()};if(e&&(d.username=e),r){const{passwordHash:e,version:t}=this.encryptPwd(r);d.password=e,t&&(d.password_secret_version=t)}return n&&(d.mobile=n,d.mobile_confirmed=1),i&&(d.email=i,d.email_confirmed=1),{code:0,uid:(await P.add(d)).id}},getUserInfo:async function({uid:e,field:t}){if(!e)return{code:N,messageValues:{param:this.t("user-id")}};let r;if(t&&t.length){const n={};for(let e=0;evoid 0===e.dcloud_appid||e.dcloud_appid.includes(this.context.APPID));if(0===i.length)return{code:10002};if(i.length>1)return{code:10005};const o=i[0]._id;return this.resetPwd({uid:o,password:r})},setAvatar:async function(e){return await P.doc(e.uid).update({avatar:e.avatar}),{code:0,msg:""}},updatePwd:async function(e){const t=await P.doc(e.uid).get();if(t&&t.data&&t.data.length>0){if(0===this._checkPwd(t.data[0],e.oldPassword).code){const{passwordHash:r,version:n}=this.encryptPwd(e.newPassword),i={password:r,token:[]};n&&(i.password_secret_version=n);return E("upRes",await P.doc(t.data[0]._id).update(i)),{code:0,msg:""}}return{code:40202}}return{code:40201}},updateUser:async function(e){const t=e.uid;if(!t)return{code:N,messageValues:{param:this.t("user-id")}};delete e.uid;const{username:r,email:n}=e,{usernameToLowerCase:i,emailToLowerCase:o}=this._getConfig();let s=r&&r.trim(),a=n&&n.trim();return s&&(i&&(s=s.toLowerCase()),e.username=s),a&&(o&&(a=a.toLowerCase()),e.email=a),E("update -> upRes",await P.doc(t).update(e)),{code:0,msg:""}},banAccount:async function({uid:e}={}){return $.call(this,{uid:e,status:B})},unbanAccount:async function({uid:e}={}){return $.call(this,{uid:e,status:M})},closeAccount:async function({uid:e}={}){return $.call(this,{uid:e,status:F})},openAccount:async function({uid:e}={}){return $.call(this,{uid:e,status:M})},_getAlipayApi:function(){const e=this.context.PLATFORM,t=this._getConfig();if(!t.oauth||!t.oauth.alipay)throw new Error(this.t("config-param-require",{param:e+".alipay"}));return["appid","privateKey"].forEach(r=>{if(!t.oauth.alipay[r])throw new Error(this.t("config-param-require",{param:`${e}.alipay.${r}`}))}),Ur({...t.oauth.alipay})},_getValidInviteCode:async function({inviteCode:e}){let t,r=10;e?(r=1,t=e):t=Vr();let n=!1;try{for(;r>0&&!n;){r--;if(0===(await P.where({my_invite_code:t}).get()).data.length){n=!0;break}t=Vr()}t=Vr()}catch(e){}return n?{code:0,inviteCode:t}:e?{code:80401}:{code:80402}},_addUser:async function(e,{needPermission:t,autoSetDcloudAppid:r=!0}={}){const n=this._getConfig(),i={...e,dcloud_appid:r?[this.context.APPID]:[],register_date:Date.now()},o=(await P.add(i)).id;let s;if(n.removePermissionAndRoleFromToken)s=await this.createToken({uid:o,needPermission:t});else{const t=e.role||[];let r;r=0===t.length||t.includes("admin")?[]:await this._getPermissionListByRoleList(t),s=await this.createToken({uid:o,role:t,permission:r})}const{token:a,tokenExpired:c}=s;return await P.doc(o).update({token:[a]}),{token:a,tokenExpired:c,uid:o,type:"register",userInfo:Object.assign({},i,{token:[a]})}},_loginExec:async function(e,t={}){if(e.status===B)return{code:10001};if(e.status===F)return{code:10006};const r=this._getConfig();let n=e.token||[];"string"==typeof n&&(n=[n]);const i=this._getExpiredToken(n);let o;if(n=n.filter(e=>-1===i.indexOf(e)),r.removePermissionAndRoleFromToken){const r=t.needPermission;o=await this.createToken({uid:e._id,needPermission:r})}else{const t=e.role||[];let r;r=0===t.length||t.includes("admin")?[]:await this._getPermissionListByRoleList(t),o=await this.createToken({uid:e._id,role:t,permission:r})}const{token:s,tokenExpired:a}=o;n.push(s),e.token=n;const c={last_login_date:Date.now(),last_login_ip:this.context.CLIENTIP,token:n,...t.extraData};await P.doc(e._id).update(c);const u=Object.assign({},e,c);return{code:0,msg:"",token:s,uid:u._id,username:u.username,type:"login",userInfo:u,tokenExpired:a}},_registerExec:async function(e,{needPermission:t,autoSetDcloudAppid:r=!0}={}){const{my_invite_code:n}=e;if(this._getConfig().autoSetInviteCode||n){const t=await this._getValidInviteCode({inviteCode:n});if(t.code)return t;e.my_invite_code=t.inviteCode}const{PLATFORM:i,appId:o,appid:s,APPID:a,uniPlatform:c,appName:u,appVersion:d,appVersionCode:p,channel:l,clientIP:f,CLIENTIP:m,OS:h,osName:g}=this.context;return e.register_env={appid:o||s||a||"",uni_platform:c||i||"",os_name:g||h||"",app_name:u||"",app_version:d||"",app_version_code:p||"",channel:l?l+"":"",client_ip:f||m||""},{code:0,msg:"",...await this._addUser(e,{needPermission:t,autoSetDcloudAppid:r})}},_getWeixinApi:function(){const e=this.context.PLATFORM,t=this._getConfig();if(!t.oauth||!t.oauth.weixin)throw new Error(this.t("config-param-require",{param:e+".weixin"}));return["appid","appsecret"].forEach(r=>{if(!t.oauth.weixin[r])throw new Error(this.t("config-param-require",{param:`${e}.weixin.${r}`}))}),qr({...t.oauth.weixin})},_getQQApi:function(){const e=this.context.PLATFORM,t=this._getConfig();if(!t.oauth||!t.oauth.qq)throw new Error(this.t("config-param-require",{param:e+".qq"}));return["appid","appsecret"].forEach(r=>{if(!t.oauth.qq[r])throw new Error(this.t("config-param-require",{param:`${e}.qq.${r}`}))}),Nr({...t.oauth.qq})},_getMatchedUser:function(e,t){if(0===e.length)return{code:10002};let r;const n={},i={};for(let r=e.length-1;r>=0;r--){const o=e[r];for(let s=0;s0?{code:10003,messageValues:{target:"用户"}}:{code:0,msg:"",userMatched:r,fieldMatched:s,isFallbackValueMatched:!!s&&i[s]}},_getCurrentAppUser:function(e){const t=this.context.APPID;return e.filter(e=>void 0===e.dcloud_appid||null===e.dcloud_appid||e.dcloud_appid.indexOf(t)>-1||e.dcloud_appid.indexOf(null)>-1)},_checkLoginUserList:function(e){if(e&&1!==e.length)return e[0].status===F?{code:10006}:{code:10005}},setAuthorizedAppLogin:async function({uid:e,dcloudAppidList:t}={}){if("array"!==m(t))return{code:U,messageValues:{param:"dcloudAppidList",reason:this.t("type-array-required",{param:this.t("dcloud-appid-list")})}};if(t&&0!==t.length){const r=await Br.bind(this)({uid:e,dcloudAppidList:t});if(r.code)return r}return await P.doc(e).update({dcloud_appid:Mr.set(t)}),{code:0}},authorizeAppLogin:async function({uid:e,dcloudAppid:t}={}){const r=await Br.bind(this)({uid:e,dcloudAppidList:[t]});return r.code?r:(await P.doc(e).update({dcloud_appid:Mr.push(t)}),{code:0})},forbidAppLogin:async function({uid:e,dcloudAppid:t}={}){return e?(await P.doc(e).update({dcloud_appid:Mr.pull(t)}),{code:0}):{code:N,messageValues:{param:this.t("user-id")}}},acceptInvite:async function({uid:e,inviteCode:t}){const r=await P.where({_id:Fr.neq(e),inviter_uid:Fr.not(Fr.all([e])),my_invite_code:t}).get();if(1!==r.data.length)return{code:80501,msg:"邀请码无效"};const n=[r.data[0]._id].concat(r.data[0].inviter_uid||[]),i=await P.doc(e).field({my_invite_code:!0,inviter_uid:!0}).get();if(0===i.data.length)return{code:80502};if(i.data[0].inviter_uid&&i.data[0].inviter_uid.length>0)return{code:80503,msg:"邀请码不可修改"};const o=Date.now();return await P.doc(e).update({inviter_uid:n,invite_time:o}),await P.where({inviter_uid:e}).update({inviter_uid:Fr.push(n)}),{code:0,msg:""}},getInvitedUser:async function({uid:e,level:t=1,limit:r=20,offset:n=0,needTotal:i=!1}){const o={code:0,msg:"",invitedUser:(await P.where({["inviter_uid."+(t-1)]:e}).field({_id:!0,username:!0,mobile:!0,invite_time:!0}).orderBy("invite_time","desc").skip(n).limit(r).get()).data};if(i){const r=await P.where({["inviter_uid."+(t-1)]:e}).count();o.total=r.total}return o},setUserInviteCode:async function({uid:e,myInviteCode:t}){const r=await this._getValidInviteCode({inviteCode:t});return r.code?r:(await P.doc(e).update({my_invite_code:r.inviteCode}),{code:0,msg:"",myInviteCode:r.inviteCode})},loginByAlipay:async function(e){"string"==typeof e&&(e={code:e});const{needPermission:t,code:r,myInviteCode:n,role:i,type:o}=e,{openid:s}=await this._getAlipayApi().code2Session(r);if(!s)return{code:10501,messageValues:{account:this.t("alipay-account")}};let a=await P.where({ali_openid:s}).get();if(a=this._getCurrentAppUser(a.data),a&&a.length>0){if("register"===o)return{code:10502,messageValues:{type:this.t("alipay-account")}};if(1!==a.length)return{code:10005};const e=a[0],r=await this._loginExec(e,{needPermission:t});if(0!==r.code)return r;const{userInfo:n}=r;return{...r,openid:s,mobileConfirmed:1===n.mobile_confirmed,emailConfirmed:1===n.email_confirmed}}{if("login"===o)return{code:10503,messageValues:{type:this.t("alipay-account")}};const e={ali_openid:s};e.my_invite_code=n,e.role=i;const r=await this._registerExec(e,{needPermission:t});return 0!==r.code?r:{...r,openid:s,mobileConfirmed:!1,emailConfirmed:!1}}},loginByEmail:async function(e){let{email:t,code:r,password:n,myInviteCode:i,type:o,needPermission:s,role:a}=e||{};if(t=t&&t.trim(),!t)return{code:N,messageValues:{param:"邮箱"}};const{emailToLowerCase:c}=this._getConfig();let u=t;c&&(u=t.toLowerCase());const d=await this.verifyCode({email:u,code:r,type:o||"login"});if(0!==d.code)return d;let p={email:t,email_confirmed:1};const l={field:"email",value:t},f=$r.command;u!==t&&(p=f.or(p,{email:u,email_confirmed:1}),l.fallbackValue=u);let m=await P.where(p).get();if(m=this._getCurrentAppUser(m.data),m&&m.length>0){if("register"===o)return{code:10301,messageValues:{type:"邮箱"}};const e=this._getMatchedUser(m,[l]);if(e.code)return e;const{userMatched:t}=e,r=await this._loginExec(t,{needPermission:s});return 0!==r.code?r:{...r,email:u}}{if("login"===o)return{code:10302,messageValues:{type:"邮箱"}};const e={email:u,email_confirmed:1},t=n&&n.trim();if(t){const{passwordHash:r,version:n}=this.encryptPwd(t);e.password=r,n&&(e.password_secret_version=n)}e.my_invite_code=i,e.role=a;const r=await this._registerExec(e,{needPermission:s});return 0!==r.code?r:{...r,email:u}}},loginBySms:async function({mobile:e,code:t,password:r,inviteCode:n,myInviteCode:i,type:o,needPermission:s,role:a}){if(!(e=e&&e.trim()))return{code:N,messageValues:{param:this.t("mobile")}};const c=this._getConfig();if(c.forceInviteCode&&!o)throw new Error(this.t("login-with-invite-type-required"));const u=await this.verifyCode({mobile:e,code:t,type:o||"login"});if(0!==u.code)return u;const d={mobile:e,mobile_confirmed:1};let p=await P.where(d).get();if(p=this._getCurrentAppUser(p.data),p&&p.length>0){if("register"===o)return{code:10201,messageValues:{type:this.t("mobile")}};if(1!==p.length)return{code:10005};const t=p[0],r=await this._loginExec(t,{needPermission:s});return 0!==r.code?r:{...r,mobile:e}}{const t=Date.now();if("login"===o)return{code:10202,messageValues:{type:this.t("mobile")}};const u={mobile:e,mobile_confirmed:1,register_ip:this.context.CLIENTIP,register_date:t},d=r&&r.trim();if(d){const{passwordHash:e,version:t}=this.encryptPwd(d);u.password=e,t&&(u.password_secret_version=t)}if(n){const e=await P.where({my_invite_code:n}).get();if(1!==e.data.length)return{code:10203};u.inviter_uid=[e.data[0]._id].concat(e.data[0].inviter_uid||[]),u.invite_time=t}else if(c.forceInviteCode)return{code:10203};u.my_invite_code=i,u.role=a;const p=await this._registerExec(u,{needPermission:s});return 0!==p.code?p:{...p,mobile:e}}},loginByWeixin:async function(e){"string"==typeof e&&(e={code:e});const{needPermission:t,platform:r,code:n,myInviteCode:i,role:o,type:s}=e,a=r||this.context.PLATFORM,c="mp-weixin"===a,{openid:u,unionid:d,sessionKey:p,accessToken:l,refreshToken:f,expired:m}=await this._getWeixinApi()[c?"code2Session":"getOauthAccessToken"](n);if(!u)return{code:10401,messageValues:{account:"微信openid"}};let h;h=c?{sessionKey:p}:{accessToken:l,refreshToken:f,accessTokenExpired:m};const g=Hr.command,y=[{wx_openid:{[a]:u}}];d&&y.push({wx_unionid:d});let w=await P.where(g.or(...y)).get();if(w=this._getCurrentAppUser(w.data),w&&w.length>0){if("register"===s)return{code:10402,messageValues:{type:this.t("wechat-account")}};if(1!==w.length)return{code:10005};const e=w[0],r={wx_openid:{[a]:u}};d&&(r.wx_unionid=d);const n=await this._loginExec(e,{needPermission:t,extraData:r});if(0!==n.code)return n;const{userInfo:i}=n;return{...n,openid:u,unionid:d,...h,mobileConfirmed:1===i.mobile_confirmed,emailConfirmed:1===i.email_confirmed}}{if("login"===s)return{code:10403,messageValues:{type:this.t("wechat-account")}};const e={wx_openid:{[a]:u},wx_unionid:d};e.my_invite_code=i,e.role=o;const r=await this._registerExec(e,{needPermission:t});return 0!==r.code?r:{...r,openid:u,unionid:d,...h,mobileConfirmed:!1,emailConfirmed:!1}}},loginByQQ:async function({code:e,accessToken:t,myInviteCode:r,needPermission:n,role:i,type:o}={}){const s=this.context.PLATFORM,a="mp-qq"===s,{openid:c,unionid:u,sessionKey:d}=await this._getQQApi()[a?"code2Session":"getOpenidByToken"]({code:e,accessToken:t});if(!c)return{code:10801,messageValues:{account:"qq openid"}};const p={accessToken:t,sessionKey:d},l=Kr.command,f=[{qq_openid:{[s]:c}}];u&&f.push({qq_unionid:u});let m=await P.where(l.or(...f)).get();if(m=this._getCurrentAppUser(m.data),m&&m.length>0){if("register"===o)return{code:10802,messageValues:{type:this.t("qq-account")}};if(1!==m.length)return{code:10005};const e=m[0],t={qq_openid:{[s]:c}};u&&(t.qq_unionid=u);const r=await this._loginExec(e,{needPermission:n,extraData:t});if(0!==r.code)return r;const{userInfo:i}=r;return{...r,openid:c,unionid:u,...p,mobileConfirmed:1===i.mobile_confirmed,emailConfirmed:1===i.email_confirmed}}{if("login"===o)return{code:10803,messageValues:{type:this.t("qq-account")}};const e={qq_openid:{[s]:c},qq_unionid:u};e.my_invite_code=r,e.role=i;const t=await this._registerExec(e);return 0!==t.code?t:{...t,openid:c,unionid:u,...p,mobileConfirmed:!1,emailConfirmed:!1}}},loginByUniverify:async function({openid:e,access_token:t,password:r,inviteCode:n,myInviteCode:i,type:o,needPermission:s,role:a}){const c=this._getConfig(),u=c&&c.service&&c.service.univerify;if(!u)throw new Error(this.t("uni-verify-config-required"));if(c.forceInviteCode&&!o)throw new Error(this.t("login-with-invite-type-required"));const d=await Gr.bind(this)({...u,openid:e,access_token:t});if(0!==d.code)return d;const p=String(d.phoneNumber);let l=await P.where({mobile:p,mobile_confirmed:1}).get();if(l=this._getCurrentAppUser(l.data),l&&l.length>0){if("register"===o)return{code:10601,messageValues:{type:this.t("mobile")}};if(1!==l.length)return{code:10005};const e=l[0],t=await this._loginExec(e,{needPermission:s});return 0!==t.code?t:{...t,mobile:p}}if("login"===o)return{code:10602,messageValues:{type:this.t("mobile")}};const f=Date.now(),m={mobile:p,my_invite_code:i,mobile_confirmed:1,role:a},h=r&&r.trim();if(h){const{passwordHash:e,version:t}=this.encryptPwd(h);m.password=e,t&&(m.password_secret_version=t)}if(n){let e=await P.where({my_invite_code:n}).get();if(1!==e.data.length)return{code:10203};e=e.data[0],m.inviter_uid=[e._id].concat(e.inviter_uid||[]),m.invite_time=f}else if(c.forceInviteCode)return{code:10203};m.my_invite_code=i;const g=await this._registerExec(m,{needPermission:s});return 0!==g.code?g:{...g,mobile:p}},loginByApple:async function({nickName:e,fullName:t,identityToken:r,myInviteCode:n,type:i,needPermission:o,role:s}){const a=this._getConfig(),c=a&&a.oauth&&a.oauth.apple,u=c&&c.bundleId;if(!u)throw new Error(this.t("config-param-require",{param:"(app || app-plus).apple.bundleId"}));if(!r)return{code:N,messageValues:{param:"identityToken"}};t=e||(t&&Object.keys(t).length>0?t.familyName+t.givenName:"");const{code:d,msg:p}=await Lr().verifyIdentityToken(r);if(0!==d)return{code:d,msg:p,messageValues:{account:this.t("apple-account")}};const{iss:l,sub:f,aud:m,email:h}=p;if("https://appleid.apple.com"!==l)return{code:10706,messageValues:{account:this.t("apple-account")}};if(!f)return{code:10701,messageValues:{account:this.t("apple-account")}};if(u!==m)return{code:10702,messageValues:{account:this.t("apple-account")}};const g=t||"User-"+(h?h.split("@")[0]:Math.random().toString(32).slice(2));let y=await P.where({apple_openid:f}).get();if(y=this._getCurrentAppUser(y.data),y&&y.length>0){if("register"===i)return{code:10703,messageValues:{type:this.t("apple-account")}};if(1!==y.length)return{code:10005};const e=y[0],t=await this._loginExec(e,{needPermission:o});return 0!==t.code?t:{...t,openid:f}}if("login"===i)return{code:10704,messageValues:{type:this.t("apple-account")}};const w={nickname:g,apple_openid:f,my_invite_code:n,role:s},v=await this._registerExec(w,{needPermission:o});return 0!==v.code?v:{...v,openid:f}},login:async function({username:e,password:t,queryField:r=[],needPermission:n}){const i=Qr.command,o=[];r&&r.length||(r=["username"]),r.length>1&&console.warn(this.t("query-field-warning"));const{usernameToLowerCase:s,emailToLowerCase:a,passwordErrorLimit:c,passwordErrorRetryTime:u}=this._getConfig(),d={email:{email_confirmed:1},mobile:{mobile_confirmed:1}},p={},l=e&&e.trim();if(!l)return{code:N,messageValues:{param:this.t("username")}};s&&(p.username=l.toLowerCase()),a&&(p.email=l.toLowerCase());const f=[];r.forEach(t=>{o.push({[t]:e,...d[t]});const r={field:t,value:e};"username"===t&&p.username!==e?(o.push({[t]:p.username,...d[t]}),r.fallbackValue=p.username):"email"===t&&p.email!==e&&(o.push({[t]:p.email,...d[t]}),r.fallbackValue=p.email),f.push(r)});let m=await P.where(i.or(...o)).get();m=this._getCurrentAppUser(m.data);const h=this.context.CLIENTIP,g=this._getMatchedUser(m,f);if(g.code)return g;const{userMatched:y}=g;let w=y.login_ip_limit||[];w=w.filter(e=>e.last_error_time>Date.now()-1e3*u);let v=w.find(e=>e.ip===h);if(v&&v.error_times>=c)return{code:10103};const _=t&&t.trim();if(!_)return{code:N,messageValues:{param:"密码"}};const b=this._checkPwd(y,_);if(0===b.code){const e=w.indexOf(v);e>-1&&w.splice(e,1);const t={login_ip_limit:w},{passwordHash:r,passwordVersion:i}=b;r&&i&&(t.password=r,t.password_secret_version=i);const o=await this._loginExec(y,{needPermission:n,extraData:t});return o.code,o}return v?(v.error_times++,v.last_error_time=Date.now()):(v={ip:h,error_times:1,last_error_time:Date.now()},w.push(v)),await P.doc(y._id).update({login_ip_limit:w}),{code:10102,msg:"密码错误"}},register:async function(e){const t=[],r=[{name:"username",desc:this.t("username")},{name:"email",desc:this.t("email"),extraCond:{email_confirmed:1}},{name:"mobile",desc:this.t("mobile"),extraCond:{mobile_confirmed:1}}],{usernameToLowerCase:n,emailToLowerCase:i}=this._getConfig();r.forEach(r=>{const o=r.name;let s=e[o]&&e[o].trim();s?(("username"===r.name&&n||"email"===r.name&&i)&&(s=s.toLowerCase()),e[o]=s,t.push({[o]:s,...r.extraCond})):delete e[o]});const{username:o,email:s,mobile:a,myInviteCode:c,needPermission:u,autoSetDcloudAppid:d=!0}=e;if("needPermission"in e&&delete e.needPermission,"autoSetDcloudAppid"in e&&delete e.autoSetDcloudAppid,0===t.length)return{code:20101,messageValues:{param:this.t("user-unique-param")}};const p=Xr.command;let l=await P.where(p.or(...t)).get();if(l=this._getCurrentAppUser(l.data),l&&l.length>0){const t=l[0];if(t.status===F)return{code:10006};for(let n=0;nt[e]===i.extraCond[e])),t[i.name]===e[i.name]&&o)return{code:20102,messageValues:{type:i.desc}}}}const f=e.password&&e.password.trim();if(!f)return{code:N,messageValues:{param:this.t("password")}};const{passwordHash:m,version:h}=this.encryptPwd(f);e.password=m,h&&(e.password_secret_version=h),e.my_invite_code=c,delete e.myInviteCode;const g=await this._registerExec(e,{needPermission:u,autoSetDcloudAppid:d});return 0!==g.code?g:{...g,username:o,email:s,mobile:a}},logout:async function(e){const t=await this.checkToken(e);if(t.code)return t;const r=Yr.command;return await P.doc(t.uid).update({token:r.pull(e)}),{code:0,msg:""}},getRoleByUid:async function({uid:e}){if(!e)return{code:N,messageValues:{param:this.t("user-id")}};const t=await P.doc(e).get();return 0===t.data.length?{code:L}:{code:0,msg:"",role:t.data[0].role||[]}},getPermissionByRole:async function({roleID:e}){if(!e)return{code:N,messageValues:{param:"roleID"}};if("admin"===e){return{code:0,msg:"",permission:(await D.limit(1e3).get()).data.map(e=>e.permission_id)}}const t=await j.where({role_id:e}).get();return 0===t.data.length?{code:V}:{code:0,msg:"",permission:t.data[0].permission||[]}},getPermissionByUid:async function({uid:e}={}){const t=await P.aggregate().match({_id:e}).project({role:!0}).unwind("$role").lookup({from:"uni-id-roles",localField:"role",foreignField:"role_id",as:"roleDetail"}).unwind("$roleDetail").replaceRoot({newRoot:"$roleDetail"}).end(),r=[],n=[];return t.data.forEach(e=>{n.push(e.role_id),r.push(...e.permission)}),{code:0,msg:"",role:n,permission:A(r)}},bindRole:async function({uid:e,roleList:t,reset:r=!1}){const n={};return"string"==typeof t&&(t=[t]),n.role=r?t:zr.push(t),await P.doc(e).update(n),{code:0,msg:""}},bindPermission:async function({roleID:e,permissionList:t,reset:r=!1}){const n={};return"string"==typeof t&&(t=[t]),n.permission=r?t:zr.push(t),await j.where({role_id:e}).update(n),{code:0,msg:""}},unbindRole:async function({uid:e,roleList:t}){return"string"==typeof t&&(t=[t]),await P.doc(e).update({role:zr.pull(zr.in(t))}),{code:0,msg:""}},unbindPermission:async function({roleID:e,permissionList:t}){return"string"==typeof t&&(t=[t]),await j.where({role_id:e}).update({permission:zr.pull(zr.in(t))}),{code:0,msg:""}},addRole:async function({roleID:e,roleName:t,comment:r,permission:n=[]}){return e?"admin"===e?{code:U,messageValues:{param:"roleID",reason:this.t("add-role-admin-is-not-allowed")}}:(await j.add({role_id:e,role_name:t,comment:r,permission:n,create_date:Date.now()}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("role-id")}}},addPermission:async function({permissionID:e,permissionName:t,comment:r}){return e?(await D.add({permission_id:e,permission_name:t,comment:r,create_date:Date.now()}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("permission-id")}}},getRoleList:async function({limit:e=20,offset:t=0,needTotal:r=!0}){const n={code:0,msg:"",roleList:(await j.skip(t).limit(e).get()).data};if(r){const{total:e}=await j.where({_id:zr.exists(!0)}).count();n.total=e}return n},getRoleInfo:async function(e){const t=await j.where({role_id:e}).get();return 0===t.data.length?{code:V}:{code:0,...t.data[0]}},updateRole:async function({roleID:e,roleName:t,comment:r,permission:n}){return e?(await j.where({role_id:e}).update({role_name:t,comment:r,permission:n}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("role-id")}}},deleteRole:async function({roleID:e}){const t=m(e);if("string"===t)e=[e];else if("array"!==t)throw new Error("typeof roleID must be array or string");return await j.where({role_id:zr.in(e)}).remove(),await P.where({role:zr.elemMatch(zr.in(e))}).update({role:zr.pullAll(e)}),{code:0,msg:""}},getPermissionList:async function({limit:e=20,offset:t=0,needTotal:r=!0}){const n={code:0,msg:"",permissionList:(await D.skip(t).limit(e).get()).data};if(r){const{total:e}=await D.where({_id:zr.exists(!0)}).count();n.total=e}return n},getPermissionInfo:async function(e){const t=await D.where({permission_id:e}).get();return 0===t.data.length?{code:N,messageValues:{param:this.t("permission-id")}}:{code:0,...t.data[0]}},updatePermission:async function({permissionID:e,permissionName:t,comment:r}){return e?(await D.where({permission_id:e}).update({permission_name:t,comment:r}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("permission-id")}}},deletePermission:async function({permissionID:e}){const t=m(e);if("string"===t)e=[e];else if("array"!==t)throw new Error("typeof permissionID must be array or string");return await D.where({permission_id:zr.in(e)}).remove(),await j.where({permission:zr.elemMatch(zr.in(e))}).update({permission:zr.pullAll(e)}),{code:0,msg:""}},bindAlipay:async function({uid:e,code:t,platform:r}){const n=r||this.context.PLATFORM,{openid:i}=await this._getAlipayApi({platform:n}).code2Session(t);if(!i)return{code:60401,messageValues:{account:this.t("alipay-account")}};let o=await P.where({ali_openid:i}).get();return o=this._getCurrentAppUser(o.data),o&&o.length>0?{code:60402,messageValues:{type:this.t("alipay-account")}}:(await P.doc(e).update({ali_openid:i}),{code:0,openid:i,msg:""})},bindEmail:async function(e){let{uid:t,email:r,code:n}=e||{};if(r=r&&r.trim(),!r)return{code:N,messageValues:{param:this.t("email")}};if(!n)return{code:N,messageValues:{param:this.t("verify-code")}};const{emailToLowerCase:i}=this._getConfig();i&&(r=r.toLowerCase());let o=await P.where({email:r,email_confirmed:1}).get();if(o=this._getCurrentAppUser(o.data),o&&o.length>0)return{code:60201,messageValues:{type:this.t("email")}};const s=await this.verifyCode({email:r,code:n,type:"bind"});return 0!==s.code?s:(await P.doc(t).update({email:r,email_confirmed:1}),{code:0,msg:"",email:r})},bindMobile:async function(e){let{uid:t,mobile:r,code:n,openid:i,access_token:o,type:s="sms"}=e||{};if("univerify"===s){const e=this._getConfig(),t=e&&e.service&&e.service.univerify;if(!t)throw new Error("请在config.json中配置service.univerify下一键登录相关参数");const n=await Gr.bind(this)({...t,openid:i,access_token:o});if(0!==n.code)return n;r=""+n.phoneNumber}let a=await P.where({mobile:r,mobile_confirmed:1}).get();if(a=this._getCurrentAppUser(a.data),a&&a.length>0)return{code:60101,messageValues:{type:"手机号"}};if("sms"===s&&"code"in e){if(!r)return{code:N,messageValues:{param:this.t("mobile")}};if(!n)return{code:N,messageValues:{param:this.t("verify-code")}};const e=await this.verifyCode({mobile:r,code:n,type:"bind"});if(0!==e.code)return e}return await P.doc(t).update({mobile:r,mobile_confirmed:1}),{code:0,msg:"",mobile:r}},bindWeixin:async function({uid:e,code:t,platform:r}){const n=r||this.context.PLATFORM,i="mp-weixin"===n,{openid:o,unionid:s,sessionKey:a,accessToken:c,refreshToken:u,expired:d}=await this._getWeixinApi({platform:n})[i?"code2Session":"getOauthAccessToken"](t);if(!o)return{code:60301,messageValues:{account:"微信openid"}};const p=Wr.command,l=[{wx_openid:{[n]:o}}];s&&l.push({wx_unionid:s});let f=await P.where(p.or(...l)).get();if(f=this._getCurrentAppUser(f.data),f&&f.length>0)return{code:60302,messageValues:{type:this.t("wechat-account")}};const m={wx_openid:{[n]:o}};let h;return s&&(m.wx_unionid=s),await P.doc(e).update(m),h=i?{sessionKey:a}:{accessToken:c,refreshToken:u,accessTokenExpired:d},{code:0,msg:"",openid:o,unionid:s,...h}},bindQQ:async function({uid:e,code:t,accessToken:r,platform:n}={}){const i=n||this.context.PLATFORM,o="mp-qq"===i,{openid:s,unionid:a,sessionKey:c}=await this._getQQApi()[o?"code2Session":"getOpenidByToken"]({code:t,accessToken:r});if(!s)return{code:60501,messageValues:{account:"qq openid"}};const u=Jr.command,d=[{qq_openid:{[i]:s}}];a&&d.push({qq_unionid:a});let p=await P.where(u.or(...d)).get();if(p=this._getCurrentAppUser(p.data),p&&p.length>0)return{code:60502,messageValues:{type:this.t("qq-account")}};const l={qq_openid:{[i]:s}};return a&&(l.qq_unionid=a),await P.doc(e).update(l),{code:0,msg:"",openid:s,unionid:a,...{accessToken:r,sessionKey:c}}},unbindAlipay:async function(e){const t=Zr.command,r=await P.doc(e).update({ali_openid:t.remove()});return E("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70401}},unbindEmail:async function(e){let{uid:t,email:r,code:n}=e||{};if(r=r&&r.trim(),!t||!r)return{code:N,messageValues:{param:t?this.t("email"):this.t("user-id")}};const{emailToLowerCase:i}=this._getConfig();if("code"in e){const e=await this.verifyCode({email:r,code:n,type:"unbind"});if(0!==e.code)return e}const o=en.command;let s={_id:t,email:r};if(i){const e=r.toLowerCase();e!==r&&(s=o.or(s,{_id:t,email:e}))}return 1===(await P.where(s).update({email:o.remove(),email_confirmed:o.remove()})).updated?{code:0,msg:""}:{code:70201}},unbindMobile:async function(e){const{uid:t,mobile:r,code:n}=e||{};if("code"in e){const e=await this.verifyCode({mobile:r,code:n,type:"unbind"});if(0!==e.code)return e}const i=tn.command;return 1===(await P.where({_id:t,mobile:r}).update({mobile:i.remove(),mobile_confirmed:i.remove()})).updated?{code:0,msg:""}:{code:70101}},unbindWeixin:async function(e){const t=rn.command,r=await P.doc(e).update({wx_openid:t.remove(),wx_unionid:t.remove()});return E("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70301}},unbindQQ:async function(e){const t=nn.command,r=await P.doc(e).update({qq_openid:t.remove(),qq_unionid:t.remove()});return E("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70501}},getSupportedLoginType:function({appid:e,platform:t}={}){if(!e||!t)throw new Error("Parameter appid and platform is required");const r=this._getConfig({appid:e,platform:t}),n=["username-password","mobile-password","email-password"];for(const e in on)on[e](r)&&n.push(e);return{supportedLoginType:n}},code2SessionAlipay:async function(e){let t=e;"string"==typeof e&&(t={code:e});try{const e=t.platform||this.context.PLATFORM,r=await this._getAlipayApi({platform:e}).code2Session(t.code);return r.openid?{code:0,msg:"",...r}:{code:80701,messageValues:{account:this.t("alipay-account")}}}catch(e){return console.error(e),{code:80702,messageValues:{account:this.t("alipay-account")}}}},code2SessionWeixin:async function(e){let t=e;"string"==typeof e&&(t={code:e});try{const e=t.platform||this.context.PLATFORM,r=await this._getWeixinApi({platform:e})["mp-weixin"===e?"code2Session":"getOauthAccessToken"](t.code);return r.openid?{code:0,msg:"",...r}:{code:80601,messageValues:{account:"微信openid"}}}catch(e){return console.error(e),{code:80602,messageValues:{account:"微信openid"}}}},verifyAppleIdentityToken:async function({identityToken:e,platform:t}){const r=t||this.context.PLATFORM,{code:n,msg:i}=await Lr({clientType:r}).verifyIdentityToken(e);return 0!==n?{code:n,msg:i}:{code:n,msg:"验证通过",...i}},wxBizDataCrypt:async function({code:e,sessionKey:r,encryptedData:n,iv:i}){if(!n)return{code:N,messageValues:{param:"encryptedData"}};if(!i)return{code:N,messageValues:{param:"iv"}};if(!e&&!r)return{code:N,messageValues:{param:"sessionKey"}};const o=this._getWeixinApi();if(!r){const t=await o.code2Session(e);if(!t.sessionKey)return{code:80801};r=t.sessionKey}r=Buffer.from(r,"base64"),n=Buffer.from(n,"base64"),i=Buffer.from(i,"base64");try{var s=t.createDecipheriv("aes-128-cbc",r,i);s.setAutoPadding(!0);var a=s.update(n,"binary","utf8");a+=s.final("utf8"),a=JSON.parse(a)}catch(e){return console.error(e),{code:80802}}return a.watermark.appid!==o.options.appId?{code:80803}:{code:0,msg:"",...a}},getWeixinUserInfo:async function({accessToken:e,openid:t}={}){const r=this.context.PLATFORM;if("app"!==r&&"app-plus"!==r)throw new Error(this.t("limit-client-platform"));try{return{code:0,msg:"",...await this._getWeixinApi().getUserInfo({accessToken:e,openid:t})}}catch(e){return console.error(e),{code:80901}}},encryptPwd:function(e,{value:r,version:n}={}){if(!(e=e&&e.trim()))throw new Error(this.t("param-required",{param:this.t("password")}));if(!r){const e=this._getConfig(),{passwordSecret:t}=e;if("array"===m(t)){const e=t.sort((e,t)=>e.version-t.version);r=e[e.length-1].value,n=e[e.length-1].version}else r=t}if(!r)throw new Error(this.t("param-error",{param:"passwordSecret",reason:"invalid passwordSecret"}));const i=t.createHmac("sha1",r.toString("ascii"));return i.update(e),{passwordHash:i.digest("hex"),version:n}},checkToken:async function(e,{needPermission:t,needUserInfo:r=!0}={}){const n=this._getConfig(),i=this._verifyToken(e);if(i.code)return i;const{uid:o,needPermission:s,role:a,permission:c,exp:u,iat:d,...p}=i,l=a&&c;t=void 0===t?s:t;const f=n.removePermissionAndRoleFromToken||!l||r,m=!n.removePermissionAndRoleFromToken&&!l||n.removePermissionAndRoleFromToken&&l||n.tokenExpiresThreshold&&u-Date.now()/1e3this._createTokenInternal({signContent:e,config:o})):this._createTokenInternal({signContent:a,config:o})},_updateToken:async function({uid:e,tokenList:t,removeToken:r=[],addToken:n=[]}={}){if(!t){const r=await P.doc(e).get(),n=r.data&&r.data[0];t=n&&n.token||[]}"string"==typeof t&&(t=[t]);const i=this._getExpiredToken(t);(t=t.filter(e=>-1===i.indexOf(e))).push(...n);for(let e=0;ee.version-t.version);let c;if(c=n?a.find(e=>e.version===n):a[0],!c)return{code:3};const u=a[a.length-1],{passwordHash:d}=this.encryptPwd(t,c);if(d===r){const e={code:0};if(c!==u){const{passwordHash:r,version:n}=this.encryptPwd(t,u);e.passwordHash=r,e.passwordVersion=n}return e}return{code:4,message:""}},_verifyToken:function(e){const t=this._getConfig();let r;try{r=Pr(e,t.tokenSecret)}catch(e){return"TokenExpiredError"===e.name?{code:30203,err:e}:{code:30204,err:e}}return t.bindTokenToDevice&&r.clientId&&r.clientId!==this._getClientUaHash()?{code:30201}:{code:0,message:"",...r}},_getExpiredToken:function(e){const t=this._getConfig(),r=[];return e.forEach(e=>{try{Pr(e,t.tokenSecret)}catch(t){r.push(e)}}),r},_getPermissionListByRoleList:async function(e){if(!Array.isArray(e))return[];if(0===e.length)return[];if(e.includes("admin")){return(await D.limit(500).get()).data.map(e=>e.permission_id)}const t=await j.where({role_id:sn.in(e)}).get(),r=[];return t.data.forEach(e=>{Array.prototype.push.apply(r,e.permission)}),A(r)},_getClientUaHash:function(){const e=t.createHash("md5"),r=/MicroMessenger/i.test(this.context.CLIENTUA)?this.context.CLIENTUA.replace(/(MicroMessenger\S+).*/i,"$1"):this.context.CLIENTUA;return e.update(r),e.digest("hex")},_createTokenInternal:function({signContent:e,config:t}){if(t.tokenExpiresIn&&t.tokenExpiresThreshold&&t.tokenExpiresIn<=t.tokenExpiresThreshold)throw new Error(this.t("token-expires-config-warning"));return"object"===m(e)&&e.uid?(t.bindTokenToDevice&&(e.clientId=this._getClientUaHash()),{token:Rr(e,t.tokenSecret,{expiresIn:t.tokenExpiresIn}),tokenExpired:Date.now()+1e3*t.tokenExpiresIn}):{code:30101,messageValues:{param:this.t("user-id")}}},setVerifyCode:async function({mobile:e,email:t,code:r,expiresIn:n,type:i}){if(t=t&&t.trim(),e=e&&e.trim(),t){const{emailToLowerCase:e}=this._getConfig();e&&(t=t.toLowerCase())}if(!e&&!t)return{code:50101,messageValues:{param:"手机号或邮箱"}};if(e&&t)return{code:50102,messageValues:{param:"参数",reason:"手机号和邮箱不可同时存在"}};r||(r=C()),n||(n=180);const o=Date.now(),s={mobile:e,email:t,type:i,code:r,state:0,ip:this.context.CLIENTIP,created_at:o,expired_at:o+1e3*n};return await R.add(s),{code:0,mobile:e,email:t}},verifyCode:async function({mobile:e,email:t,code:r,type:n}){if(t=t&&t.trim(),e=e&&e.trim(),t){const{emailToLowerCase:e}=this._getConfig();e&&(t=t.toLowerCase())}if(!e&&!t)return{code:50201,messageValues:{param:"手机号或邮箱"}};if(e&&t)return{code:50203,messageValues:{param:"参数",reason:"手机号和邮箱不可同时存在"}};if(!r)return{code:50202,messageValues:{type:this.t(e?"sms":"email")}};const i=an.command,o=Date.now(),s={mobile:e,email:t,type:n,code:r,state:0,expired_at:i.gt(o)},a=await R.where(s).orderBy("created_at","desc").limit(1).get();if(a&&a.data&&a.data.length>0){const e=a.data[0];return await R.doc(e._id).update({state:1}),{code:0,msg:"验证通过"}}return{code:50202,messageValues:{type:this.t(e?"sms":"email")}}},sendSmsCode:async function({mobile:e,code:t,type:r,templateId:n}){if(!e)return{code:N,messageValues:{param:this.t("mobile")}};if(t||(t=C()),!r)return{code:N,messageValues:{param:this.t("verify-code-type")}};const i=this._getConfig();let o=i&&i.service&&i.service.sms;if(!o)throw new Error(this.t("config-param-required",{param:"service.sms"}));o=Object.assign({codeExpiresIn:300},o);const s=["smsKey","smsSecret"];for(let e=0,t=s.length;e=0?o:{code:0,msg:""}}catch(e){return console.error(e),{code:50301}}}});let un;try{un=require("uni-config-center")}catch(e){throw new Error("Plugin[uni-config-center] was not found")}class dn{constructor({context:e,clientInfo:t,config:r}={}){const n=un({pluginId:"uni-id"});this.pluginConfig=n,this.config=r||this._getConfigContent(),this._configCache={},Object.defineProperty(this,"context",{get(){let r;r=t?{OS:t.os,CLIENTIP:t.clientIP,CLIENTUA:t.userAgent,PLATFORM:t.platform,APPID:t.appId,LOCALE:t.locale,DEVICEID:t.deviceId}:Object.assign({},e||global.__ctx__||{});const n=["CLIENTIP","PLATFORM","APPID","LOCALE"];for(let e=0;ee.dcloudAppid===t)||e.find(e=>e.isDefaultConfig):e}_parseConfigContent(e){return Array.isArray(e)?e:e[0]?Object.values(e):e}_getConfigContent(){if(this.pluginConfig&&this.pluginConfig.hasFile("config.json")){let e;try{e=this.pluginConfig.config()}catch(e){throw new Error("Invalid uni-id config file\n"+e.message)}return this._parseConfigContent(e)}{let e;try{e=require("./config.json")}catch(e){if("MODULE_NOT_FOUND"===e.code||"ENOENT"===e.code)throw new Error("uni-id config file[uniCloud/cloudfunctions/common/uni-config-center/uni-id/config.json] not found");throw e}return this._parseConfigContent(e)}}init(){throw new Error("uniID.init has been deprecated, use uniID.createInstance instead")}setInterceptor(e,t){this.interceptorMap.set(e,t)}_getConfig({appid:e,platform:t}={}){const r=`${e=e||this.context.APPID}_${t=t||this.context.PLATFORM}`;if(this._configCache[r])return this._configCache[r];if(!(this.config&&0!==Object.keys(this.config).length))throw new Error(this.t("config-file-not-found"));const n=this._getAppConfig(this.config,e);"app"!==t&&"app-plus"!==t||(t=n.preferedAppPlatform||t),"web"!==t&&"h5"!==t||(t=n.preferedWebPlatform||t);const i=Object.assign(n,n[t])||{},o=Object.assign({bindTokenToDevice:!1,tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600,usernameToLowerCase:!0,emailToLowerCase:!0},i);return["passwordSecret","tokenSecret","tokenExpiresIn","passwordErrorLimit","passwordErrorRetryTime"].forEach(e=>{if(!o||!o[e])throw new Error(this.t("config-param-required",{param:e}))}),this._configCache[r]=o,o}}for(const e in cn)dn.prototype[e]=cn[e];function pn(e){const t=new dn(e);return new Proxy(t,{get(e,t){if(t in e&&0!==t.indexOf("_")){if("function"==typeof e[t])return(r=e[t],function(){const e=r.apply(this,arguments);return f(e)?e.then(e=>(x.bind(this)(e),e)):(x.bind(this)(e),e)}).bind(e);if("context"!==t&&"config"!==t)return e[t]}var r}})}dn.prototype.createInstance=pn;var ln=pn();module.exports=ln; diff --git a/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/package.json b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/package.json new file mode 100644 index 0000000..93b2b8f --- /dev/null +++ b/uni_modules/uni-id/uniCloud/cloudfunctions/common/uni-id/package.json @@ -0,0 +1,16 @@ +{ + "name": "uni-id", + "version": "3.3.28", + "description": "uni-id for uniCloud", + "main": "index.js", + "homepage": "https://uniapp.dcloud.io/uniCloud/uni-id", + "repository": { + "type": "git", + "url": "git+https://gitee.com/dcloud/uni-id.git" + }, + "author": "", + "license": "Apache-2.0", + "dependencies": { + "uni-config-center": "file:../../../../../uni-config-center/uniCloud/cloudfunctions/common/uni-config-center" + } +} \ No newline at end of file diff --git a/uni_modules/uni-load-more/changelog.md b/uni_modules/uni-load-more/changelog.md new file mode 100644 index 0000000..8f03f1d --- /dev/null +++ b/uni_modules/uni-load-more/changelog.md @@ -0,0 +1,19 @@ +## 1.3.3(2022-01-20) +- 新增 showText属性 ,是否显示文本 +## 1.3.2(2022-01-19) +- 修复 nvue 平台下不显示文本的bug +## 1.3.1(2022-01-19) +- 修复 微信小程序平台样式选择器报警告的问题 +## 1.3.0(2021-11-19) +- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource) +- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-load-more](https://uniapp.dcloud.io/component/uniui/uni-load-more) +## 1.2.1(2021-08-24) +- 新增 支持国际化 +## 1.2.0(2021-07-30) +- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834) +## 1.1.8(2021-05-12) +- 新增 组件示例地址 +## 1.1.7(2021-03-30) +- 修复 uni-load-more 在首页使用时,h5 平台报 'uni is not defined' 的 bug +## 1.1.6(2021-02-05) +- 调整为uni_modules目录规范 diff --git a/uni_modules/uni-load-more/components/uni-load-more/i18n/en.json b/uni_modules/uni-load-more/components/uni-load-more/i18n/en.json new file mode 100644 index 0000000..6f45b0e --- /dev/null +++ b/uni_modules/uni-load-more/components/uni-load-more/i18n/en.json @@ -0,0 +1,5 @@ +{ + "uni-load-more.contentdown": "Pull up to show more", + "uni-load-more.contentrefresh": "loading...", + "uni-load-more.contentnomore": "No more data" +} diff --git a/uni_modules/uni-load-more/components/uni-load-more/i18n/index.js b/uni_modules/uni-load-more/components/uni-load-more/i18n/index.js new file mode 100644 index 0000000..fa8f0f3 --- /dev/null +++ b/uni_modules/uni-load-more/components/uni-load-more/i18n/index.js @@ -0,0 +1,8 @@ +import en from './en.json' +import zhHans from './zh-Hans.json' +import zhHant from './zh-Hant.json' +export default { + en, + 'zh-Hans': zhHans, + 'zh-Hant': zhHant +} diff --git a/uni_modules/uni-load-more/components/uni-load-more/i18n/zh-Hans.json b/uni_modules/uni-load-more/components/uni-load-more/i18n/zh-Hans.json new file mode 100644 index 0000000..3a14ca0 --- /dev/null +++ b/uni_modules/uni-load-more/components/uni-load-more/i18n/zh-Hans.json @@ -0,0 +1,5 @@ +{ + "uni-load-more.contentdown": "上拉显示更多", + "uni-load-more.contentrefresh": "正在加载...", + "uni-load-more.contentnomore": "没有更多数据了" +} diff --git a/uni_modules/uni-load-more/components/uni-load-more/i18n/zh-Hant.json b/uni_modules/uni-load-more/components/uni-load-more/i18n/zh-Hant.json new file mode 100644 index 0000000..ee99b06 --- /dev/null +++ b/uni_modules/uni-load-more/components/uni-load-more/i18n/zh-Hant.json @@ -0,0 +1,5 @@ +{ + "uni-load-more.contentdown": "上拉顯示更多", + "uni-load-more.contentrefresh": "正在加載...", + "uni-load-more.contentnomore": "沒有更多數據了" +} diff --git a/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue b/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue new file mode 100644 index 0000000..ededbc2 --- /dev/null +++ b/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue @@ -0,0 +1,399 @@ + + + + + diff --git a/uni_modules/uni-load-more/package.json b/uni_modules/uni-load-more/package.json new file mode 100644 index 0000000..2fa6f04 --- /dev/null +++ b/uni_modules/uni-load-more/package.json @@ -0,0 +1,86 @@ +{ + "id": "uni-load-more", + "displayName": "uni-load-more 加载更多", + "version": "1.3.3", + "description": "LoadMore 组件,常用在列表里面,做滚动加载使用。", + "keywords": [ + "uni-ui", + "uniui", + "加载更多", + "load-more" +], + "repository": "https://github.com/dcloudio/uni-ui", + "engines": { + "HBuilderX": "" + }, + "directories": { + "example": "../../temps/example_temps" + }, + "dcloudext": { + "category": [ + "前端组件", + "通用组件" + ], + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "无", + "permissions": "无" + }, + "npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui" + }, + "uni_modules": { + "dependencies": ["uni-scss"], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y" + }, + "client": { + "App": { + "app-vue": "y", + "app-nvue": "y" + }, + "H5-mobile": { + "Safari": "y", + "Android Browser": "y", + "微信浏览器(Android)": "y", + "QQ浏览器(Android)": "y" + }, + "H5-pc": { + "Chrome": "y", + "IE": "y", + "Edge": "y", + "Firefox": "y", + "Safari": "y" + }, + "小程序": { + "微信": "y", + "阿里": "y", + "百度": "y", + "字节跳动": "y", + "QQ": "y" + }, + "快应用": { + "华为": "u", + "联盟": "u" + }, + "Vue": { + "vue2": "y", + "vue3": "y" + } + } + } + } +} \ No newline at end of file diff --git a/uni_modules/uni-load-more/readme.md b/uni_modules/uni-load-more/readme.md new file mode 100644 index 0000000..54dc1fa --- /dev/null +++ b/uni_modules/uni-load-more/readme.md @@ -0,0 +1,14 @@ + + +### LoadMore 加载更多 +> **组件名:uni-load-more** +> 代码块: `uLoadMore` + + +用于列表中,做滚动加载使用,展示 loading 的各种状态。 + + +### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-load-more) +#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839 + + diff --git a/uni_modules/uni-scss/changelog.md b/uni_modules/uni-scss/changelog.md new file mode 100644 index 0000000..b863bb0 --- /dev/null +++ b/uni_modules/uni-scss/changelog.md @@ -0,0 +1,8 @@ +## 1.0.3(2022-01-21) +- 优化 组件示例 +## 1.0.2(2021-11-22) +- 修复 / 符号在 vue 不同版本兼容问题引起的报错问题 +## 1.0.1(2021-11-22) +- 修复 vue3中scss语法兼容问题 +## 1.0.0(2021-11-18) +- init diff --git a/uni_modules/uni-scss/index.scss b/uni_modules/uni-scss/index.scss new file mode 100644 index 0000000..1744a5f --- /dev/null +++ b/uni_modules/uni-scss/index.scss @@ -0,0 +1 @@ +@import './styles/index.scss'; diff --git a/uni_modules/uni-scss/package.json b/uni_modules/uni-scss/package.json new file mode 100644 index 0000000..7cc0ccb --- /dev/null +++ b/uni_modules/uni-scss/package.json @@ -0,0 +1,82 @@ +{ + "id": "uni-scss", + "displayName": "uni-scss 辅助样式", + "version": "1.0.3", + "description": "uni-sass是uni-ui提供的一套全局样式 ,通过一些简单的类名和sass变量,实现简单的页面布局操作,比如颜色、边距、圆角等。", + "keywords": [ + "uni-scss", + "uni-ui", + "辅助样式" +], + "repository": "https://github.com/dcloudio/uni-ui", + "engines": { + "HBuilderX": "^3.1.0" + }, + "dcloudext": { + "category": [ + "JS SDK", + "通用 SDK" + ], + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "无", + "permissions": "无" + }, + "npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui" + }, + "uni_modules": { + "dependencies": [], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y" + }, + "client": { + "App": { + "app-vue": "y", + "app-nvue": "u" + }, + "H5-mobile": { + "Safari": "y", + "Android Browser": "y", + "微信浏览器(Android)": "y", + "QQ浏览器(Android)": "y" + }, + "H5-pc": { + "Chrome": "y", + "IE": "y", + "Edge": "y", + "Firefox": "y", + "Safari": "y" + }, + "小程序": { + "微信": "y", + "阿里": "y", + "百度": "y", + "字节跳动": "y", + "QQ": "y" + }, + "快应用": { + "华为": "n", + "联盟": "n" + }, + "Vue": { + "vue2": "y", + "vue3": "y" + } + } + } + } +} diff --git a/uni_modules/uni-scss/readme.md b/uni_modules/uni-scss/readme.md new file mode 100644 index 0000000..b7d1c25 --- /dev/null +++ b/uni_modules/uni-scss/readme.md @@ -0,0 +1,4 @@ +`uni-sass` 是 `uni-ui`提供的一套全局样式 ,通过一些简单的类名和`sass`变量,实现简单的页面布局操作,比如颜色、边距、圆角等。 + +### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-sass) +#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839 \ No newline at end of file diff --git a/uni_modules/uni-scss/styles/index.scss b/uni_modules/uni-scss/styles/index.scss new file mode 100644 index 0000000..ffac4fe --- /dev/null +++ b/uni_modules/uni-scss/styles/index.scss @@ -0,0 +1,7 @@ +@import './setting/_variables.scss'; +@import './setting/_border.scss'; +@import './setting/_color.scss'; +@import './setting/_space.scss'; +@import './setting/_radius.scss'; +@import './setting/_text.scss'; +@import './setting/_styles.scss'; diff --git a/uni_modules/uni-scss/styles/setting/_border.scss b/uni_modules/uni-scss/styles/setting/_border.scss new file mode 100644 index 0000000..12a11c3 --- /dev/null +++ b/uni_modules/uni-scss/styles/setting/_border.scss @@ -0,0 +1,3 @@ +.uni-border { + border: 1px $uni-border-1 solid; +} \ No newline at end of file diff --git a/uni_modules/uni-scss/styles/setting/_color.scss b/uni_modules/uni-scss/styles/setting/_color.scss new file mode 100644 index 0000000..1ededd9 --- /dev/null +++ b/uni_modules/uni-scss/styles/setting/_color.scss @@ -0,0 +1,66 @@ + +// TODO 暂时不需要 class ,需要用户使用变量实现 ,如果使用类名其实并不推荐 +// @mixin get-styles($k,$c) { +// @if $k == size or $k == weight{ +// font-#{$k}:#{$c} +// }@else{ +// #{$k}:#{$c} +// } +// } +$uni-ui-color:( + // 主色 + primary: $uni-primary, + primary-disable: $uni-primary-disable, + primary-light: $uni-primary-light, + // 辅助色 + success: $uni-success, + success-disable: $uni-success-disable, + success-light: $uni-success-light, + warning: $uni-warning, + warning-disable: $uni-warning-disable, + warning-light: $uni-warning-light, + error: $uni-error, + error-disable: $uni-error-disable, + error-light: $uni-error-light, + info: $uni-info, + info-disable: $uni-info-disable, + info-light: $uni-info-light, + // 中性色 + main-color: $uni-main-color, + base-color: $uni-base-color, + secondary-color: $uni-secondary-color, + extra-color: $uni-extra-color, + // 背景色 + bg-color: $uni-bg-color, + // 边框颜色 + border-1: $uni-border-1, + border-2: $uni-border-2, + border-3: $uni-border-3, + border-4: $uni-border-4, + // 黑色 + black:$uni-black, + // 白色 + white:$uni-white, + // 透明 + transparent:$uni-transparent +) !default; +@each $key, $child in $uni-ui-color { + .uni-#{"" + $key} { + color: $child; + } + .uni-#{"" + $key}-bg { + background-color: $child; + } +} +.uni-shadow-sm { + box-shadow: $uni-shadow-sm; +} +.uni-shadow-base { + box-shadow: $uni-shadow-base; +} +.uni-shadow-lg { + box-shadow: $uni-shadow-lg; +} +.uni-mask { + background-color:$uni-mask; +} diff --git a/uni_modules/uni-scss/styles/setting/_radius.scss b/uni_modules/uni-scss/styles/setting/_radius.scss new file mode 100644 index 0000000..9a0428b --- /dev/null +++ b/uni_modules/uni-scss/styles/setting/_radius.scss @@ -0,0 +1,55 @@ +@mixin radius($r,$d:null ,$important: false){ + $radius-value:map-get($uni-radius, $r) if($important, !important, null); + // Key exists within the $uni-radius variable + @if (map-has-key($uni-radius, $r) and $d){ + @if $d == t { + border-top-left-radius:$radius-value; + border-top-right-radius:$radius-value; + }@else if $d == r { + border-top-right-radius:$radius-value; + border-bottom-right-radius:$radius-value; + }@else if $d == b { + border-bottom-left-radius:$radius-value; + border-bottom-right-radius:$radius-value; + }@else if $d == l { + border-top-left-radius:$radius-value; + border-bottom-left-radius:$radius-value; + }@else if $d == tl { + border-top-left-radius:$radius-value; + }@else if $d == tr { + border-top-right-radius:$radius-value; + }@else if $d == br { + border-bottom-right-radius:$radius-value; + }@else if $d == bl { + border-bottom-left-radius:$radius-value; + } + }@else{ + border-radius:$radius-value; + } +} + +@each $key, $child in $uni-radius { + @if($key){ + .uni-radius-#{"" + $key} { + @include radius($key) + } + }@else{ + .uni-radius { + @include radius($key) + } + } +} + +@each $direction in t, r, b, l,tl, tr, br, bl { + @each $key, $child in $uni-radius { + @if($key){ + .uni-radius-#{"" + $direction}-#{"" + $key} { + @include radius($key,$direction,false) + } + }@else{ + .uni-radius-#{$direction} { + @include radius($key,$direction,false) + } + } + } +} diff --git a/uni_modules/uni-scss/styles/setting/_space.scss b/uni_modules/uni-scss/styles/setting/_space.scss new file mode 100644 index 0000000..3c89528 --- /dev/null +++ b/uni_modules/uni-scss/styles/setting/_space.scss @@ -0,0 +1,56 @@ + +@mixin fn($space,$direction,$size,$n) { + @if $n { + #{$space}-#{$direction}: #{$size*$uni-space-root}px + } @else { + #{$space}-#{$direction}: #{-$size*$uni-space-root}px + } +} +@mixin get-styles($direction,$i,$space,$n){ + @if $direction == t { + @include fn($space, top,$i,$n); + } + @if $direction == r { + @include fn($space, right,$i,$n); + } + @if $direction == b { + @include fn($space, bottom,$i,$n); + } + @if $direction == l { + @include fn($space, left,$i,$n); + } + @if $direction == x { + @include fn($space, left,$i,$n); + @include fn($space, right,$i,$n); + } + @if $direction == y { + @include fn($space, top,$i,$n); + @include fn($space, bottom,$i,$n); + } + @if $direction == a { + @if $n { + #{$space}:#{$i*$uni-space-root}px; + } @else { + #{$space}:#{-$i*$uni-space-root}px; + } + } +} + +@each $orientation in m,p { + $space: margin; + @if $orientation == m { + $space: margin; + } @else { + $space: padding; + } + @for $i from 0 through 16 { + @each $direction in t, r, b, l, x, y, a { + .uni-#{$orientation}#{$direction}-#{$i} { + @include get-styles($direction,$i,$space,true); + } + .uni-#{$orientation}#{$direction}-n#{$i} { + @include get-styles($direction,$i,$space,false); + } + } + } +} \ No newline at end of file diff --git a/uni_modules/uni-scss/styles/setting/_styles.scss b/uni_modules/uni-scss/styles/setting/_styles.scss new file mode 100644 index 0000000..689afec --- /dev/null +++ b/uni_modules/uni-scss/styles/setting/_styles.scss @@ -0,0 +1,167 @@ +/* #ifndef APP-NVUE */ + +$-color-white:#fff; +$-color-black:#000; +@mixin base-style($color) { + color: #fff; + background-color: $color; + border-color: mix($-color-black, $color, 8%); + &:not([hover-class]):active { + background: mix($-color-black, $color, 10%); + border-color: mix($-color-black, $color, 20%); + color: $-color-white; + outline: none; + } +} +@mixin is-color($color) { + @include base-style($color); + &[loading] { + @include base-style($color); + &::before { + margin-right:5px; + } + } + &[disabled] { + &, + &[loading], + &:not([hover-class]):active { + color: $-color-white; + border-color: mix(darken($color,10%), $-color-white); + background-color: mix($color, $-color-white); + } + } + +} +@mixin base-plain-style($color) { + color:$color; + background-color: mix($-color-white, $color, 90%); + border-color: mix($-color-white, $color, 70%); + &:not([hover-class]):active { + background: mix($-color-white, $color, 80%); + color: $color; + outline: none; + border-color: mix($-color-white, $color, 50%); + } +} +@mixin is-plain($color){ + &[plain] { + @include base-plain-style($color); + &[loading] { + @include base-plain-style($color); + &::before { + margin-right:5px; + } + } + &[disabled] { + &, + &:active { + color: mix($-color-white, $color, 40%); + background-color: mix($-color-white, $color, 90%); + border-color: mix($-color-white, $color, 80%); + } + } + } +} + + +.uni-btn { + margin: 5px; + color: #393939; + border:1px solid #ccc; + font-size: 16px; + font-weight: 200; + background-color: #F9F9F9; + // TODO 暂时处理边框隐藏一边的问题 + overflow: visible; + &::after{ + border: none; + } + + &:not([type]),&[type=default] { + color: #999; + &[loading] { + background: none; + &::before { + margin-right:5px; + } + } + + + + &[disabled]{ + color: mix($-color-white, #999, 60%); + &, + &[loading], + &:active { + color: mix($-color-white, #999, 60%); + background-color: mix($-color-white,$-color-black , 98%); + border-color: mix($-color-white, #999, 85%); + } + } + + &[plain] { + color: #999; + background: none; + border-color: $uni-border-1; + &:not([hover-class]):active { + background: none; + color: mix($-color-white, $-color-black, 80%); + border-color: mix($-color-white, $-color-black, 90%); + outline: none; + } + &[disabled]{ + &, + &[loading], + &:active { + background: none; + color: mix($-color-white, #999, 60%); + border-color: mix($-color-white, #999, 85%); + } + } + } + } + + &:not([hover-class]):active { + color: mix($-color-white, $-color-black, 50%); + } + + &[size=mini] { + font-size: 16px; + font-weight: 200; + border-radius: 8px; + } + + + + &.uni-btn-small { + font-size: 14px; + } + &.uni-btn-mini { + font-size: 12px; + } + + &.uni-btn-radius { + border-radius: 999px; + } + &[type=primary] { + @include is-color($uni-primary); + @include is-plain($uni-primary) + } + &[type=success] { + @include is-color($uni-success); + @include is-plain($uni-success) + } + &[type=error] { + @include is-color($uni-error); + @include is-plain($uni-error) + } + &[type=warning] { + @include is-color($uni-warning); + @include is-plain($uni-warning) + } + &[type=info] { + @include is-color($uni-info); + @include is-plain($uni-info) + } +} +/* #endif */ diff --git a/uni_modules/uni-scss/styles/setting/_text.scss b/uni_modules/uni-scss/styles/setting/_text.scss new file mode 100644 index 0000000..a34d08f --- /dev/null +++ b/uni_modules/uni-scss/styles/setting/_text.scss @@ -0,0 +1,24 @@ +@mixin get-styles($k,$c) { + @if $k == size or $k == weight{ + font-#{$k}:#{$c} + }@else{ + #{$k}:#{$c} + } +} + +@each $key, $child in $uni-headings { + /* #ifndef APP-NVUE */ + .uni-#{$key} { + @each $k, $c in $child { + @include get-styles($k,$c) + } + } + /* #endif */ + /* #ifdef APP-NVUE */ + .container .uni-#{$key} { + @each $k, $c in $child { + @include get-styles($k,$c) + } + } + /* #endif */ +} diff --git a/uni_modules/uni-scss/styles/setting/_variables.scss b/uni_modules/uni-scss/styles/setting/_variables.scss new file mode 100644 index 0000000..557d3d7 --- /dev/null +++ b/uni_modules/uni-scss/styles/setting/_variables.scss @@ -0,0 +1,146 @@ +// @use "sass:math"; +@import '../tools/functions.scss'; +// 间距基础倍数 +$uni-space-root: 2 !default; +// 边框半径默认值 +$uni-radius-root:5px !default; +$uni-radius: () !default; +// 边框半径断点 +$uni-radius: map-deep-merge( + ( + 0: 0, + // TODO 当前版本暂时不支持 sm 属性 + // 'sm': math.div($uni-radius-root, 2), + null: $uni-radius-root, + 'lg': $uni-radius-root * 2, + 'xl': $uni-radius-root * 6, + 'pill': 9999px, + 'circle': 50% + ), + $uni-radius +); +// 字体家族 +$body-font-family: 'Roboto', sans-serif !default; +// 文本 +$heading-font-family: $body-font-family !default; +$uni-headings: () !default; +$letterSpacing: -0.01562em; +$uni-headings: map-deep-merge( + ( + 'h1': ( + size: 32px, + weight: 300, + line-height: 50px, + // letter-spacing:-0.01562em + ), + 'h2': ( + size: 28px, + weight: 300, + line-height: 40px, + // letter-spacing: -0.00833em + ), + 'h3': ( + size: 24px, + weight: 400, + line-height: 32px, + // letter-spacing: normal + ), + 'h4': ( + size: 20px, + weight: 400, + line-height: 30px, + // letter-spacing: 0.00735em + ), + 'h5': ( + size: 16px, + weight: 400, + line-height: 24px, + // letter-spacing: normal + ), + 'h6': ( + size: 14px, + weight: 500, + line-height: 18px, + // letter-spacing: 0.0125em + ), + 'subtitle': ( + size: 12px, + weight: 400, + line-height: 20px, + // letter-spacing: 0.00937em + ), + 'body': ( + font-size: 14px, + font-weight: 400, + line-height: 22px, + // letter-spacing: 0.03125em + ), + 'caption': ( + 'size': 12px, + 'weight': 400, + 'line-height': 20px, + // 'letter-spacing': 0.03333em, + // 'text-transform': false + ) + ), + $uni-headings +); + + + +// 主色 +$uni-primary: #2979ff !default; +$uni-primary-disable:lighten($uni-primary,20%) !default; +$uni-primary-light: lighten($uni-primary,25%) !default; + +// 辅助色 +// 除了主色外的场景色,需要在不同的场景中使用(例如危险色表示危险的操作)。 +$uni-success: #18bc37 !default; +$uni-success-disable:lighten($uni-success,20%) !default; +$uni-success-light: lighten($uni-success,25%) !default; + +$uni-warning: #f3a73f !default; +$uni-warning-disable:lighten($uni-warning,20%) !default; +$uni-warning-light: lighten($uni-warning,25%) !default; + +$uni-error: #e43d33 !default; +$uni-error-disable:lighten($uni-error,20%) !default; +$uni-error-light: lighten($uni-error,25%) !default; + +$uni-info: #8f939c !default; +$uni-info-disable:lighten($uni-info,20%) !default; +$uni-info-light: lighten($uni-info,25%) !default; + +// 中性色 +// 中性色用于文本、背景和边框颜色。通过运用不同的中性色,来表现层次结构。 +$uni-main-color: #3a3a3a !default; // 主要文字 +$uni-base-color: #6a6a6a !default; // 常规文字 +$uni-secondary-color: #909399 !default; // 次要文字 +$uni-extra-color: #c7c7c7 !default; // 辅助说明 + +// 边框颜色 +$uni-border-1: #F0F0F0 !default; +$uni-border-2: #EDEDED !default; +$uni-border-3: #DCDCDC !default; +$uni-border-4: #B9B9B9 !default; + +// 常规色 +$uni-black: #000000 !default; +$uni-white: #ffffff !default; +$uni-transparent: rgba($color: #000000, $alpha: 0) !default; + +// 背景色 +$uni-bg-color: #f7f7f7 !default; + +/* 水平间距 */ +$uni-spacing-sm: 8px !default; +$uni-spacing-base: 15px !default; +$uni-spacing-lg: 30px !default; + +// 阴影 +$uni-shadow-sm:0 0 5px rgba($color: #d8d8d8, $alpha: 0.5) !default; +$uni-shadow-base:0 1px 8px 1px rgba($color: #a5a5a5, $alpha: 0.2) !default; +$uni-shadow-lg:0px 1px 10px 2px rgba($color: #a5a4a4, $alpha: 0.5) !default; + +// 蒙版 +$uni-mask: rgba($color: #000000, $alpha: 0.4) !default; diff --git a/uni_modules/uni-scss/styles/tools/functions.scss b/uni_modules/uni-scss/styles/tools/functions.scss new file mode 100644 index 0000000..ac6f63e --- /dev/null +++ b/uni_modules/uni-scss/styles/tools/functions.scss @@ -0,0 +1,19 @@ +// 合并 map +@function map-deep-merge($parent-map, $child-map){ + $result: $parent-map; + @each $key, $child in $child-map { + $parent-has-key: map-has-key($result, $key); + $parent-value: map-get($result, $key); + $parent-type: type-of($parent-value); + $child-type: type-of($child); + $parent-is-map: $parent-type == map; + $child-is-map: $child-type == map; + + @if (not $parent-has-key) or ($parent-type != $child-type) or (not ($parent-is-map and $child-is-map)){ + $result: map-merge($result, ( $key: $child )); + }@else { + $result: map-merge($result, ( $key: map-deep-merge($parent-value, $child) )); + } + } + @return $result; +}; diff --git a/uni_modules/uni-scss/theme.scss b/uni_modules/uni-scss/theme.scss new file mode 100644 index 0000000..80ee62f --- /dev/null +++ b/uni_modules/uni-scss/theme.scss @@ -0,0 +1,31 @@ +// 间距基础倍数 +$uni-space-root: 2; +// 边框半径默认值 +$uni-radius-root:5px; +// 主色 +$uni-primary: #2979ff; +// 辅助色 +$uni-success: #4cd964; +// 警告色 +$uni-warning: #f0ad4e; +// 错误色 +$uni-error: #dd524d; +// 描述色 +$uni-info: #909399; +// 中性色 +$uni-main-color: #303133; +$uni-base-color: #606266; +$uni-secondary-color: #909399; +$uni-extra-color: #C0C4CC; +// 背景色 +$uni-bg-color: #f5f5f5; +// 边框颜色 +$uni-border-1: #DCDFE6; +$uni-border-2: #E4E7ED; +$uni-border-3: #EBEEF5; +$uni-border-4: #F2F6FC; + +// 常规色 +$uni-black: #000000; +$uni-white: #ffffff; +$uni-transparent: rgba($color: #000000, $alpha: 0); diff --git a/uni_modules/uni-scss/variables.scss b/uni_modules/uni-scss/variables.scss new file mode 100644 index 0000000..1c062d4 --- /dev/null +++ b/uni_modules/uni-scss/variables.scss @@ -0,0 +1,62 @@ +@import './styles/setting/_variables.scss'; +// 间距基础倍数 +$uni-space-root: 2; +// 边框半径默认值 +$uni-radius-root:5px; + +// 主色 +$uni-primary: #2979ff; +$uni-primary-disable:mix(#fff,$uni-primary,50%); +$uni-primary-light: mix(#fff,$uni-primary,80%); + +// 辅助色 +// 除了主色外的场景色,需要在不同的场景中使用(例如危险色表示危险的操作)。 +$uni-success: #18bc37; +$uni-success-disable:mix(#fff,$uni-success,50%); +$uni-success-light: mix(#fff,$uni-success,80%); + +$uni-warning: #f3a73f; +$uni-warning-disable:mix(#fff,$uni-warning,50%); +$uni-warning-light: mix(#fff,$uni-warning,80%); + +$uni-error: #e43d33; +$uni-error-disable:mix(#fff,$uni-error,50%); +$uni-error-light: mix(#fff,$uni-error,80%); + +$uni-info: #8f939c; +$uni-info-disable:mix(#fff,$uni-info,50%); +$uni-info-light: mix(#fff,$uni-info,80%); + +// 中性色 +// 中性色用于文本、背景和边框颜色。通过运用不同的中性色,来表现层次结构。 +$uni-main-color: #3a3a3a; // 主要文字 +$uni-base-color: #6a6a6a; // 常规文字 +$uni-secondary-color: #909399; // 次要文字 +$uni-extra-color: #c7c7c7; // 辅助说明 + +// 边框颜色 +$uni-border-1: #F0F0F0; +$uni-border-2: #EDEDED; +$uni-border-3: #DCDCDC; +$uni-border-4: #B9B9B9; + +// 常规色 +$uni-black: #000000; +$uni-white: #ffffff; +$uni-transparent: rgba($color: #000000, $alpha: 0); + +// 背景色 +$uni-bg-color: #f7f7f7; + +/* 水平间距 */ +$uni-spacing-sm: 8px; +$uni-spacing-base: 15px; +$uni-spacing-lg: 30px; + +// 阴影 +$uni-shadow-sm:0 0 5px rgba($color: #d8d8d8, $alpha: 0.5); +$uni-shadow-base:0 1px 8px 1px rgba($color: #a5a5a5, $alpha: 0.2); +$uni-shadow-lg:0px 1px 10px 2px rgba($color: #a5a4a4, $alpha: 0.5); + +// 蒙版 +$uni-mask: rgba($color: #000000, $alpha: 0.4); diff --git a/uni_modules/uni-upgrade-center-app/changelog.md b/uni_modules/uni-upgrade-center-app/changelog.md new file mode 100644 index 0000000..6804a9a --- /dev/null +++ b/uni_modules/uni-upgrade-center-app/changelog.md @@ -0,0 +1,64 @@ +## 0.6.1(2022-08-17) +- 修复 后台添加应用市场,但都没有启用的情况下报错的Bug (需要 uni-admin 1.9.3+) +## 0.6.0(2022-07-19) +- 新增 支持多应用商店配置(需要 uni-admin 1.9.3+) +## 0.4.1(2022-05-27) +- 修复 上版引出的报错问题 +## 0.4.0(2022-05-27) +- 新增 Android 支持跳转手机自带商店,填写升级包地址时请填写跳转商店链接 +- 新增 改为云对象调用方式,使用更直观 +## 0.3.3(2022-04-14) +- 修复 调用 check-update,当 code 为 0 时没有回调 +## 0.3.2(2022-01-12) +- 优化显示逻辑 +## 0.3.1(2021-11-24) +- 修复 vue3 上图片不显示的Bug +## 0.3.0(2021-11-18) +- 移除 wgt 安装成功后提示,防止重启过快弹框不消失 +## 0.2.2(2021-08-25) +- 兼容vue3.0 +## 0.2.1(2021-07-26) +- 修复 使用腾讯云并手动填写地址时,导致下载链接失效的bug +## 0.2.0(2021-07-13) +- 更新文档 关于报错local_storage_key 为空,请不要将页面路径设置为pages.json中第一项 +## 0.1.9(2021-06-28) +- 更新文档 +- 修复 wgt安装失败时,按钮状态不对 +## 0.1.8(2021-06-16) +- 修复 跳转安装时,导致上次下载的apk还没安装就被删掉的bug +## 0.1.7(2021-06-03) +- 修改 移除static中的图片 +## 0.1.6(2021-06-03) +- 修改 下载更新按钮使用CSS渐变色 +## 0.1.5(2021-04-22) +- 更新check-update函数。现在返回一个Promise,有更新时成功回调,其他情况错误回调 +## 0.1.4(2021-04-13) +- 更新文档。明确云函数调用结果 +## 0.1.3(2021-04-13) +- 解耦云函数与弹框处理。utils中新增 call-check-version.js,可用于单独检测是否有更新 +## 0.1.2(2021-04-07) +- 更新版本对比函数 compare +## 0.1.1(2021-04-07) +- 修复 腾讯云空间下载链接不能下载问题 +## 0.1.0(2021-04-07) +- 新增使用uni.showModal提示升级示例 +- 修改iOS升级提示方式 +## 0.0.7(2021-04-02) +- 修复在iOS上打开弹框报错 +## 0.0.6(2021-04-01) +- 兼容旧版本安卓 +## 0.0.5(2021-04-01) +- 修复低版本安卓上进度条错位 +## 0.0.4(2021-04-01) +- 更新readme +- 修复check-update语法错误 +## 0.0.3(2021-04-01) +- 新增前台更新弹框,详见readme +- 更新前台检查更新方法 + +## 0.0.2(2021-03-29) +- 更新文档 +- 移除 dependencies + +## 0.0.1(2021-03-25) +- 升级中心前台检查更新 diff --git a/uni_modules/uni-upgrade-center-app/images/app_update_close.png b/uni_modules/uni-upgrade-center-app/images/app_update_close.png new file mode 100644 index 0000000..8b2ffe6 Binary files /dev/null and b/uni_modules/uni-upgrade-center-app/images/app_update_close.png differ diff --git a/uni_modules/uni-upgrade-center-app/images/bg_top.png b/uni_modules/uni-upgrade-center-app/images/bg_top.png new file mode 100644 index 0000000..015f698 Binary files /dev/null and b/uni_modules/uni-upgrade-center-app/images/bg_top.png differ diff --git a/uni_modules/uni-upgrade-center-app/package.json b/uni_modules/uni-upgrade-center-app/package.json new file mode 100644 index 0000000..8ccd619 --- /dev/null +++ b/uni_modules/uni-upgrade-center-app/package.json @@ -0,0 +1,81 @@ +{ + "id": "uni-upgrade-center-app", + "displayName": "升级中心 uni-upgrade-center - App", + "version": "0.6.1", + "description": "uni升级中心 - 客户端检查更新", + "keywords": [ + "uniCloud", + "update", + "升级", + "wgt" +], + "repository": "https://gitee.com/dcloud/uni-upgrade-center/tree/master/uni_modules/uni-upgrade-center-app", + "engines": { + "HBuilderX": "^3.1.0" + }, +"dcloudext": { + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "插件不采集任何数据", + "permissions": "无" + }, + "npmurl": "", + "type": "unicloud-template-page" + }, + "uni_modules": { + "dependencies": [], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y" + }, + "client": { + "App": { + "app-vue": "y", + "app-nvue": "u" + }, + "H5-mobile": { + "Safari": "y", + "Android Browser": "y", + "微信浏览器(Android)": "y", + "QQ浏览器(Android)": "y" + }, + "H5-pc": { + "Chrome": "y", + "IE": "y", + "Edge": "y", + "Firefox": "y", + "Safari": "y" + }, + "小程序": { + "微信": "u", + "阿里": "u", + "百度": "u", + "字节跳动": "u", + "QQ": "u", + "京东": "u" + }, + "快应用": { + "华为": "u", + "联盟": "u" + }, + "Vue": { + "vue2": "y", + "vue3": "y" + } + } + } + } +} diff --git a/uni_modules/uni-upgrade-center-app/pages/upgrade-popup.vue b/uni_modules/uni-upgrade-center-app/pages/upgrade-popup.vue new file mode 100644 index 0000000..cc33c1d --- /dev/null +++ b/uni_modules/uni-upgrade-center-app/pages/upgrade-popup.vue @@ -0,0 +1,539 @@ + + + + + diff --git a/uni_modules/uni-upgrade-center-app/readme.md b/uni_modules/uni-upgrade-center-app/readme.md new file mode 100644 index 0000000..1dad9cd --- /dev/null +++ b/uni_modules/uni-upgrade-center-app/readme.md @@ -0,0 +1,126 @@ +## 升级中心 - app插件与 `uni-admin` 版本关系 + +### `uni-admin >= 1.9.3`:云函数 `checkVersion` 废弃,使用 uni-admin 自带的 `uni-upgrade-center` 云函数。 + +# uni-upgrade-center - App + +### 概述 + +> 统一管理App及App在`Android`、`iOS`平台上`App安装包`和`wgt资源包`的发布升级 + +> uni升级中心分为业务插件和后台管理插件。本插件为业务插件,包括uni升级中心客户端检查更新的前后端逻辑。后台管理系统另见 [uni-upgrade-center - Admin](https://ext.dcloud.net.cn/plugin?id=4470) + +### uni升级中心 - 客户端检查更新插件 + - 一键式检查更新,同时支持整包升级与wgt资源包更新 + - 好看、实用、可自定义的客户端提示框 + +## 安装指引 + +1. 依赖数据库`opendb-app-versions`,如果没有此库,请在云服务空间中创建。 + +2. 使用`HBuilderX 3.1.0+`,因为要使用到`uni_modules` + +3. 在插件市场打开本插件页面,在右侧点击`使用 HBuilderX 导入插件`,选择要导入的项目点击确定 + +4. 绑定一个服务空间。自 `0.6.0` 起,依赖 `uni-admin 1.9.3+` 的 `uni-upgrade-center 云函数`,请和 uni-admin 项目关联同一个服务空间 + +5. 找到`/uni_modules/uni-upgrade-center-app/uniCloud/cloudfunctions/check-version`,右键上传部署。自 `0.6.0` 起,依赖 `uni-admin 1.9.3+` 的 `uni-upgrade-center 云函数`,插件不再单独提供云函数,这样可以省下一个云函数名额。 + +6. 在`pages.json`中添加页面路径。**注:请不要设置为pages.json中第一项** +```json +"pages": [ + // ……其他页面配置 + { + "path": "uni_modules/uni-upgrade-center-app/pages/upgrade-popup", + "style": { + "disableScroll": true, + "app-plus": { + "backgroundColorTop": "transparent", + "background": "transparent", + "titleNView": false, + "scrollIndicator": false, + "popGesture": "none", + "animationType": "fade-in", + "animationDuration": 200 + + } + } + } +] +``` + +7. 将`@/uni_modules/uni-upgrade-center-app/utils/check-update`import到需要用到的地方,调用一下即可 + 1. 默认使用当前绑定的服务空间,如果要请求其他服务空间,可以使用其他服务空间的 `callFunction`。[详情](https://uniapp.dcloud.io/uniCloud/cf-functions.html#call-by-function-cross-space) + +8. 升级弹框可自行编写,也可以使用`uni.showModal`,或使用现有的升级弹框样式,如果不满足UI需求请自行替换资源文件。在`utils/check-update.js`中都有实例。 + +9. wgt更新时,打包前请务必将manifest.json中的版本修改为更高版本。 + +### 更新下载安装`check-update.js` + +*该函数在utils目录下* + +1. 如果是静默更新,则不会打开更新弹框,会在后台下载后安装,下次启动应用生效 + +2. 如果是 iOS,则会直接打开AppStore的链接 + +3. 其他情况,会将`check-version`返回的结果保存在localStorage中,并跳转进入`upgrade-popup.vue`打开更新弹框 + +### 检查更新函数`check-version` + +*该函数在uniCloud/cloudfunctions目录下* + +1. 使用检查更新需要传递三个参数 `appid`、`appVersion`、`wgtVersion` + +2. `appid` 使用 plus.runtime.appid 获取,*注:真机运行时为固定值HBuilder,在调试的时候请使用本地调试云函数* + +3. `appVersion` 使用 plus.runtime.version 获取 + +4. `wgtVersion` 使用 plus.runtime.getProperty(plus.runtime.appid,(wgtInfo) => { wgtInfo.version }) 获取 + +5. `check-version`云函数内部会自动获取 App 平台 + + +**Tips** + +1. `check-version`云函数内部有版本对比函数(compare)。 + - 使用多段式版本格式(如:"3.0.0.0.0.1.0.1", "3.0.0.0.0.1")。如果不满足对比规则,请自行修改。 + - 如果修改,请将*pages/upgrade-popup.vue*中*compare*函数一并修改 + +## 项目代码说明 + +### 更新弹框 +- `upgrade-popup.vue` - 更新应用: + - 如果云函数`check-version`返回的参数表明需要更新,则将参数保存在localStorage中,带着键值跳转该页面 + - 进入时会先从localStorage中尝试取出之前存的安装包路径(此包不会是强制安装类型的包) + - 如果有已经保存的包,则和传进来的 `version` 进行比较,如果相等则安装。大于和小于都不进行安装,因为admin端可能会调整包的版本。不符合更新会将此包删除 + - 如果本地没有包或者包不符合安装条件,则进行下载安装包 + - 点击下载会有进度条、已下载大小和下载包的大小 + - 下载完成会提示安装: + - 如果是 wgt 包,安装时则会提示 正在安装…… 和 安装完成。安装完成会提示是否重启 + - 如果是 原生安装包,则直接跳出去覆盖安装 + - 下载过程中,如果退出会提示是否取消下载。如果是强制更新,则只会提示正在下载请稍后,此时不可退出 + - 如果是下载完成了没有安装就退出,则会将下载完成的包保存在本地。将包的本地路径和包version保存在localStorage中 + +### 工具类 utils +- `call-check-version` + - 请求云函数`check-version`拿取版本检测结果 +- `check-update` + - 调用`call-check-version`并根据结果判断是否显示更新弹框 + +### 云函数 +- `check-version` - 检查应用更新: + - 根据传参,先检测传参是否完整,appid appVersion wgtVersion 必传 + - 先从数据库取出所有该平台(会从上下文读取平台信息)的所有线上发行更新 + - 再从所有线上发行更新中取出版本最大的一版。如果可以,尽量先检测wgt的线上发行版更新 + - 使用上一步取出的版本包的版本号 和传参 appVersion、wgtVersion 来检测是否有更新。必须同时大于这两项,因为上一次可能是wgt热更新,否则返回暂无更新 + - 如果库中 wgt包 版本大于传参 appVersion,但是不满足 min_uni_version < appVersion,则不会使用wgt更新,会接着判断库中 app包version 是否大于 appVersion + - 返回结果: + + |code|message| + |:-:|:-:| + |0|当前版本已经是最新的,不需要更新| + |101|wgt更新| + |102|整包更新| + |-101|暂无更新或检查appid是否填写正确| + |-102|请检查传参是否填写正确| \ No newline at end of file diff --git a/uni_modules/uni-upgrade-center-app/uniCloud/cloudfunctions/temp.png b/uni_modules/uni-upgrade-center-app/uniCloud/cloudfunctions/temp.png new file mode 100644 index 0000000..8b2ffe6 Binary files /dev/null and b/uni_modules/uni-upgrade-center-app/uniCloud/cloudfunctions/temp.png differ diff --git a/uni_modules/uni-upgrade-center-app/utils/call-check-version.js b/uni_modules/uni-upgrade-center-app/utils/call-check-version.js new file mode 100644 index 0000000..1a28bd8 --- /dev/null +++ b/uni_modules/uni-upgrade-center-app/utils/call-check-version.js @@ -0,0 +1,33 @@ +export default function() { + // #ifdef APP-PLUS + return new Promise((resolve, reject) => { + plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) { + const data = { + action: 'checkVersion', + appid: plus.runtime.appid, + appVersion: plus.runtime.version, + wgtVersion: widgetInfo.version + } + console.log("data: ",data); + uniCloud.callFunction({ + name: 'uni-upgrade-center', + data, + success: (e) => { + console.log("e: ", e); + resolve(e) + }, + fail: (error) => { + reject(error) + } + }) + }) + }) + // #endif + // #ifndef APP-PLUS + return new Promise((resolve, reject) => { + reject({ + message: '请在App中使用' + }) + }) + // #endif +} diff --git a/uni_modules/uni-upgrade-center-app/utils/check-update.js b/uni_modules/uni-upgrade-center-app/utils/check-update.js new file mode 100644 index 0000000..f45e5fb --- /dev/null +++ b/uni_modules/uni-upgrade-center-app/utils/check-update.js @@ -0,0 +1,158 @@ +import callCheckVersion from './call-check-version' + +// 推荐再App.vue中使用 +const PACKAGE_INFO_KEY = '__package_info__' + +export default function() { + // #ifdef APP-PLUS + return new Promise((resolve, reject) => { + callCheckVersion().then(async (e) => { + if (!e.result) return; + const { + code, + message, + is_silently, // 是否静默更新 + url, // 安装包下载地址 + platform, // 安装包平台 + type // 安装包类型 + } = e.result; + + // 此处逻辑仅为实例,可自行编写 + if (code > 0) { + // 腾讯云和阿里云下载链接不同,需要处理一下,阿里云会原样返回 + const { + fileList + } = await uniCloud.getTempFileURL({ + fileList: [url] + }); + if (fileList[0].tempFileURL) + e.result.url = fileList[0].tempFileURL; + + resolve(e) + + // 静默更新,只有wgt有 + if (is_silently) { + uni.downloadFile({ + url: e.result.url, + success: res => { + if (res.statusCode == 200) { + // 下载好直接安装,下次启动生效 + plus.runtime.install(res.tempFilePath, { + force: false + }); + } + } + }); + return; + } + + /** + * 提示升级一 + * 使用 uni.showModal + */ + // return updateUseModal(e.result) + + /** + * 提示升级二 + * 官方适配的升级弹窗,可自行替换资源适配UI风格 + */ + uni.setStorageSync(PACKAGE_INFO_KEY, e.result) + uni.navigateTo({ + url: `/uni_modules/uni-upgrade-center-app/pages/upgrade-popup?local_storage_key=${PACKAGE_INFO_KEY}`, + fail: (err) => { + console.error('更新弹框跳转失败', err) + uni.removeStorageSync(PACKAGE_INFO_KEY) + } + }) + + return + } else if (code < 0) { + // TODO 云函数报错处理 + console.error(message) + return reject(e) + } + return resolve(e) + }).catch(err => { + // TODO 云函数报错处理 + console.error(err.message) + reject(err) + }) + }); + // #endif +} + +/** + * 使用 uni.showModal 升级 + */ +function updateUseModal(packageInfo) { + const { + title, // 标题 + contents, // 升级内容 + is_mandatory, // 是否强制更新 + url, // 安装包下载地址 + platform, // 安装包平台 + type // 安装包类型 + } = packageInfo; + + let isWGT = type === 'wgt' + let isiOS = !isWGT ? platform.includes('iOS') : false; + let confirmText = isiOS ? '立即跳转更新' : '立即下载更新' + + return uni.showModal({ + title, + content: contents, + showCancel: !is_mandatory, + confirmText, + success: res => { + if (res.cancel) return; + + // 安装包下载 + if (isiOS) { + plus.runtime.openURL(url); + return; + } + + uni.showToast({ + title: '后台下载中……', + duration: 1000 + }); + + // wgt 和 安卓下载更新 + downloadTask = uni.downloadFile({ + url, + success: res => { + if (res.statusCode !== 200) { + console.error('下载安装包失败', err); + return; + } + // 下载好直接安装,下次启动生效 + plus.runtime.install(res.tempFilePath, { + force: false + }, () => { + if (is_mandatory) { + //更新完重启app + plus.runtime.restart(); + return; + } + uni.showModal({ + title: '安装成功是否重启?', + success: res => { + if (res.confirm) { + //更新完重启app + plus.runtime.restart(); + } + } + }); + }, err => { + uni.showModal({ + title: '更新失败', + content: err + .message, + showCancel: false + }); + }); + } + }); + } + }); +} diff --git a/utils/CLodopfuncs.js b/utils/CLodopfuncs.js new file mode 100644 index 0000000..1cfb5be --- /dev/null +++ b/utils/CLodopfuncs.js @@ -0,0 +1,1894 @@ +/* eslint-disable */ + +// #ifdef APP-PLUS +window = { + location: { + href: 'http://127.0.0.1/print' + } +}; +// #endif +(function(win) { + let printListDev = []; + let printListOnline = []; + var CLODOP = { + strWebPageID:"JL68836", + strTaskID: "", + strHostURI: "http://192.168.81.198:8000", + wsHostURI: "ws://192.168.81.198:8000/c_webskt/", + VERSION:"6.2.2.0", + IVERSION:"6220", + CVERSION:"3.0.2.5", + HTTPS_STATUS:0, + VERSION_EXT:false, + iBaseTask: 0, + timeThreshold: 5, + Priority: 0, + blIslocal:false, + Iframes: [], + ItemDatas: {}, + PageData: {}, + defStyleJson: {}, + PageDataEx: {}, + ItemCNameStyles: {}, + blWorking: false, + blNormalItemAdded: false, + blTmpSelectedIndex: null, + Caption: null, + Color: null, + CompanyName: null, + strBroadcastMS: null, + Border: null, + Inbrowse: null, + webskt: null, + SocketEnable: false, + SocketOpened: false, + NoClearAfterPrint: false, + On_Return_Remain: false, + On_Broadcast_Remain: false, + On_Return: null, + Result: null, + iTrySendTimes: 0, + OBO_Mode: 1, + blOneByone: false, + DelimChar: "\f\f", + Printers: { + "default": "1", + "list":[] + }, + altMessageWebSocketInvalid: "WebSocket没准备好,点确定继续...", + altMessageNoReadWriteFile: "不能远程读写文件!", + altMessageNoReadFile: "不能远程读文件!", + altMessageNoWriteFile: "不能远程写文件!", + altMessageNoPrintDesign: "不能远程打印设计!", + altMessageNoPrintSetup: "不能远程打印维护!", + altMessageSomeWindowExist: "有窗口已打开,先关闭它(持续如此时请刷新页面)!", + altMessageBusy: "上一个请求正忙,请稍后再试!", + Browser: (function() { + // #ifdef APP-PLUS + navigator = { + userAgent: `Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36` + }; + // #endif + var ua = navigator.userAgent; + var isOpera = Object.prototype.toString.call(window.opera) == "[object Opera]"; + return { + IE: !!window.attachEvent && !isOpera, + Opera: isOpera, + WebKit: ua.indexOf("AppleWebKit/") > -1, + Gecko: ua.indexOf("Gecko") > -1 && ua.indexOf("KHTML") === -1, + MobileSafari: /Apple.*Mobile/.test(ua) + } + })(), + GetTaskID: function() { + if (!this.strTaskID || this.strTaskID == "") { + var dt = new Date(); + this.iBaseTask++; + this.strTaskID = "" + dt.getHours() + dt.getMinutes() + dt.getSeconds() + "_" + this.iBaseTask; + } + return this.strWebPageID + this.strTaskID; + }, + DoInit: function() { + if (process.env.NODE_ENV === 'development') { + //开发环境 + CLODOP.Printers.list = printListDev + } else { + //生产环境 + CLODOP.Printers.list = printListOnline + } + this.strTaskID = ""; + if (this.NoClearAfterPrint) return; + this.ItemDatas = { + "count": 0 + }; + this.PageData = {}; + this.ItemCNameStyles = {}; + this.defStyleJson = { + "beginpage": 0, + "beginpagea": 0 + }; + this.blNormalItemAdded = false; + // win.CLODOP.OpenWebSocket(); + }, + OpenWebSocket: function(rest) { + // #ifdef APP-PLUS + if (window.On_CLodop_Opened) { + if (CLODOP.Priority == window.CLODOP_OK_Priority) setTimeout("window.On_CLodop_Opened(CLODOP)", 1); + } + // #endif + if (!window.WebSocket && !window.MozWebSocket) { + if (window.On_CLodop_Opened) { + if (CLODOP.Priority == window.CLODOP_OK_Priority) setTimeout("window.On_CLodop_Opened(CLODOP)", 1); + } + } + console.log(this.webskt) + console.log(CLODOP.wsHostURI) + console.log(rest) + let ip = uni.getStorageSync('fl_ip') || '192.168.81.198'; + let wsHostURI = `ws://${ip}:8000/c_webskt/` + this.SocketEnable = true; + try { + if (!this.webskt || this.webskt.readyState == 3 || rest) { + console.log('链接') + if (!window.WebSocket && window.MozWebSocket) window.WebSocket = window.MozWebSocket; + this.webskt = uni.connectSocket({ + url: wsHostURI, + success: res => { + console.info(res); + console.log('链接成功') + }, + fail: res => { + console.info(res); + console.log('链接失败') + }, + complete: res => { + console.info(res); + console.log('链接完成') + } + }); + console.log(this.webskt) + this.webskt.onOpen(function(e) { + CLODOP.SocketOpened = true; + if (window.On_CLodop_Opened) { + if (CLODOP.Priority == window.CLODOP_OK_Priority) setTimeout(window.On_CLodop_Opened(CLODOP), 10000); + } + }); + this.webskt.onMessage(function(e) { + console.log(e); + CLODOP.resultHandle(e.data); + }); + this.webskt.onClose(function(e) { + if (!CLODOP.SocketOpened) { + CLODOP.SocketEnable = false; + return; + } + // setTimeout(CLODOP.OpenWebSocket(), 2000); + }); + this.webskt.onError(function(e) { + console.info(e); + }); + } + } catch (err) { + this.webskt = null; + if (err.message.indexOf("SecurityError") > -1) + this.SocketEnable = false; + else + setTimeout(()=>{ + CLODOP.OpenWebSocket() + }, 2000); + } + }, + resultHandle: function(data) { + CLODOP.blOneByone = false; + var strResult = data; + CLODOP.Result = strResult; + try { + var strFTaskID = null; + var iPos = strResult.indexOf("="); + if (iPos >= 0 && iPos < 30) { + strFTaskID = strResult.slice(0, iPos); + strResult = strResult.slice(iPos + 1); + } + if (strFTaskID.indexOf("ErrorMS") > -1) { + console.info(strResult); + return; + } + if (strFTaskID.indexOf("BroadcastMS") > -1) { + CLODOP.strBroadcastMS = strResult; + if (CLODOP.On_Broadcast) { + var selfFunc = CLODOP.On_Broadcast; + CLODOP.On_Broadcast(strResult); + if (!CLODOP.On_Broadcast_Remain && selfFunc === CLODOP.On_Broadcast) + CLODOP.On_Broadcast = null; + } + return; + } + if (CLODOP.On_Return) { + var selfFunc = CLODOP.On_Return; + if ((strResult.toLowerCase() == "true") || (strResult.toLowerCase() == "false")) + CLODOP.On_Return(strFTaskID, strResult.toLowerCase() == "true"); + else + CLODOP.On_Return(strFTaskID, strResult); + if (!CLODOP.On_Return_Remain && selfFunc === CLODOP.On_Return) CLODOP.On_Return = null; + } + } catch (err) { + console.log(err); + }; + }, + wsSend: function(strData) { + // console.info(strData); + console.log(this.webskt); + console.log(this.wsHostURI); + console.log(11); + if (this.webskt && this.webskt.readyState == 1) { + this.Result = null; + this.iTrySendTimes = 0; + this.webskt.send({ + data: strData, + success: res => { + console.info(res); + }, + fail: res => { + console.info(res); + } + }); + return true; + } else { + this.iTrySendTimes++; + console.log(this.iTrySendTimes); + if (this.iTrySendTimes <= 1) { + this.OpenWebSocket(); + setTimeout(()=>{ + CLODOP.wsSend(strData) + }, 1000); + } + } + }, + FORMAT: function(oType, oValue) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (oType !== undefined && oValue !== undefined) { + if (oType.replace(/^\s+|\s+$/g, "").toLowerCase().indexOf("time:") == 0) { + oType = oType.replace(/^\s+|\s+$/g, "").slice(5); + if (oValue.toLowerCase().indexOf("now") > -1) oValue = (new Date()).toString(); + if (oValue.toLowerCase().indexOf("date") > -1) oValue = (new Date()).toString(); + if (oValue.toLowerCase().indexOf("time") > -1) oValue = (new Date()).toString(); + var TypeYMD = "ymd"; + if (oValue.toLowerCase().indexOf("ymd") > -1) { + TypeYMD = "ymd"; + oValue = oValue.slice(3); + } + if (oValue.toLowerCase().indexOf("dmy") > -1) { + TypeYMD = "dmy"; + oValue = oValue.slice(3); + } + if (oValue.toLowerCase().indexOf("mdy") > -1) { + TypeYMD = "mdy"; + oValue = oValue.slice(3); + } + oValue = oValue.replace(/ [^ ]*\+[^ ]* /g, " "); + oValue = oValue.replace(/\(.*\)/g, " "); + oValue = oValue.replace(/星期日|星期一|星期二|星期三|星期四|星期五|星期六/g, " "); + oValue = oValue.replace(/[A-Za-z]+day|Mon|Tue|Wed|Thu|Fri|Sat|Sun/g, " "); + var aMonth = 0; + var exp = new RegExp("Oct[A-Za-z]*|十月|10月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 10; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Nov[A-Za-z]*|十一月|11月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 11; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Dec[A-Za-z]*|十二月|12月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 12; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Jan[A-Za-z]*|一月|01月|1月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 1; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Feb[A-Za-z]*|二月|02月|2月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 2; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Mar[A-Za-z]*|三月|03月|3月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 3; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Apr[A-Za-z]*|四月|04月|4月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 4; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("May[A-Za-z]*|五月|05月|5月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 5; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Jun[A-Za-z]*|六月|06月|6月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 6; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Jul[A-Za-z]*|七月|07月|7月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 7; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Aug[A-Za-z]*|八月|08月|8月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 8; + oValue = oValue.replace(exp, ""); + } + exp = new RegExp("Sep[A-Za-z]*|九月|09月|9月", "i"); + if (oValue.match(exp) !== null) { + aMonth = 9; + oValue = oValue.replace(exp, ""); + } + oValue = oValue.replace(/日|秒/g, " "); + oValue = oValue.replace(/时|分/g, ":"); + var subTime = oValue.match(/ \d+:\d+:\d+/); + if (subTime == null) subTime = ""; + oValue = oValue.replace(/ \d+:\d+:\d+/, "") + subTime; + var dValue = new Date(); + var iYear = 0; + var iMonth = 0; + var iDate = 0; + var iHour = 0; + var iMinutes = 0; + var iSecond = 0; + var tmpValue = oValue; + var sValue = ""; + var MC1 = 0; + MC2 = 0; + MC3 = 0; + sValue = tmpValue.match(/\d+/); + if (sValue !== null) { + MC1 = parseInt(sValue[0]); + tmpValue = tmpValue.replace(/\d+/, ""); + } + sValue = tmpValue.match(/\d+/); + if (sValue !== null) { + MC2 = parseInt(sValue[0]); + tmpValue = tmpValue.replace(/\d+/, ""); + } + if (aMonth <= 0) { + sValue = tmpValue.match(/\d+/); + if (sValue !== null) { + MC3 = parseInt(sValue[0]); + tmpValue = tmpValue.replace(/\d+/, ""); + } + } + if (aMonth > 0) { + iMonth = aMonth; + if (MC2 <= 31) { + iYear = MC1; + iDate = MC2; + } else { + iYear = MC2; + iDate = MC1; + } + } else + if (TypeYMD == "dmy") { + iDate = MC1; + iMonth = MC2; + iYear = MC3; + } else + if (TypeYMD == "mdy") { + iMonth = MC1; + iDate = MC2; + iYear = MC3; + } else { + iYear = MC1; + iMonth = MC2; + iDate = MC3; + if (MC3 > 31) { + iYear = MC3; + iMonth = MC1; + iDate = MC2; + if (MC1 > 12) { + iDate = MC1; + iMonth = MC2 + }; + } else { + if (MC2 > 12) { + iYear = MC2; + iMonth = MC1; + } + } + } + var sValue = tmpValue.match(/\d+/); + if (sValue !== null) { + iHour = parseInt(sValue[0]); + tmpValue = tmpValue.replace(/\d+/, ""); + } + var sValue = tmpValue.match(/\d+/); + if (sValue !== null) { + iMinutes = parseInt(sValue[0]); + tmpValue = tmpValue.replace(/\d+/, ""); + } + var sValue = tmpValue.match(/\d+/); + if (sValue !== null) { + iSecond = parseInt(sValue[0]); + tmpValue = tmpValue.replace(/\d+/, ""); + } + if (oType.toLowerCase() == "isvalidformat") + oValue = (iYear > 0 && iMonth > 0 && iMonth <= 12 && iDate > 0 && iDate <= 31); + else { + if (("" + iYear).length < 4) iYear = iYear + 2000; + dValue.setFullYear(iYear, iMonth - 1, iDate); + dValue.setHours(iHour); + dValue.setMinutes(iMinutes); + dValue.setSeconds(iSecond); + var iDay = dValue.getDay(); + if (oType.toLowerCase() == "weekindex") + oValue = iDay; + else + if (oType.toLowerCase() == "floatvalue") + oValue = dValue.getTime(); + else { + var sWeek = ""; + switch (iDay) { + case 0: + sWeek = "日"; + break; + case 1: + sWeek = "一"; + break; + case 2: + sWeek = "二"; + break; + case 3: + sWeek = "三"; + break; + case 4: + sWeek = "四"; + break; + case 5: + sWeek = "五"; + break; + case 6: + sWeek = "六"; + break; + } + oValue = oType.replace(/dddd/ig, "星期" + sWeek); + if (/(y+)/i.test(oValue)) oValue = oValue.replace(RegExp.$1, (iYear + "").substr(4 - RegExp.$1.length)); + if (/(m+:)/i.test(oValue)) oValue = oValue.replace(RegExp.$1, ("00" + iMinutes + ":").substr(("00" + iMinutes + + ":").length - RegExp.$1.length)); + if (/(M+)/i.test(oValue)) { + var dsWidth = ("" + iMonth).length > RegExp.$1.length ? ("" + iMonth).length : RegExp.$1.length; + oValue = oValue.replace(RegExp.$1, ("00" + iMonth).substr(("00" + iMonth).length - dsWidth)); + } + if (/(d+)/i.test(oValue)) { + var dsWidth = ("" + iDate).length > RegExp.$1.length ? ("" + iDate).length : RegExp.$1.length; + oValue = oValue.replace(RegExp.$1, ("00" + iDate).substr(("00" + iDate).length - dsWidth)); + } + if (/(H+)/i.test(oValue)) oValue = oValue.replace(RegExp.$1, ("00" + iHour).substr(("00" + iHour).length - + RegExp.$1.length)); + if (/(n+)/i.test(oValue)) oValue = oValue.replace(RegExp.$1, ("00" + iMinutes).substr(("00" + iMinutes).length - + RegExp.$1.length)); + if (/(s+)/i.test(oValue)) oValue = oValue.replace(RegExp.$1, ("00" + iSecond).substr(("00" + iSecond).length - + RegExp.$1.length)); + } + } + if (CLODOP.On_Return) { + var selfFunc = CLODOP.On_Return; + CLODOP.On_Return(0, oValue); + if (!CLODOP.On_Return_Remain && selfFunc === CLODOP.On_Return) CLODOP.On_Return = null; + } + return oValue; + } else + if (this.blIslocal || oType.indexOf("FILE:") < 0) { + this.PageData["format_type"] = oType; + this.PageData["format_value"] = oValue; + if (this.DoPostDatas("format") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } else console.info(this.altMessageNoReadWriteFile) + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + SET_PRINT_PAPER: function(Top, Left, Width, Height, strPrintTask) { + return this.PRINT_INITA(Top, Left, Width, Height, strPrintTask); + }, + PRINT_INIT: function(strPrintTask,host) { + this.wsHostURI = `ws://${host}:8000/c_webskt/`; + return this.PRINT_INITA(null, null, null, null, strPrintTask); + }, + PRINT_INITA: function(Top, Left, Width, Height, strPrintTask) { + if (Top === undefined || Top === null) Top = ""; + if (Left === undefined || Left === null) Left = ""; + if (Width === undefined || Width === null) Width = ""; + if (Height === undefined || Height === null) Height = ""; + if (strPrintTask === undefined || strPrintTask === null) strPrintTask = ""; + this.NoClearAfterPrint = false; + this.DoInit(); + this.PageData["top"] = Top; + this.PageData["left"] = Left; + this.PageData["width"] = Width; + this.PageData["height"] = Height; + this.PageData["printtask"] = strPrintTask; + return true; + }, + SET_PRINT_MODE: function(strModeType, ModeValue) { + if (strModeType === undefined || strModeType === null) strModeType = ""; + if (ModeValue === undefined || ModeValue === null) ModeValue = ""; + if (strModeType === "") return false; + strModeType = strModeType.toLowerCase(); + this.PageData[strModeType] = ModeValue; + if (strModeType == "noclear_after_print") this.NoClearAfterPrint = ModeValue; + if (strModeType.indexOf("window_def") > -1 || strModeType.indexOf("control_printer") > -1) { + var tResult = null; + if (this.DoPostDatas("onlysetprint") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + this.DoInit(); + this.blWorking = false; + return tResult; + } + }, + ADD_PRINT_TEXT: function(top, left, width, height, strText) { + return this.AddItemArray(2, top, left, width, height, strText); + }, + ADD_PRINT_TEXTA: function(itemName, top, left, width, height, strText) { + return this.AddItemArray(2, top, left, width, height, strText, itemName); + }, + ADD_PRINT_HTM: function(top, left, width, height, strHTML) { + return this.AddItemArray(4, top, left, width, height, strHTML); + }, + ADD_PRINT_HTML: function(top, left, width, height, strHTML) { + return this.AddItemArray(1, top, left, width, height, strHTML); + }, + ADD_PRINT_HTMLA: function(itemName, top, left, width, height, strHTML) { + return this.AddItemArray(1, top, left, width, height, strHTML, itemName); + }, + ADD_PRINT_BARCODE: function(top, left, width, height, BarType, BarValue) { + return this.AddItemArray(9, top, left, width, height, BarValue, null, null, null, null, null, null, BarType); + }, + ADD_PRINT_BARCODEA: function(ItemName, top, left, width, height, BarType, BarValue) { + return this.AddItemArray(9, top, left, width, height, BarValue, ItemName, null, null, null, null, null, BarType); + }, + ADD_PRINT_RECTA: function(top, left, width, height, intPenStyle, intPenWidth, intColor) { + return this.AddItemArray(3, top, left, width, height, null, null, 2, intPenStyle, intPenWidth, intColor, null); + }, + ADD_PRINT_RECT: function(top, left, width, height, intPenStyle, intPenWidth) { + return this.AddItemArray(3, top, left, width, height, null, null, 2, intPenStyle, intPenWidth, null, null); + }, + ADD_PRINT_ELLIPSEA: function(top, left, width, height, intPenStyle, intPenWidth, intColor) { + return this.AddItemArray(3, top, left, width, height, null, null, 3, intPenStyle, intPenWidth, intColor, null); + }, + ADD_PRINT_ELLIPSE: function(top, left, width, height, intPenStyle, intPenWidth) { + return this.AddItemArray(3, top, left, width, height, null, null, 3, intPenStyle, intPenWidth, null, null); + }, + ADD_PRINT_SHAPE: function(ShapeType, top, left, width, height, intPenStyle, intPenWidth, intColor) { + return this.AddItemArray(3, top, left, width, height, null, null, ShapeType, intPenStyle, intPenWidth, intColor, + null); + }, + ADD_PRINT_LINE: function(top1, left1, top2, left2, intPenStyle, intPenWidth) { + return this.AddItemArray(3, top1, left1, top2, left2, null, null, 0, intPenStyle, intPenWidth, null, "1"); + }, + ADD_PRINT_DNLINE: function(Top, Left, Width, Height, intPenStyle, intPenWidth) { + return this.AddItemArray(3, Top, Left, Width, Height, null, null, 1, intPenStyle, intPenWidth, null, null); + }, + ADD_PRINT_DNLINEA: function(Top, Left, Width, Height, intPenStyle, intPenWidth, intColor) { + return this.AddItemArray(3, Top, Left, Width, Height, null, null, 1, intPenStyle, intPenWidth, intColor, null); + }, + ADD_PRINT_UPLINE: function(Top, Left, Width, Height, intPenStyle, intPenWidth) { + return this.AddItemArray(3, Top, Left, Width, Height, null, null, 0, intPenStyle, intPenWidth, null, null); + }, + ADD_PRINT_UPLINEA: function(Top, Left, Width, Height, intPenStyle, intPenWidth, intColor) { + return this.AddItemArray(3, Top, Left, Width, Height, null, null, 0, intPenStyle, intPenWidth, intColor, null); + }, + ADD_PRINT_TABLE: function(top, left, width, height, strHTML) { + return this.AddItemArray(6, top, left, width, height, strHTML); + }, + ADD_PRINT_TBURL: function(top, left, width, height, strURL) { + return this.AddItemArray(7, top, left, width, height, strURL); + }, + ADD_PRINT_URL: function(top, left, width, height, strURL) { + return this.AddItemArray(5, top, left, width, height, strURL); + }, + ADD_PRINT_IMAGE: function(top, left, width, height, strHTML) { + return this.AddItemArray(8, top, left, width, height, strHTML); + }, + ADD_PRINT_CHART: function(top, left, width, height, strChartTypess, strHTML) { + return this.AddItemArray(10, top, left, width, height, strHTML, null, null, null, null, null, null, null, + strChartTypess); + }, + + SET_PRINT_PROPERTY: function(ItemNO, intPageType, intHorzOrient, intVertOrient) { + this.SET_PRINT_STYLEA(ItemNO, "ItemType", intPageType); + this.SET_PRINT_STYLEA(ItemNO, "HOrient", intHorzOrient); + this.SET_PRINT_STYLEA(ItemNO, "VOrient", intVertOrient); + }, + SET_PRINT_PROPERTYA: function(ItemName, intPageType, intHorzOrient, intVertOrient) { + this.SET_PRINT_PROPERTY(ItemName, intPageType, intHorzOrient, intVertOrient); + }, + SET_PRINT_STYLE: function(strStyleName, StyleValue) { + if (strStyleName === undefined || strStyleName === null) strStyleName = ""; + if (StyleValue === undefined || StyleValue === null) StyleValue = ""; + if (strStyleName === "") return false; + strStyleName = strStyleName.toLowerCase(); + this.defStyleJson[strStyleName] = StyleValue; + }, + SET_PRINT_STYLEA: function(ItemNo, strKey, Value) { + if (ItemNo === undefined || ItemNo === null) ItemNo = ""; + if (strKey === undefined || strKey === null) strKey = ""; + if (Value === undefined || Value === null) Value = ""; + if (ItemNo === "" || strKey === "") return false; + if (this.ItemDatas["count"] <= 0) { + if (this.PageData["add_print_program_data"] !== undefined) { + this.ItemCNameStyles[strKey.toLowerCase() + "-" + ItemNo] = Value; + return true; + } else { + return false; + } + } + strKey = strKey.toLowerCase(); + if (strKey == "type") return false; + var blResult = false; + if (ItemNo == 0) { + ItemNo = this.ItemDatas["count"]; + } + for (var vItemNO in this.ItemDatas) { + var ItemName = this.ItemDatas[vItemNO]["itemname"]; + if ((ItemNo == vItemNO) || (ItemNo == ItemName) || ((typeof ItemNo === "string") && (typeof ItemName === + "string") && (ItemNo.toUpperCase() == ItemName.toUpperCase()))) { + this.ItemDatas[vItemNO][strKey] = Value; + blResult = true; + } + } + if (blResult) return true; + return false; + }, + SET_PRINT_TEXT_STYLE: function(ItemNO, strFontName, intSize, intBold, intItalic, intUnderline, intAlignment) { + this.SET_PRINT_STYLEA(ItemNO, "fontname", strFontName); + this.SET_PRINT_STYLEA(ItemNO, "fontsize", intSize); + this.SET_PRINT_STYLEA(ItemNO, "bold", intBold); + this.SET_PRINT_STYLEA(ItemNO, "italic", intItalic); + this.SET_PRINT_STYLEA(ItemNO, "underline", intUnderline); + this.SET_PRINT_STYLEA(ItemNO, "alignment", intAlignment); + }, + SET_PRINT_TEXT_STYLEA: function(ItemNO, strFontName, intSize, intBold, intItalic, intUnderline, intAlignment, Color) { + this.SET_PRINT_TEXT_STYLE(ItemNO, strFontName, intSize, intBold, intItalic, intUnderline, intAlignment); + this.SET_PRINT_STYLEA(ItemNO, "fontcolor", Color); + }, + SET_PRINT_TEXT_STYLEB: function(ItemNO, strFontName, intSize, intBold, intItalic, intUnderline, intAlignment, Color) { + this.SET_PRINT_TEXT_STYLEA(ItemNO, strFontName, intSize, intBold, intItalic, intUnderline, intAlignment, Color); + }, + NEWPAGE: function() { + this.NewPage(); + }, + NewPage: function() { + var blSomeNormal = false; + var noItemType; + for (var vItemNO in this.ItemDatas) { + if (vItemNO == "count") noItemType = false; + else noItemType = true; + for (var vItemxx in this.ItemDatas[vItemNO]) { + if (vItemxx == "itemtype") { + noItemType = false; + if ((this.ItemDatas[vItemNO][vItemxx] == 0) || (this.ItemDatas[vItemNO][vItemxx] == 4)) { + blSomeNormal = true; + break; + } + } + } + if (noItemType) blSomeNormal = true; + if (blSomeNormal) break; + } + if (blSomeNormal) this.defStyleJson["beginpage"] = this.defStyleJson["beginpage"] + 1; + }, + NEWPAGEA: function() { + this.NewPageA(); + }, + NewPageA: function() { + var blSomeNormal = false; + var noItemType; + for (var vItemNO in this.ItemDatas) { + if (vItemNO == "count") noItemType = false; + else noItemType = true; + for (var vItemxx in this.ItemDatas[vItemNO]) { + if (vItemxx == "itemtype") { + noItemType = false; + if ((this.ItemDatas[vItemNO][vItemxx] == 0) || (this.ItemDatas[vItemNO][vItemxx] == 4)) { + blSomeNormal = true; + break; + } + } + } + if (noItemType) blSomeNormal = true; + if (blSomeNormal) break; + } + if (blSomeNormal) this.defStyleJson["beginpagea"] = this.defStyleJson["beginpagea"] + 1; + }, + PREVIEW: function(sView, iW, iH) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if ((!sView) && (this.blIslocal)) { + if (this.DoPostDatas("preview") == true) { + this.Result = null; + this.GetLastResult(true); + tResult = this.GetTaskID(); + } + } else { + if (this.DoPostDatas("cpreview") == true) { + this.DoCPreview(sView, iW, iH); + tResult = this.GetTaskID(); + } + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + PRINT: function(sView, iW, iH) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.DoPostDatas("print") == true) + tResult = this.GetTaskID(); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + GET_PRINTER_COUNT: function() { + if (this.Printers === undefined) return 0; + else { + return this.Printers["list"].length; + } + }, + GET_PRINTER_NAME: function(intNO) { + if (this.Printers === undefined) return ""; + else { + if (typeof intNO == "string" && intNO.indexOf(":") > -1) { + var strPPname = intNO.slice(intNO.indexOf(":") + 1); + intNO = intNO.slice(0, intNO.indexOf(":")); + if (intNO == -1) + return this.Printers["list"][this.Printers["default"]][strPPname]; + else + return this.Printers["list"][intNO][strPPname]; + } else { + if (intNO == -1) + return this.Printers["list"][this.Printers["default"]].name; + else + if (intNO >= 0 && intNO < this.Printers["list"].length) + return this.Printers["list"][intNO].name; + else return "Printer NO. overflow"; + } + } + }, + GET_PAGESIZES_LIST: function(PNameIndx, Split, ListName, NameOrID) { + if (!ListName) ListName = "pagelist"; + if (!NameOrID) NameOrID = "name"; + if (this.Printers === undefined) return ""; + else { + if (PNameIndx == -1) PNameIndx = this.Printers["list"][this.Printers["default"]].name; + for (var intNO in this.Printers["list"]) { + if (PNameIndx == intNO || PNameIndx == this.Printers["list"][intNO].name) { + var strList = ""; + for (var iPNO in this.Printers["list"][intNO][ListName]) { + if ((NameOrID == "id") && this.Printers["list"][intNO][ListName][iPNO].id) { + if (strList === "") strList = this.Printers["list"][intNO][ListName][iPNO].id; + else + strList = strList + Split + this.Printers["list"][intNO][ListName][iPNO].id; + } else { + if (strList === "") strList = this.Printers["list"][intNO][ListName][iPNO].name; + else + strList = strList + Split + this.Printers["list"][intNO][ListName][iPNO].name; + } + } + return strList; + } + } + return ""; + } + }, + SET_PRINTER_INDEX: function(strName, strKeyModeName) { + if (isNaN(strName)) { + this.PageData.printerindex = 1 + } else{ + this.PageData.printerindex = strName + } + return true; + if (this.Printers === undefined) return false; + else { + if (!strKeyModeName) strKeyModeName = "printerindex"; + strName = strName + ""; + strName = strName.replace(/^\s+|\s+$/g, ""); + var iPos = strName.indexOf(","); + var strNameOrNO = strName; + if (iPos > -1) strNameOrNO = strName.slice(0, iPos); + if (strNameOrNO == "-1") { + this.PageData[strKeyModeName] = this.Printers["default"]; + if (iPos > -1) this.PageData["printersubid"] = strName.slice(iPos + 1); + return true; + } else { + for (var vNO in this.Printers["list"]) { + var strPrinterName = this.Printers["list"][vNO].name; + if (!strPrinterName) continue; + if ((strPrinterName.replace(/\\/g, "") == strNameOrNO.replace(/\\/g, "")) || (vNO == strNameOrNO)) { + this.PageData[strKeyModeName] = vNO; + if (iPos > -1) this.PageData["printersubid"] = strName.slice(iPos + 1); + return true; + } + } + return false; + } + } + }, + SET_PRINTER_INDEXA: function(strName) { + return this.SET_PRINTER_INDEX(strName, "printerindexa"); + }, + PRINT_DESIGN: function() { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.blIslocal) { + if (this.DoPostDatas("print_design") == true) { + this.Result = null; + this.GetLastResult(true); + tResult = this.GetTaskID(); + } + } else console.info(this.altMessageNoPrintDesign); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + PRINT_SETUP: function() { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.blIslocal) { + if (this.DoPostDatas("print_setup") == true) { + this.Result = null; + this.GetLastResult(true); + tResult = this.GetTaskID(); + } + } else console.info(this.altMessageNoPrintSetup); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + SET_PRINT_PAGESIZE: function(intOrient, PageWidth, PageHeight, strPageName) { + if (intOrient !== undefined && intOrient !== null) this.PageData["orient"] = intOrient; + if (PageWidth !== undefined && PageWidth !== null) this.PageData["pagewidth"] = PageWidth; + if (PageHeight !== undefined && PageHeight !== null) this.PageData["pageheight"] = PageHeight; + if (strPageName !== undefined && strPageName !== null) this.PageData["pagename"] = strPageName; + }, + SET_PRINT_COPIES: function(intCopies) { + if (intCopies !== undefined && intCopies !== null) { + this.PageData["printcopies"] = intCopies; + return true; + } + }, + SELECT_PRINTER: function(blPrint) { + this.SelectBox.create(388, 240, !blPrint); + return true; + }, + PRINTA: function(blPrintB, sView) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (!sView && this.blIslocal) { + this.Result = null; + if (blPrintB) { + if (this.DoPostDatas("printb") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } else { + if (this.DoPostDatas("printa") == true) { + this.GetLastResult(true); + tResult = this.GetTaskID(); + } + } + this.DoInit(); + this.blWorking = false; + } else { + this.SELECT_PRINTER(true); + } + return tResult; + }, + PRINTAOK: function(iPrintIndex, iPrintCopies, iStartNO, iEndNO, onlySelect) { + this.SET_PRINTER_INDEX(iPrintIndex); + this.SET_PRINT_COPIES(iPrintCopies); + if (iStartNO !== undefined && iStartNO !== 0) this.SET_PRINT_MODE("PRINT_START_PAGE", iStartNO); + if (iEndNO !== undefined && iEndNO !== 0) this.SET_PRINT_MODE("PRINT_END_PAGE", iEndNO); + if (!onlySelect) this.PRINT(); + else { + this.blTmpSelectedIndex = iPrintIndex; + if (CLODOP.On_Return) { + var selfFunc = CLODOP.On_Return; + CLODOP.On_Return(0, iPrintIndex); + if (!CLODOP.On_Return_Remain && selfFunc === CLODOP.On_Return) CLODOP.On_Return = null; + } + } + }, + SET_LICENSES: function(strCompanyName, strLicense, strLicenseA, strLicenseB) { + if ((strCompanyName == 'THIRD LICENSE') && (strLicense == "")) { + if (strLicenseA && strLicenseA !== "") this.PageDataEx["licensec"] = strLicenseA; + if (strLicenseB && strLicenseB !== "") this.PageDataEx["licensed"] = strLicenseB; + } else if ((strCompanyName == 'LICENSE TETCODE') && (strLicense == "") && (strLicenseB == "")) { + if (strLicenseA && strLicenseA !== "") this.PageDataEx["Licensetetcode"] = strLicenseA; + } else { + if (strCompanyName && strCompanyName !== "") this.PageDataEx["companyname"] = strCompanyName; + if (strLicense && strLicense !== "") this.PageDataEx["license"] = strLicense; + if (strLicenseA && strLicenseA !== "") this.PageDataEx["licensea"] = strLicenseA; + if (strLicenseB && strLicenseB !== "") this.PageDataEx["licenseb"] = strLicenseB; + } + }, + PRINTB: function() { + return this.PRINTA(true); + }, + PREVIEWA: function() { + return this.PREVIEW(); + }, + PREVIEWB: function() { + return this.PREVIEW(); + }, + ADD_PRINT_SETUP_BKIMG: function(strContent) { + if (strContent !== undefined && strContent !== null) { + this.PageData["setup_bkimg"] = strContent; + return true; + } + }, + SET_PREVIEW_WINDOW: function(intDispMode, intToolMode, blDirectPrint, oWidth, oHeight, strPButtonCaptoin) { + if (intDispMode !== undefined && intDispMode !== null) this.PageData["pvw_dispmode"] = intDispMode; + if (intToolMode !== undefined && intToolMode !== null) this.PageData["pvw_toolmode"] = intToolMode; + if (blDirectPrint !== undefined && blDirectPrint !== null) this.PageData["pvw_directprint"] = blDirectPrint; + if (oWidth !== undefined && oWidth !== null) this.PageData["pvw_width"] = oWidth; + if (oHeight !== undefined && oHeight !== null) this.PageData["pvw_height"] = oHeight; + if (strPButtonCaptoin !== undefined && strPButtonCaptoin !== null) this.PageData["pvw_puttoncaptoin"] = + strPButtonCaptoin; + }, + SET_PREVIEW_MODE: function(ModeValue) { + if (ModeValue !== undefined) this.PageData["pvw_preview_mode"] = ModeValue; + }, + SET_SHOW_MODE: function(strModeType, ModeValue) { + if (strModeType === undefined || strModeType === null) strModeType = ""; + if (ModeValue === undefined || ModeValue === null) ModeValue = ""; + if (strModeType === "") return false; + strModeType = strModeType.toLowerCase(); + this.PageData['shwmod_' + strModeType] = ModeValue; + }, + SAVE_TO_FILE: function(strFileName) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.blIslocal) { + if (strFileName) { + this.PageData["stf_file_name"] = strFileName; + if (this.DoPostDatas("savetofile") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + } else console.info(this.altMessageNoWriteFile); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + SET_SAVE_MODE: function(strModeType, ModeValue) { + if (strModeType === undefined || strModeType === null) strModeType = ""; + if (ModeValue === undefined || ModeValue === null) ModeValue = ""; + if (strModeType === "") return false; + strModeType = strModeType.toLowerCase(); + this.PageData['stfmod_' + strModeType] = ModeValue; + }, + SEND_PRINT_RAWDATA: function(strRawData) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (strRawData !== undefined) { + this.PageData["raw_print_data"] = strRawData; + if (this.DoPostDatas("sendrawdata") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + WRITE_FILE_TEXT: function(WriteMode, strFileName, strText) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.blIslocal) { + if (strFileName !== undefined && strText !== undefined) { + this.PageData["write_file_mode"] = WriteMode; + this.PageData["write_file_name"] = strFileName; + this.PageData["write_file_text"] = strText; + if (this.DoPostDatas("writefiletext") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + } else console.info(this.altMessageNoWriteFile); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + GET_DIALOG_VALUE: function(oType, oPreValue) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (oType !== undefined && oPreValue !== undefined) { + if (this.blIslocal) { + this.PageData["dialog_type"] = oType; + this.PageData["dialog_value"] = oPreValue; + if (this.DoPostDatas("dialog") == true) { + this.GetLastResult(true); + tResult = this.GetTaskID(); + } + } else console.info(this.altMessageNoReadWriteFile); + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + WRITE_PORT_DATA: function(strPortName, strData) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (strPortName !== undefined && strData !== undefined) { + this.PageData["write_port_name"] = strPortName; + this.PageData["write_port_data"] = strData; + if (this.DoPostDatas("writeportdata") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + READ_PORT_DATA: function(strPortName) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (strPortName !== undefined) { + this.PageData["read_port_name"] = strPortName; + if (this.DoPostDatas("readportdata") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + GET_SYSTEM_INFO: function(InfoType) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (InfoType !== undefined) { + this.PageData["system_info_type"] = InfoType; + if (this.DoPostDatas("getsysteminfo") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + GET_FILE_TEXT: function(strFileName) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.blIslocal) { + if (strFileName !== undefined) { + this.PageData["get_file_name"] = strFileName; + if (this.DoPostDatas("getfiletext") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + } else console.info(this.altMessageNoReadFile); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + IS_FILE_EXIST: function(strFileName) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.blIslocal) { + if (strFileName !== undefined) { + this.PageData["file_exist_name"] = strFileName; + if (this.DoPostDatas("isfileexist") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + } else console.info(this.altMessageNoReadFile); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + GET_FILE_TIME: function(strFileName) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.blIslocal) { + if (strFileName !== undefined) { + this.PageData["file_time_name"] = strFileName; + if (this.DoPostDatas("getfiletime") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + } else console.info(this.altMessageNoReadFile); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + GET_PRINT_INIFFNAME: function(strPrintTaskName) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (this.blIslocal) { + if (strPrintTaskName !== undefined) { + this.PageData["iniff_task_name"] = strPrintTaskName; + if (this.DoPostDatas("getiniffname") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + } else console.info(this.altMessageNoReadFile); + this.DoInit(); + this.blWorking = false; + return tResult; + }, + GET_VALUE: function(ValueType, ValueIndex) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (ValueType !== undefined && ValueIndex !== undefined) { + this.PageData["get_value_type"] = ValueType; + this.PageData["get_value_index"] = ValueIndex; + if (this.DoPostDatas("dogetvalue") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + ADD_PRINT_DATA: function(DataType, oValue) { + if (DataType !== undefined && oValue !== null) { + if (DataType.toLowerCase().indexOf("programdata") > -1) { + this.PageData["add_print_program_data"] = oValue; + return true; + } + } + }, + SHOW_CHART: function() {}, + DO_ACTION: function(strActName, strActValue) { + if (this.blWorking) { + console.info(this.altMessageBusy); + return null; + } + var tResult = null; + if (strActName !== undefined && strActValue !== undefined) { + this.PageData["do_action_name"] = strActName; + this.PageData["do_action_value"] = strActValue; + if (this.DoPostDatas("doaction") == true) { + this.GetLastResult(false); + tResult = this.GetTaskID(); + } + } + this.DoInit(); + this.blWorking = false; + return tResult; + }, + Create_Printer_List: function(oElement, blNoDetailForAO) { + while (oElement.childNodes.length > 0) { + var children = oElement.childNodes; + for (var i = 0; i < children.length; i++) + oElement.removeChild(children[i]); + }; + var iCount = this.GET_PRINTER_COUNT(); + var iIndex = 0; + for (var i = 0; i < iCount; i++) { + var option = document.createElement('option'); + option.innerHTML = this.GET_PRINTER_NAME(i); + option.value = iIndex; + oElement.appendChild(option); + iIndex++; + if (this.VERSION_EXT) { + if (this.Printers["list"][i]["subdevlist"].length > 0) { + if (blNoDetailForAO) option.innerHTML = option.innerHTML + ',..'; + else { + var strDrivename = option.innerHTML; + for (var j = 0; j < this.Printers["list"][i]["subdevlist"].length; j++) { + var strDevID = this.Printers["list"][i]["subdevlist"][j].id; + var strDevName = this.Printers["list"][i]["subdevlist"][j].name; + if (j == 0) { + option.innerHTML = strDrivename + ',' + strDevName; + option.value = strDrivename + ',' + strDevID + ';' + strDevName; + } else { + option = document.createElement('option'); + option.innerHTML = strDrivename + ',' + strDevName; + option.value = strDrivename + ',' + strDevID + ';' + strDevName; + oElement.appendChild(option); + iIndex++; + if (iIndex >= 100) return; + } + } + } + } + } + } + }, + Create_PageSize_List: function(oElement, printIndex) { + while (oElement.childNodes.length > 0) { + var children = oElement.childNodes; + for (var i = 0; i < children.length; i++) + oElement.removeChild(children[i]); + }; + var strPageSizeList = CLODOP.GET_PAGESIZES_LIST(printIndex, "\n"); + var Options = new Array(); + Options = strPageSizeList.split("\n"); + for (var i in Options) { + var option = document.createElement('option'); + option.innerHTML = Options[i]; + option.value = Options[i]; + oElement.appendChild(option); + } + }, + SET_BRIDGE_INDEX: function(strValue) { + if (this.Printers === undefined) return false; + else { + strValue = (strValue + "").replace(/^\s+|\s+$/g, ""); + for (var vNO in this.Printers["list"]) { + var strDriverOrName = this.Printers["list"][vNO].name; + if (strDriverOrName == "(AO)Client-Bridge Driver") { + this.PageData["printerindex"] = vNO; + this.PageData["printersubid"] = strValue; + return true; + } + } + return false; + } + }, + Get_AOPrinters_List: function(DriverNameOrIndex, strListName, strSplit) { + if (!strSplit) strSplit = "\n"; + if (!strListName) strListName = "name"; + return CLODOP.GET_PAGESIZES_LIST(DriverNameOrIndex, strSplit, "subdevlist", strListName); + }, + Get_AOBridges_List: function(DriverNameOrIndex, strListName, strSplit) { + return CLODOP.Get_AOPrinters_List(DriverNameOrIndex, strListName, strSplit); + }, + Get_AOBridge_List: function(strListName, strSplit) { + return CLODOP.Get_AOPrinters_List("(AO)Client-Bridge Driver", strListName, strSplit); + }, + Get_AOBridge_SubPrinters_List: function(BridgeNameOrIndex, strListName, strSplit, DriverNameOrIndex) { + if (!DriverNameOrIndex) DriverNameOrIndex = "(AO)Client-Bridge Driver"; + if (!strSplit) strSplit = "\n"; + if (!strListName) strListName = "name"; + for (var iDrvNO in this.Printers["list"]) { + if (DriverNameOrIndex == iDrvNO || DriverNameOrIndex == this.Printers["list"][iDrvNO].name) { + for (var iBdgNO in this.Printers["list"][iDrvNO]["subdevlist"]) { + var BridgeID = this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].id; + var BridgeName = this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].name; + if (BridgeNameOrIndex == iBdgNO || BridgeNameOrIndex == BridgeID + ";" + BridgeName) { + var strList = ""; + for (var iSsbPNO in this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].ssbprinter["list"]) { + if (iSsbPNO != "0") strList = strList + strSplit; + if (strListName.toLowerCase() == "id") strList = strList + iSsbPNO; + else + strList = strList + this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].ssbprinter["list"][iSsbPNO].name; + } + return strList; + } + } + } + } + return ""; + }, + Get_AOBridge_SubPrinters_PageSize_List: function(BridgeNameOrIndex, SubPrinterNameOrIndex, strSplit, + DriverNameOrIndex) { + if (!DriverNameOrIndex) DriverNameOrIndex = "(AO)Client-Bridge Driver"; + if (!strSplit) strSplit = "\n"; + for (var iDrvNO in this.Printers["list"]) { + if (DriverNameOrIndex == iDrvNO || DriverNameOrIndex == this.Printers["list"][iDrvNO].name) { + for (var iBdgNO in this.Printers["list"][iDrvNO]["subdevlist"]) { + var BridgeID = this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].id; + var BridgeName = this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].name; + if (BridgeNameOrIndex == iBdgNO || BridgeNameOrIndex == BridgeID + ";" + BridgeName) { + for (var iSsbPNO in this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].ssbprinter["list"]) { + if (SubPrinterNameOrIndex == iSsbPNO || SubPrinterNameOrIndex == this.Printers["list"][iDrvNO]["subdevlist"] + [iBdgNO].ssbprinter["list"][iSsbPNO].name) { + var strList = ""; + for (var iPageSizeNO in this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].ssbprinter["list"][iSsbPNO][ + "pagelist" + ]) { + if (iPageSizeNO != "0") strList = strList + strSplit; + strList = strList + this.Printers["list"][iDrvNO]["subdevlist"][iBdgNO].ssbprinter["list"][iSsbPNO][ + "pagelist" + ][iPageSizeNO].name; + } + return strList; + }; + } + } + } + } + } + return ""; + }, + AddItemArray: function(type, top, left, width, height, strContent, itemname, ShapeType, intPenStyle, intPenWidth, + intColor, isLinePosition, BarType, strChartTypess) { + if (top === undefined || left === undefined || width === undefined || height === undefined || strContent === + undefined) { + return false; + } + var sCount = this.ItemDatas["count"]; + sCount++; + var oneItem = {}; + for (var vstyle in this.defStyleJson) { + oneItem[vstyle] = this.defStyleJson[vstyle]; + } + oneItem["type"] = type; + oneItem["top"] = top; + oneItem["left"] = left; + oneItem["width"] = width; + oneItem["height"] = height; + if (strContent != null) { + if (typeof strContent === "string" && strContent.indexOf(this.DelimChar) > -1) + oneItem["content"] = strContent.replace(new RegExp(this.DelimChar, 'g'), ''); + else + oneItem["content"] = strContent; + } + if ((itemname !== undefined) && (itemname != null)) oneItem["itemname"] = itemname + ""; + if ((ShapeType !== undefined) && (ShapeType != null)) oneItem["shapetype"] = ShapeType; + if ((intPenStyle !== undefined) && (intPenStyle != null)) oneItem["penstyle"] = intPenStyle; + if ((intPenWidth !== undefined) && (intPenWidth != null)) oneItem["penwidth"] = intPenWidth; + if ((intColor !== undefined) && (intColor != null)) oneItem["fontcolor"] = intColor; + if ((isLinePosition !== undefined) && (isLinePosition != null)) oneItem["lineposition"] = "1"; + if ((BarType !== undefined) && (BarType != null)) oneItem["fontname"] = BarType; + if ((strChartTypess !== undefined) && (strChartTypess != null)) oneItem["charttypess"] = strChartTypess; + + oneItem["beginpage"] = this.defStyleJson["beginpage"]; + oneItem["beginpagea"] = this.defStyleJson["beginpagea"]; + this.ItemDatas["count"] = sCount; + this.ItemDatas[sCount] = oneItem; + this.blNormalItemAdded = true; + return true; + }, + RemoveIframes: function() { + // #ifndef APP-PLUS + var obody = document.body || document.getElementsByTagName("body")[0] || document.documentElement; + // #endif + try { + for (var i = 0; i < this.Iframes.length; i++) { + var now = (new Date()).getTime(); + if ((now - this.Iframes[i]["time"]) > this.timeThreshold * 60000) { + // #ifndef APP-PLUS + obody.removeChild(this.Iframes[i]["iframe"]); + // #endif + this.Iframes.splice(i, 1); + } + } + } catch (err) {}; + }, + AddInputElement: function(odocument, oform, name, value) { + if (value !== undefined) { + var oinput = odocument.createElement("input"); + oinput.name = name; + oinput.type = "hidden"; + oinput.value = value; + oform.appendChild(oinput); + } + }, + createPostDataString: function(afterPostAction) { + var strData = "act=" + afterPostAction + this.DelimChar; + strData = strData + "browseurl=" + window.location.href + this.DelimChar; + for (var vMode in this.PageDataEx) { + strData = strData + vMode + "=" + this.PageDataEx[vMode] + this.DelimChar; + } + var PrintModeNamess = ""; + for (var vMode in this.PageData) { + strData = strData + vMode + "=" + this.PageData[vMode] + this.DelimChar; + if (vMode != "top" && vMode != "left" && vMode != "width" && vMode != "height" && vMode != "printtask" && vMode != + "printerindex" && vMode != "printerindexa" && vMode != "printersubid" && vMode != "orient" && vMode != + "pagewidth" && vMode != "pageheight" && vMode != "pagename" && vMode != "printcopies" && vMode != "setup_bkimg" + ) + PrintModeNamess = PrintModeNamess + ";" + vMode; + } + if (PrintModeNamess !== "") + strData = strData + "printmodenames=" + PrintModeNamess + this.DelimChar; + var StyleClassNamess = ""; + for (var vClassStyle in this.ItemCNameStyles) { + strData = strData + vClassStyle + "=" + this.ItemCNameStyles[vClassStyle] + this.DelimChar; + StyleClassNamess = StyleClassNamess + ";" + vClassStyle; + } + if (StyleClassNamess !== "") + strData = strData + "printstyleclassnames=" + StyleClassNamess + this.DelimChar; + strData = strData + "itemcount=" + this.ItemDatas["count"] + this.DelimChar; + for (var vItemNO in this.ItemDatas) { + var ItemStyless = ""; + for (var vItemxx in this.ItemDatas[vItemNO]) { + if (vItemxx != "beginpage" && vItemxx != "beginpagea" && vItemxx != "type" && vItemxx != "top" && vItemxx != + "left" && vItemxx != "width" && vItemxx != "height") + ItemStyless = ItemStyless + ";" + vItemxx; + } + strData = strData + vItemNO + "_itemstylenames" + "=" + ItemStyless + this.DelimChar; + for (var vItemxx in this.ItemDatas[vItemNO]) { + strData = strData + vItemNO + "_" + vItemxx + "=" + this.ItemDatas[vItemNO][vItemxx] + this.DelimChar; + } + } + return strData; + }, + wsDoPostDatas: function(afterPostAction) { + var strData = "charset=丂" + this.DelimChar; + strData = strData + "tid=" + this.GetTaskID() + this.DelimChar; + strData = strData + this.createPostDataString(afterPostAction); + return this.wsSend("post:" + strData); + }, + DoPostDatas: function(afterPostAction) { + if (this.OBO_Mode && this.blOneByone) { + console.info(this.altMessageSomeWindowExist); + return false; + } + this.blWorking = true; + if (this.blTmpSelectedIndex !== null) + this.SET_PRINTER_INDEX(this.blTmpSelectedIndex); + if (this.SocketEnable) { + return this.wsDoPostDatas(afterPostAction); + } + // #ifdef APP-PLUS + return this.wsDoPostDatas(afterPostAction); + // #endif + this.RemoveIframes(); + var obody = document.body || document.getElementsByTagName("body")[0] || document.documentElement; + var oiframe = document.createElement("iframe"); + oiframe.setAttribute("src", "about:blank"); + oiframe.setAttribute("style", "display:none"); + oiframe.height = 0; + obody.appendChild(oiframe); + var contentdocument = oiframe.contentWindow.document; + contentdocument.write("
"); + var oform = contentdocument.getElementsByTagName("form")[0]; + this.AddInputElement(contentdocument, oform, "charset", "丂"); + this.AddInputElement(contentdocument, oform, "tid", this.GetTaskID()); + this.AddInputElement(contentdocument, oform, "post", this.createPostDataString(afterPostAction)); + oform.submit(); + var IframeMS = {}; + IframeMS["time"] = (new Date()).getTime(); + IframeMS["iframe"] = oiframe; + this.Iframes.push(IframeMS); + return true; + }, + GetLastResult: function(blFOneByone) { + if (blFOneByone) this.blOneByone = true; + if (this.SocketEnable) { + return true; + } + var url = this.strHostURI + "/c_lastresult.js"; + url = url + "?times=" + (new Date().getTime()); + url = url + "&tid=" + this.GetTaskID(); + url = encodeURI(url).replace("%20", "+"); + var oscript = document.createElement("script"); + oscript.src = url; + oscript.async = false; + oscript.type = "text/javascript"; + oscript.charset = "utf-8"; + var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement; + head.insertBefore(oscript, head.firstChild); + oscript.onload = oscript.onreadystatechange = function() { + if (!oscript.readyState || /loaded|complete/.test(oscript.readyState)) { + CLODOP.blOneByone = false; + if (CLodop_ACTLastResult) + var strResult = decodeURIComponent(CLodop_ACTLastResult); + var strResultTaskID = CLodop_ACTTaskID; + CLODOP.Result = strResult; + if (CLodop_ACTAlert) CLodop_ACTconsole.info(); + if (CLODOP.On_Return) + try { + var selfFunc = CLODOP.On_Return; + if (strResult == "true" || strResult == "false") + CLODOP.On_Return(strResultTaskID, strResult == "true"); + else + CLODOP.On_Return(strResultTaskID, strResult); + if (!CLODOP.On_Return_Remain && selfFunc === CLODOP.On_Return) CLODOP.On_Return = null; + } catch (err) {}; + oscript.onload = oscript.onreadystatechange = null; + if (oscript.parentNode) { + oscript.parentNode.removeChild(oscript); + } + } + }; + return true; + }, + DoCPreview: function(sView, iW, iH) { + var obody = document.body || document.getElementsByTagName("body")[0] || document.documentElement; + if (typeof iW !== "number") iW = Math.round(obody.offsetWidth * 2 / 3); + else + if (obody.offsetWidth < iW) iW = obody.offsetWidth; + if (typeof iH !== "number") iH = Math.round(window.screen.height - 200); + else + if (window.screen.height < iH) iH = window.screen.height; + var url = this.strHostURI + "/c_dopreview"; + url = url + "?times=" + (new Date().getTime()); + url = url + "&tid=" + this.GetTaskID(); + url = url + "&iw=" + iW; + url = url + "&ih=" + iH; + url = encodeURI(url).replace("%20", "+"); + this.PopView(sView, url, iW, iH); + }, + PopView: function(sView, strPURL, iW, iH) { + try { + if (sView && typeof sView === "string" && sView.length > 0) { + if (sView === "_dialog") { + if (window.showModalDialog) { + window.showModalDialog(strPURL, 'dialog', 'center:yes'); + } else { + window.open(strPURL, "", "scrollbars=yes,toolbar=no,left=150,top=100,resizable=yes"); + } + } else + if (sView === "_self" || sView === "_top" || sView === "_parent") { + window.location.href = strPURL; + } else + if (sView === "_blank") { + this.PreviewBox.create(strPURL, iW, iH); + } else + if (sView.indexOf("_winopen:") > -1) { + var strFeatures = sView.slice(sView.indexOf("_winopen:") + 9); + if (strFeatures.indexOf("_blank") > -1) + window.open(strPURL, "_blank", strFeatures.slice(strFeatures.indexOf("_blank") + 6)); + else + window.open(strPURL, "", strFeatures); + } else + if (document.getElementById(sView)) { + document.getElementById(sView).src = strPURL; + } else + console.info("iframe '" + sView + "' not exist!"); + } else this.PreviewBox.create(strPURL, iW, iH); + } catch (err) { + console.info("CLODOP PopView " + err); + }; + }, + creatMyButtonElement: function(strType, strValue) { + try { + var oElement = document.createElement(""); + } catch (e) {}; + if (!oElement) { + oElement = document.createElement("input"); + oElement.type = strType; + oElement.value = strValue; + } + return oElement; + }, + creatLabelElement: function(Type, Value, Width, Left, Top) { + var TxtLabel = document.createElement(Type); + TxtLabel.innerHTML = Value; + TxtLabel.style.cssText = "position:absolute;width:" + Width + "px;left:" + Left + "px;top:" + Top + "px;"; + return TxtLabel; + }, + SelectBox: { + dragapproved: false, + offsetx: 0, + offsety: 0, + tempx: 0, + tempy: 0, + FrantDiv: undefined, + PopDiv: undefined, + selPrinter: undefined, + selCopies: undefined, + closeit: function() { + if (CLODOP.SelectBox.PopDiv && CLODOP.SelectBox.PopDiv.parentNode) + CLODOP.SelectBox.PopDiv.parentNode.removeChild(CLODOP.SelectBox.PopDiv); + if (this.FrantDiv && this.FrantDiv.parentNode) + this.FrantDiv.parentNode.removeChild(this.FrantDiv); + this.PopDiv = undefined; + }, + initializedrag: function(e) { + var we = window.event || e; + this.offsetx = we.clientX; + this.offsety = we.clientY; + this.tempx = parseInt(this.PopDiv.style.left); + this.tempy = parseInt(this.PopDiv.style.top); + this.dragapproved = true; + }, + drag_drop: function(e) { + if (!this.dragapproved) return; + var we = window.event || e; + this.PopDiv.style.left = we.clientX - this.offsetx + this.tempx + "px"; + this.PopDiv.style.top = we.clientY - this.offsety + this.tempy + "px"; + }, + stopdrag: function() { + this.dragapproved = false; + }, + clickOK: function(onlySelect) { + CLODOP.PRINTAOK(CLODOP.SelectBox.selPrinter.value, CLODOP.SelectBox.selCopies.value, 0, 0, onlySelect); + this.closeit(); + }, + create: function(iW, iH, onlySelect) { + if (CLODOP.SelectBox.PopDiv) this.closeit(); + var obody = document.body || document.getElementsByTagName("body")[0] || document.documentElement; + var Boxdiv = document.createElement("div"); + obody.appendChild(Boxdiv); + Boxdiv.style.cssText = + "position:absolute;z-index:91100;display:block;top:2px;border:1px solid #6B97C1;background:#F5F5F5;color:#000;font-size:13px;"; + Boxdiv.style.width = iW + "px"; + Boxdiv.style.left = Math.max((obody.offsetWidth - iW) / 2, 0) + "px"; + Boxdiv.style.top = Math.max((obody.offsetHeight - iH) / 2, 0) + "px"; + Boxdiv.style.height = iH + "px"; + this.PopDiv = Boxdiv; + var titleDiv = document.createElement("div"); + Boxdiv.appendChild(titleDiv); + titleDiv.style.cssText = + "font: bold 13px Arial;line-height:25px;height:27px;text-indent:5px;color: white;background:#8BACCF"; + titleDiv.innerHTML = "      打印"; + titleDiv.onmousedown = function(event) { + CLODOP.SelectBox.initializedrag(event); + }; + titleDiv.onmousemove = function(event) { + CLODOP.SelectBox.drag_drop(event); + }; + titleDiv.onmouseup = function() { + CLODOP.SelectBox.stopdrag(); + }; + var icoButton = document.createElement("button"); + titleDiv.appendChild(icoButton); + icoButton.style.cssText = "background:transparent url(" + CLODOP.strHostURI + + "/c_favicon.ico) no-repeat scroll 0 0px;margin-left:5px;position:absolute;height:20px;line-height:100px;width:34px;left:3px;border:0;top:5px"; + var CloseButton = document.createElement("button"); + titleDiv.appendChild(CloseButton); + CloseButton.style.cssText = "background:transparent url(" + CLODOP.strHostURI + + "/images/c_winclose.png) no-repeat scroll 0 0px;margin-right:5px;position:absolute;height:20px;line-height:100px;width:34px;right:3px;border:0;top:4px"; + CloseButton.onclick = function() { + CLODOP.SelectBox.closeit(); + if (onlySelect && CLODOP.On_Return) { + var selfFunc = CLODOP.On_Return; + CLODOP.On_Return(0, -1); + if (!CLODOP.On_Return_Remain && selfFunc === CLODOP.On_Return) CLODOP.On_Return = null; + } + }; + var areaDiv = document.createElement("div"); + Boxdiv.appendChild(areaDiv); + areaDiv.style.cssText = "background:#F5F5F5;color:#000;border:0px;left:0px;top:0px;"; + areaDiv.style.width = iW - 2 + "px"; + areaDiv.style.height = (iH - 27) + "px"; + var OKButton = CLODOP.creatMyButtonElement("button", "确定"); + Boxdiv.appendChild(OKButton); + OKButton.style.cssText = "position:absolute;width:80px;height:23px;"; + OKButton.style.left = "110px"; + OKButton.style.top = (iH - 64) + "px"; + OKButton.onclick = function() { + CLODOP.SelectBox.clickOK(onlySelect); + }; + var CancelButton = CLODOP.creatMyButtonElement("button", "取消"); + Boxdiv.appendChild(CancelButton); + CancelButton.style.cssText = "position:absolute;width:80px;;height:23px;"; + CancelButton.style.left = "240px"; + CancelButton.style.top = (iH - 64) + "px"; + CancelButton.onclick = function() { + CLODOP.SelectBox.closeit(); + if (onlySelect && CLODOP.On_Return) { + var selfFunc = CLODOP.On_Return; + CLODOP.On_Return(0, -1); + if (!CLODOP.On_Return_Remain && selfFunc === CLODOP.On_Return) CLODOP.On_Return = null; + } + }; + areaDiv.appendChild(CLODOP.creatLabelElement("span", "选打印机:", 200, 46, 67)); + var oSelect = document.createElement("select"); + Boxdiv.appendChild(oSelect); + this.selPrinter = oSelect; + oSelect.style.cssText = "position:absolute;size:1;width:212px;left:110px;top:62px;"; + CLODOP.Create_Printer_List(oSelect); + areaDiv.appendChild(CLODOP.creatLabelElement("span", "打印份数:", 200, 46, 121)); + var oCopies = CLODOP.creatMyButtonElement("text", "1"); + Boxdiv.appendChild(oCopies); + this.selCopies = oCopies; + oCopies.style.cssText = "position:absolute;size:1;width:30px;left:110px;top:117px;"; + this.FrantDiv = document.createElement("div"); + obody.appendChild(this.FrantDiv); + this.FrantDiv.style.cssText = + "border:0px;left:0px;top:0px;filter: alpha(opacity=20); position: fixed; opacity: 0.2;-moz-opacity: 0.2; _position: absolute;z-index:91009; over-flow: hidden;"; + if (CLODOP.Browser.IE && (document.compatMode == "BackCompat" || navigator.userAgent.indexOf("MSIE 6.0") > 0)) { + this.FrantDiv.style.width = obody.scrollWidth + "px"; + this.FrantDiv.style.height = obody.scrollHeight + "px"; + } else { + this.FrantDiv.style.width = "100%"; + this.FrantDiv.style.height = "100%"; + } + } + }, + PreviewBox: { + dragapproved: false, + offsetx: 0, + offsety: 0, + tempx: 0, + tempy: 0, + FrantDiv: undefined, + PopDiv: undefined, + ContentFrame: undefined, + closeit: function(oSelf) { + if (CLODOP.PreviewBox.PopDiv && CLODOP.PreviewBox.PopDiv.parentNode) + CLODOP.PreviewBox.PopDiv.parentNode.removeChild(CLODOP.PreviewBox.PopDiv); + if (this.FrantDiv && this.FrantDiv.parentNode) + this.FrantDiv.parentNode.removeChild(this.FrantDiv); + this.PopDiv = undefined; + }, + initializedrag: function(e, oSelf) { + var we = window.event || e; + this.offsetx = we.clientX; + this.offsety = we.clientY; + this.tempx = parseInt(oSelf.style.left); + this.tempy = parseInt(oSelf.style.top); + this.dragapproved = true; + }, + drag_drop: function(e, oSelf) { + if (!this.dragapproved) return; + var we = window.event || e; + oSelf.style.left = we.clientX - this.offsetx + this.tempx + "px"; + oSelf.style.top = we.clientY - this.offsety + this.tempy + "px"; + }, + stopdrag: function() { + this.dragapproved = false; + if (this.ContentFrame) this.ContentFrame.style.display = "block"; + }, + create: function(strURL, iW, iH) { + if (CLODOP.PreviewBox.PopDiv) this.closeit(); + var obody = document.body || document.getElementsByTagName("body")[0] || document.documentElement; + var vBoxDiv = document.createElement("div"); + obody.appendChild(vBoxDiv); + vBoxDiv.style.cssText = + "position:absolute;z-index:91100;display:block;top:2px;border:1px solid #6B97C1;font-size:13px;"; + vBoxDiv.style.width = iW + "px"; + var iLeft = (obody.offsetWidth - iW) / 2; + if (window.screen.width < obody.offsetWidth) iLeft = (window.screen.width - iW) / 2; + if (iLeft < 0) iLeft = 0; + vBoxDiv.style.left = iLeft + "px"; + vBoxDiv.style.height = iH + "px"; + vBoxDiv.onmousedown = function(event) { + CLODOP.PreviewBox.initializedrag(event, this); + }; + vBoxDiv.onmouseup = function() { + CLODOP.PreviewBox.stopdrag(); + }; + vBoxDiv.onmousemove = function(event) { + CLODOP.PreviewBox.drag_drop(event, this); + }; + this.PopDiv = vBoxDiv; + var titleDiv = document.createElement("div"); + vBoxDiv.appendChild(titleDiv); + titleDiv.style.cssText = + "position:absolute;left:0px;width:100%;font: bold 14px Arial;line-height:27px;height:27px;text-indent:26px;color: white;background:#8BACCF"; + titleDiv.innerHTML = "打印预览"; + var icoButton = document.createElement("button"); + titleDiv.appendChild(icoButton); + icoButton.style.cssText = "background:transparent url(" + CLODOP.strHostURI + + "/c_favicon.ico) no-repeat scroll 0 0px;margin-left:5px;position:absolute;height:20px;line-height:100px;width:34px;left:3px;border:0;top:5px"; + var CloseButton = document.createElement("button"); + titleDiv.appendChild(CloseButton); + CloseButton.style.cssText = "background:transparent url(" + CLODOP.strHostURI + + "/images/c_winclose.png) no-repeat scroll 0 0px;margin-right:5px;position:absolute;height:20px;line-height:100px;width:34px;right:3px;border:0;top:4px"; + CloseButton.onclick = function() { + CLODOP.PreviewBox.closeit(this); + }; + var areaDiv = document.createElement("div"); + vBoxDiv.appendChild(areaDiv); + areaDiv.style.cssText = "background:#F5F5F5;color:#000;border:0px;left:0px;top:0px;"; + areaDiv.style.width = iW + "px"; + areaDiv.style.height = (iH - 0) + "px"; + this.ContentFrame = document.createElement("iframe"); + areaDiv.appendChild(this.ContentFrame); + this.ContentFrame.style.cssText = "width:100%;height:100%;"; + this.ContentFrame.src = strURL; + this.ContentFrame.frameBorder = "no"; + this.FrantDiv = document.createElement("div"); + obody.appendChild(this.FrantDiv); + this.FrantDiv.style.cssText = + "border:0px;left:0px;top:0px;filter: alpha(opacity=20); position: fixed; opacity: 0.2; -moz-opacity: 0.2; _position: absolute;z-index:91009; over-flow: hidden;"; + if (CLODOP.Browser.IE && (document.compatMode == "BackCompat" || navigator.userAgent.indexOf("MSIE 6.0") > 0)) { + this.FrantDiv.style.width = obody.scrollWidth + "px"; + this.FrantDiv.style.height = obody.scrollHeight + "px"; + } else { + this.FrantDiv.style.width = "100%"; + this.FrantDiv.style.height = "100%"; + } + } + } + }; + if (win.CLODOP2015_7028 && win.CLODOP2015_7028.Priority && win.CLODOP2015_7028.Priority > CLODOP.Priority) { + CLODOP = win.CLODOP2015_7028; + win.CLODOP_OK_Priority = win.CLODOP2015_7028.Priority; + return; + } + win.LODOP = CLODOP; + win.CLODOP = CLODOP; + win.CLODOP2015_7028 = CLODOP; + win.CLODOP_OK_Priority = CLODOP.Priority; + + // #ifndef APP-PLUS + win.CLODOP.DoInit(); + // #endif + + if (navigator.userAgent.indexOf("Lodop") < 0) win.CLODOP.OpenWebSocket(); +})(window); + +function getCLodop() { + return window.CLODOP2015_7028; +} + +async function getPrinterList(ip){ + if (!ip) { + ip = uni.getStorageSync('fl_ip'); + } + try{ + const res = await uni.request({ + url: `http://${ip}:8000/CLodopfuncs.js`, + }); + if (res[0]) { + return []; + } + let temp = res[1].data.match(/"list":(.+)/); + const printerListString = temp[1].substr(0,temp[1].length-2); + let printerListArray = JSON.parse(printerListString); + let printerList = []; + printerListArray.forEach(item=>{ + printerList.push(item.name) + }) + return printerList; + }catch(e){ + console.log(e); + } +} +export { + getCLodop, + getPrinterList +}; //导出getLodop diff --git a/utils/api.js b/utils/api.js new file mode 100644 index 0000000..bcc7a47 --- /dev/null +++ b/utils/api.js @@ -0,0 +1,16 @@ +import request from './request.js' +// 登录 +export const handLogin = (user, password) => request({ + url:'mobile/auth/login', + data: { + username: user, + password: password + } +}) + +// 测试状态码报错接口 +export const handRequest = () => request({ + url:'getInfo/4', + data: {} +}) + diff --git a/utils/getData1.js b/utils/getData1.js new file mode 100644 index 0000000..b8e2f24 --- /dev/null +++ b/utils/getData1.js @@ -0,0 +1 @@ +import request from './request.js' diff --git a/utils/getData2.js b/utils/getData2.js new file mode 100644 index 0000000..4d08a6c --- /dev/null +++ b/utils/getData2.js @@ -0,0 +1,108 @@ +import request from './request.js' +import request1 from './request1.js' + +// 版本更新测试 +export const pdaUpdate = () => request({ + url:'api/pda/update' +}) +// export const pdaUpdate = () => { +// let res = { +// versionName: '1.0.1', +// url: 'https://mp-e979e0eb-882b-42b3-a4a1-923ad08ea194.cdn.bspapp.com/cloudstorage/f72ec59f-7b25-487d-a034-fead1b6654c6.apk' +// } +// return res +// } + +// 登录 +export const handLogin = (user, password) => request({ + url:'mobile/auth/login', + data: { + username: user, + password: password + } +}) +// export const handLogin = (user, password) => { +// let res = { +// "user": { +// "user": { +// "user_id": "1", +// "username": "admin", +// "person_name": "管理员", +// "gender": "男", +// "phone": "18312365896", +// "email": "201507802@qq.com", +// "avatar_name": "avatar-20200806032259161.png", +// "avatar_path": "/Users/jie/Documents/work/me/admin/eladmin/~/avatar/avatar-20200806032259161.png", +// "password": "f52020dca765fd3943ed40a615dc2c5c", +// "is_admin": true, +// "is_used": true, +// "pwd_reset_user_id": 0, +// "pwd_reset_time": null, +// "create_id": null, +// "create_name": "", +// "create_time": "2022-12-01 00:00:00", +// "update_id": "1", +// "update_name": "admin", +// "update_time": "2023-05-06 14:00:14", +// "extperson_id": null, +// "extuser_id": null +// } +// }, +// "token": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiIxIiwicm5TdHIiOiIyZENCQk1uYW03ellTb21aVVN2ZzZnMndJOHJ0V0RmciIsImxvZ2luSW5mbyI6eyJpZCI6IjEiLCJ1c2VybmFtZSI6ImFkbWluIiwicHJlc29uTmFtZSI6IueuoeeQhuWRmCIsInVzZXIiOnsidXNlcl9pZCI6IjEiLCJ1c2VybmFtZSI6ImFkbWluIiwicGVyc29uX25hbWUiOiLnrqHnkIblkZgiLCJnZW5kZXIiOiLnlLciLCJwaG9uZSI6IjE4MzEyMzY1ODk2IiwiZW1haWwiOiIyMDE1MDc4MDJAcXEuY29tIiwiYXZhdGFyX25hbWUiOiJhdmF0YXItMjAyMDA4MDYwMzIyNTkxNjEucG5nIiwiYXZhdGFyX3BhdGgiOiIvVXNlcnMvamllL0RvY3VtZW50cy93b3JrL21lL2FkbWluL2VsYWRtaW4vfi9hdmF0YXIvYXZhdGFyLTIwMjAwODA2MDMyMjU5MTYxLnBuZyIsInBhc3N3b3JkIjoiZjUyMDIwZGNhNzY1ZmQzOTQzZWQ0MGE2MTVkYzJjNWMiLCJpc19hZG1pbiI6dHJ1ZSwiaXNfdXNlZCI6dHJ1ZSwicHdkX3Jlc2V0X3VzZXJfaWQiOjAsImNyZWF0ZV9uYW1lIjoiIiwiY3JlYXRlX3RpbWUiOjE2Njk4MjQwMDAsInVwZGF0ZV9pZCI6IjEiLCJ1cGRhdGVfbmFtZSI6ImFkbWluIiwidXBkYXRlX3RpbWUiOjE2ODMzNTI4MTR9LCJwZXJtaXNzaW9ucyI6WyJhZG1pbiIsIm1vbml0b3I6bGlzdCIsInRpbWluZzpkZWwiLCJ0aW1pbmc6ZWRpdCIsInRpbWluZzphZGQiLCJkaWN0OmRlbCIsImRpY3Q6ZWRpdCIsImRpY3Q6YWRkIiwiZGVwdDpkZWwiLCJkZXB0OmVkaXQiLCJkZXB0OmFkZCIsIm1lbnU6ZGVsIiwibWVudTplZGl0IiwibWVudTphZGQiLCJyb2xlczpkZWwiLCJtZW51Omxpc3QiLCJyb2xlczplZGl0Iiwicm9sZXM6YWRkIiwidXNlcjpkZWwiLCJ1c2VyOmVkaXQiLCJ1c2VyOmFkZCIsInN0b3JhZ2U6ZGVsIiwic3RvcmFnZTplZGl0Iiwic3RvcmFnZTphZGQiLCJzdG9yYWdlOmxpc3QiLCJkaWN0Omxpc3QiLCJkZXB0Omxpc3QiLCJyb2xlczpsaXN0IiwidGltaW5nOmxpc3QiLCJ1c2VyOmxpc3QiLCI5OTkiLCJnZW5Db2RlOmVkaXQiLCJnZW5Db2RlOmRlbCIsImdlbkNvZGU6YWRkIiwiZ2VuQ29kZTpsaXN0Il19fQ.cur9GPyns_MCRCw9vwNogGiCAOxzSd_9-KKythjc9dU" +// } +// return res +// } + +// 测试状态码报错接口 +export const handRequest = () => request({ + url:'getInfo/4', + data: {} +}) + +// 菜单 +export const authority = () => { + let res = { + sonTree: [ + {menu_id: '1', icon: 'RF08', name: '入库搬运', path: '', sonTree: [ + {menu_id: '1', name: '生箔生产进度', path: '/pages/ProductManage/SboProdProgress'} + ]}, + {menu_id: '2', icon: 'RF02', name: '叫料出库', path: '', sonTree: []}, + {menu_id: '3', icon: 'RF03', name: '任务管理', path: '', sonTree: []}, + {menu_id: '4', icon: 'RF07', name: '指令管理', path: '', sonTree: []}, + {menu_id: '5', icon: 'RF04', name: '设备点检', path: '/pages/modules/equip-inspection', sonTree: []}, + {menu_id: '6', icon: 'RF10', name: '设备操作', path: '', sonTree: []} + ] + } + return res +} + +/** + * 设备点检 + */ +// 获取设备下拉框 +export const deviceInfo = () => request({ + url:'api/pda/deviceCheck/deviceInfo', + data: {} +}) +// 获取设备状态下拉框 +export const deviceStatus = () => request({ + url:'api/pda/deviceCheck/deviceStatus', + data: {} +}) +// 设备点检 +export const deviceCheckVerify = (code, user, remark, status) => request({ + url:'api/pda/deviceCheck/verify', + data: { + device_code: code, + username: user, + remark: remark, + check_status: status + } +}) + + +// 1.3打印机类型 +export const virtualprintType = (url) => request1({ + url: `${url}/` + 'api/pda/virtual/printType', + data: {} +}) diff --git a/utils/jsencrypt.js b/utils/jsencrypt.js new file mode 100644 index 0000000..29008d4 --- /dev/null +++ b/utils/jsencrypt.js @@ -0,0 +1,12 @@ +import JSEncrypt from '../node_modules/jsencrypt/bin/jsencrypt.js' +let publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n' + + '2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ=='; +function RSAencrypt(pas){ + //实例化jsEncrypt对象 + let jse = new JSEncrypt(); + //设置公钥 + jse.setPublicKey(publicKey); + return jse.encrypt(pas); +} + +export {RSAencrypt} \ No newline at end of file diff --git a/utils/jsencrypt2.js b/utils/jsencrypt2.js new file mode 100644 index 0000000..1f14d0d --- /dev/null +++ b/utils/jsencrypt2.js @@ -0,0 +1,5373 @@ +/** + * 复制下面代码到node_modules/jsencrypt/bin/jsencrypt.js文件中兼容app + */ +(function(global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.JSEncrypt = {}))); +}(this, (function(exports) { + 'use strict'; + var navigator2 = { + appName: 'Netscape', + userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1' + }; + // 用来替换window2 + var window2 = { + ASN1: null, + Base64: null, + Hex: null, + crypto: null, + href: null + }; + var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"; + + function int2char(n) { + return BI_RM.charAt(n); + } + //#region BIT_OPERATIONS + // (public) this & a + function op_and(x, y) { + return x & y; + } + // (public) this | a + function op_or(x, y) { + return x | y; + } + // (public) this ^ a + function op_xor(x, y) { + return x ^ y; + } + // (public) this & ~a + function op_andnot(x, y) { + return x & ~y; + } + // return index of lowest 1-bit in x, x < 2^31 + function lbit(x) { + if (x == 0) { + return -1; + } + var r = 0; + if ((x & 0xffff) == 0) { + x >>= 16; + r += 16; + } + if ((x & 0xff) == 0) { + x >>= 8; + r += 8; + } + if ((x & 0xf) == 0) { + x >>= 4; + r += 4; + } + if ((x & 3) == 0) { + x >>= 2; + r += 2; + } + if ((x & 1) == 0) { + ++r; + } + return r; + } + // return number of 1 bits in x + function cbit(x) { + var r = 0; + while (x != 0) { + x &= x - 1; + ++r; + } + return r; + } + //#endregion BIT_OPERATIONS + + var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var b64pad = "="; + + function hex2b64(h) { + var i; + var c; + var ret = ""; + for (i = 0; i + 3 <= h.length; i += 3) { + c = parseInt(h.substring(i, i + 3), 16); + ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63); + } + if (i + 1 == h.length) { + c = parseInt(h.substring(i, i + 1), 16); + ret += b64map.charAt(c << 2); + } else if (i + 2 == h.length) { + c = parseInt(h.substring(i, i + 2), 16); + ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4); + } + while ((ret.length & 3) > 0) { + ret += b64pad; + } + return ret; + } + // convert a base64 string to hex + function b64tohex(s) { + var ret = ""; + var i; + var k = 0; // b64 state, 0-3 + var slop = 0; + for (i = 0; i < s.length; ++i) { + if (s.charAt(i) == b64pad) { + break; + } + var v = b64map.indexOf(s.charAt(i)); + if (v < 0) { + continue; + } + if (k == 0) { + ret += int2char(v >> 2); + slop = v & 3; + k = 1; + } else if (k == 1) { + ret += int2char((slop << 2) | (v >> 4)); + slop = v & 0xf; + k = 2; + } else if (k == 2) { + ret += int2char(slop); + ret += int2char(v >> 2); + slop = v & 3; + k = 3; + } else { + ret += int2char((slop << 2) | (v >> 4)); + ret += int2char(v & 0xf); + k = 0; + } + } + if (k == 1) { + ret += int2char(slop << 2); + } + return ret; + } + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. All rights reserved. + Licensed under the Apache License, Version 2.0 (the "License"); you may not use + this file except in compliance with the License. You may obtain a copy of the + License at http://www.apache.org/licenses/LICENSE-2.0 + + THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED + WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, + MERCHANTABLITY OR NON-INFRINGEMENT. + + See the Apache Version 2.0 License for specific language governing permissions + and limitations under the License. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ + __proto__: [] + } + instanceof Array && function(d, b) { + d.__proto__ = b; + }) || + function(d, b) { + for (var p in b) + if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + extendStatics(d, b); + + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + // Hex JavaScript decoder + // Copyright (c) 2008-2013 Lapo Luchini + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ + var decoder; + var Hex = { + decode: function(a) { + var i; + if (decoder === undefined) { + var hex = "0123456789ABCDEF"; + var ignore = " \f\n\r\t\u00A0\u2028\u2029"; + decoder = {}; + for (i = 0; i < 16; ++i) { + decoder[hex.charAt(i)] = i; + } + hex = hex.toLowerCase(); + for (i = 10; i < 16; ++i) { + decoder[hex.charAt(i)] = i; + } + for (i = 0; i < ignore.length; ++i) { + decoder[ignore.charAt(i)] = -1; + } + } + var out = []; + var bits = 0; + var char_count = 0; + for (i = 0; i < a.length; ++i) { + var c = a.charAt(i); + if (c == "=") { + break; + } + c = decoder[c]; + if (c == -1) { + continue; + } + if (c === undefined) { + throw new Error("Illegal character at offset " + i); + } + bits |= c; + if (++char_count >= 2) { + out[out.length] = bits; + bits = 0; + char_count = 0; + } else { + bits <<= 4; + } + } + if (char_count) { + throw new Error("Hex encoding incomplete: 4 bits missing"); + } + return out; + } + }; + + // Base64 JavaScript decoder + // Copyright (c) 2008-2013 Lapo Luchini + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ + var decoder$1; + var Base64 = { + decode: function(a) { + var i; + if (decoder$1 === undefined) { + var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var ignore = "= \f\n\r\t\u00A0\u2028\u2029"; + decoder$1 = Object.create(null); + for (i = 0; i < 64; ++i) { + decoder$1[b64.charAt(i)] = i; + } + for (i = 0; i < ignore.length; ++i) { + decoder$1[ignore.charAt(i)] = -1; + } + } + var out = []; + var bits = 0; + var char_count = 0; + for (i = 0; i < a.length; ++i) { + var c = a.charAt(i); + if (c == "=") { + break; + } + c = decoder$1[c]; + if (c == -1) { + continue; + } + if (c === undefined) { + throw new Error("Illegal character at offset " + i); + } + bits |= c; + if (++char_count >= 4) { + out[out.length] = (bits >> 16); + out[out.length] = (bits >> 8) & 0xFF; + out[out.length] = bits & 0xFF; + bits = 0; + char_count = 0; + } else { + bits <<= 6; + } + } + switch (char_count) { + case 1: + throw new Error("Base64 encoding incomplete: at least 2 bits missing"); + case 2: + out[out.length] = (bits >> 10); + break; + case 3: + out[out.length] = (bits >> 16); + out[out.length] = (bits >> 8) & 0xFF; + break; + } + return out; + }, + re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/, + unarmor: function(a) { + var m = Base64.re.exec(a); + if (m) { + if (m[1]) { + a = m[1]; + } else if (m[2]) { + a = m[2]; + } else { + throw new Error("RegExp out of sync"); + } + } + return Base64.decode(a); + } + }; + + // Big integer base-10 printing library + // Copyright (c) 2014 Lapo Luchini + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ + var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256 + var Int10 = /** @class */ (function() { + function Int10(value) { + this.buf = [+value || 0]; + } + Int10.prototype.mulAdd = function(m, c) { + // assert(m <= 256) + var b = this.buf; + var l = b.length; + var i; + var t; + for (i = 0; i < l; ++i) { + t = b[i] * m + c; + if (t < max) { + c = 0; + } else { + c = 0 | (t / max); + t -= c * max; + } + b[i] = t; + } + if (c > 0) { + b[i] = c; + } + }; + Int10.prototype.sub = function(c) { + // assert(m <= 256) + var b = this.buf; + var l = b.length; + var i; + var t; + for (i = 0; i < l; ++i) { + t = b[i] - c; + if (t < 0) { + t += max; + c = 1; + } else { + c = 0; + } + b[i] = t; + } + while (b[b.length - 1] === 0) { + b.pop(); + } + }; + Int10.prototype.toString = function(base) { + if ((base || 10) != 10) { + throw new Error("only base 10 is supported"); + } + var b = this.buf; + var s = b[b.length - 1].toString(); + for (var i = b.length - 2; i >= 0; --i) { + s += (max + b[i]).toString().substring(1); + } + return s; + }; + Int10.prototype.valueOf = function() { + var b = this.buf; + var v = 0; + for (var i = b.length - 1; i >= 0; --i) { + v = v * max + b[i]; + } + return v; + }; + Int10.prototype.simplify = function() { + var b = this.buf; + return (b.length == 1) ? b[0] : this; + }; + return Int10; + }()); + + // ASN.1 JavaScript decoder + var ellipsis = "\u2026"; + var reTimeS = + /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; + var reTimeL = + /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; + + function stringCut(str, len) { + if (str.length > len) { + str = str.substring(0, len) + ellipsis; + } + return str; + } + var Stream = /** @class */ (function() { + function Stream(enc, pos) { + this.hexDigits = "0123456789ABCDEF"; + if (enc instanceof Stream) { + this.enc = enc.enc; + this.pos = enc.pos; + } else { + // enc should be an array or a binary string + this.enc = enc; + this.pos = pos; + } + } + Stream.prototype.get = function(pos) { + if (pos === undefined) { + pos = this.pos++; + } + if (pos >= this.enc.length) { + throw new Error("Requesting byte offset " + pos + " on a stream of length " + + this.enc.length); + } + return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos]; + }; + Stream.prototype.hexByte = function(b) { + return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF); + }; + Stream.prototype.hexDump = function(start, end, raw) { + var s = ""; + for (var i = start; i < end; ++i) { + s += this.hexByte(this.get(i)); + if (raw !== true) { + switch (i & 0xF) { + case 0x7: + s += " "; + break; + case 0xF: + s += "\n"; + break; + default: + s += " "; + } + } + } + return s; + }; + Stream.prototype.isASCII = function(start, end) { + for (var i = start; i < end; ++i) { + var c = this.get(i); + if (c < 32 || c > 176) { + return false; + } + } + return true; + }; + Stream.prototype.parseStringISO = function(start, end) { + var s = ""; + for (var i = start; i < end; ++i) { + s += String.fromCharCode(this.get(i)); + } + return s; + }; + Stream.prototype.parseStringUTF = function(start, end) { + var s = ""; + for (var i = start; i < end;) { + var c = this.get(i++); + if (c < 128) { + s += String.fromCharCode(c); + } else if ((c > 191) && (c < 224)) { + s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F)); + } else { + s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << + 6) | (this.get(i++) & 0x3F)); + } + } + return s; + }; + Stream.prototype.parseStringBMP = function(start, end) { + var str = ""; + var hi; + var lo; + for (var i = start; i < end;) { + hi = this.get(i++); + lo = this.get(i++); + str += String.fromCharCode((hi << 8) | lo); + } + return str; + }; + Stream.prototype.parseTime = function(start, end, shortYear) { + var s = this.parseStringISO(start, end); + var m = (shortYear ? reTimeS : reTimeL).exec(s); + if (!m) { + return "Unrecognized time: " + s; + } + if (shortYear) { + // to avoid querying the timer, use the fixed range [1970, 2069] + // it will conform with ITU X.400 [-10, +40] sliding window2 until 2030 + m[1] = +m[1]; + m[1] += (+m[1] < 70) ? 2000 : 1900; + } + s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4]; + if (m[5]) { + s += ":" + m[5]; + if (m[6]) { + s += ":" + m[6]; + if (m[7]) { + s += "." + m[7]; + } + } + } + if (m[8]) { + s += " UTC"; + if (m[8] != "Z") { + s += m[8]; + if (m[9]) { + s += ":" + m[9]; + } + } + } + return s; + }; + Stream.prototype.parseInteger = function(start, end) { + var v = this.get(start); + var neg = (v > 127); + var pad = neg ? 255 : 0; + var len; + var s = ""; + // skip unuseful bits (not allowed in DER) + while (v == pad && ++start < end) { + v = this.get(start); + } + len = end - start; + if (len === 0) { + return neg ? -1 : 0; + } + // show bit length of huge integers + if (len > 4) { + s = v; + len <<= 3; + while (((+s ^ pad) & 0x80) == 0) { + s = +s << 1; + --len; + } + s = "(" + len + " bit)\n"; + } + // decode the integer + if (neg) { + v = v - 256; + } + var n = new Int10(v); + for (var i = start + 1; i < end; ++i) { + n.mulAdd(256, this.get(i)); + } + return s + n.toString(); + }; + Stream.prototype.parseBitString = function(start, end, maxLength) { + var unusedBit = this.get(start); + var lenBit = ((end - start - 1) << 3) - unusedBit; + var intro = "(" + lenBit + " bit)\n"; + var s = ""; + for (var i = start + 1; i < end; ++i) { + var b = this.get(i); + var skip = (i == end - 1) ? unusedBit : 0; + for (var j = 7; j >= skip; --j) { + s += (b >> j) & 1 ? "1" : "0"; + } + if (s.length > maxLength) { + return intro + stringCut(s, maxLength); + } + } + return intro + s; + }; + Stream.prototype.parseOctetString = function(start, end, maxLength) { + if (this.isASCII(start, end)) { + return stringCut(this.parseStringISO(start, end), maxLength); + } + var len = end - start; + var s = "(" + len + " byte)\n"; + maxLength /= 2; // we work in bytes + if (len > maxLength) { + end = start + maxLength; + } + for (var i = start; i < end; ++i) { + s += this.hexByte(this.get(i)); + } + if (len > maxLength) { + s += ellipsis; + } + return s; + }; + Stream.prototype.parseOID = function(start, end, maxLength) { + var s = ""; + var n = new Int10(); + var bits = 0; + for (var i = start; i < end; ++i) { + var v = this.get(i); + n.mulAdd(128, v & 0x7F); + bits += 7; + if (!(v & 0x80)) { // finished + if (s === "") { + n = n.simplify(); + if (n instanceof Int10) { + n.sub(80); + s = "2." + n.toString(); + } else { + var m = n < 80 ? n < 40 ? 0 : 1 : 2; + s = m + "." + (n - m * 40); + } + } else { + s += "." + n.toString(); + } + if (s.length > maxLength) { + return stringCut(s, maxLength); + } + n = new Int10(); + bits = 0; + } + } + if (bits > 0) { + s += ".incomplete"; + } + return s; + }; + return Stream; + }()); + var ASN1 = /** @class */ (function() { + function ASN1(stream, header, length, tag, sub) { + if (!(tag instanceof ASN1Tag)) { + throw new Error("Invalid tag value."); + } + this.stream = stream; + this.header = header; + this.length = length; + this.tag = tag; + this.sub = sub; + } + ASN1.prototype.typeName = function() { + switch (this.tag.tagClass) { + case 0: // universal + switch (this.tag.tagNumber) { + case 0x00: + return "EOC"; + case 0x01: + return "BOOLEAN"; + case 0x02: + return "INTEGER"; + case 0x03: + return "BIT_STRING"; + case 0x04: + return "OCTET_STRING"; + case 0x05: + return "NULL"; + case 0x06: + return "OBJECT_IDENTIFIER"; + case 0x07: + return "ObjectDescriptor"; + case 0x08: + return "EXTERNAL"; + case 0x09: + return "REAL"; + case 0x0A: + return "ENUMERATED"; + case 0x0B: + return "EMBEDDED_PDV"; + case 0x0C: + return "UTF8String"; + case 0x10: + return "SEQUENCE"; + case 0x11: + return "SET"; + case 0x12: + return "NumericString"; + case 0x13: + return "PrintableString"; // ASCII subset + case 0x14: + return "TeletexString"; // aka T61String + case 0x15: + return "VideotexString"; + case 0x16: + return "IA5String"; // ASCII + case 0x17: + return "UTCTime"; + case 0x18: + return "GeneralizedTime"; + case 0x19: + return "GraphicString"; + case 0x1A: + return "VisibleString"; // ASCII subset + case 0x1B: + return "GeneralString"; + case 0x1C: + return "UniversalString"; + case 0x1E: + return "BMPString"; + } + return "Universal_" + this.tag.tagNumber.toString(); + case 1: + return "Application_" + this.tag.tagNumber.toString(); + case 2: + return "[" + this.tag.tagNumber.toString() + "]"; // Context + case 3: + return "Private_" + this.tag.tagNumber.toString(); + } + }; + ASN1.prototype.content = function(maxLength) { + if (this.tag === undefined) { + return null; + } + if (maxLength === undefined) { + maxLength = Infinity; + } + var content = this.posContent(); + var len = Math.abs(this.length); + if (!this.tag.isUniversal()) { + if (this.sub !== null) { + return "(" + this.sub.length + " elem)"; + } + return this.stream.parseOctetString(content, content + len, maxLength); + } + switch (this.tag.tagNumber) { + case 0x01: // BOOLEAN + return (this.stream.get(content) === 0) ? "false" : "true"; + case 0x02: // INTEGER + return this.stream.parseInteger(content, content + len); + case 0x03: // BIT_STRING + return this.sub ? "(" + this.sub.length + " elem)" : + this.stream.parseBitString(content, content + len, maxLength); + case 0x04: // OCTET_STRING + return this.sub ? "(" + this.sub.length + " elem)" : + this.stream.parseOctetString(content, content + len, maxLength); + // case 0x05: // NULL + case 0x06: // OBJECT_IDENTIFIER + return this.stream.parseOID(content, content + len, maxLength); + // case 0x07: // ObjectDescriptor + // case 0x08: // EXTERNAL + // case 0x09: // REAL + // case 0x0A: // ENUMERATED + // case 0x0B: // EMBEDDED_PDV + case 0x10: // SEQUENCE + case 0x11: // SET + if (this.sub !== null) { + return "(" + this.sub.length + " elem)"; + } else { + return "(no elem)"; + } + case 0x0C: // UTF8String + return stringCut(this.stream.parseStringUTF(content, content + len), + maxLength); + case 0x12: // NumericString + case 0x13: // PrintableString + case 0x14: // TeletexString + case 0x15: // VideotexString + case 0x16: // IA5String + // case 0x19: // GraphicString + case 0x1A: // VisibleString + // case 0x1B: // GeneralString + // case 0x1C: // UniversalString + return stringCut(this.stream.parseStringISO(content, content + len), + maxLength); + case 0x1E: // BMPString + return stringCut(this.stream.parseStringBMP(content, content + len), + maxLength); + case 0x17: // UTCTime + case 0x18: // GeneralizedTime + return this.stream.parseTime(content, content + len, (this.tag + .tagNumber == 0x17)); + } + return null; + }; + ASN1.prototype.toString = function() { + return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub + .length) + "]"; + }; + ASN1.prototype.toPrettyString = function(indent) { + if (indent === undefined) { + indent = ""; + } + var s = indent + this.typeName() + " @" + this.stream.pos; + if (this.length >= 0) { + s += "+"; + } + s += this.length; + if (this.tag.tagConstructed) { + s += " (constructed)"; + } else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag + .tagNumber == 0x04))) && (this.sub !== null)) { + s += " (encapsulates)"; + } + s += "\n"; + if (this.sub !== null) { + indent += " "; + for (var i = 0, max = this.sub.length; i < max; ++i) { + s += this.sub[i].toPrettyString(indent); + } + } + return s; + }; + ASN1.prototype.posStart = function() { + return this.stream.pos; + }; + ASN1.prototype.posContent = function() { + return this.stream.pos + this.header; + }; + ASN1.prototype.posEnd = function() { + return this.stream.pos + this.header + Math.abs(this.length); + }; + ASN1.prototype.toHexString = function() { + return this.stream.hexDump(this.posStart(), this.posEnd(), true); + }; + ASN1.decodeLength = function(stream) { + var buf = stream.get(); + var len = buf & 0x7F; + if (len == buf) { + return len; + } + // no reason to use Int10, as it would be a huge buffer anyways + if (len > 6) { + throw new Error("Length over 48 bits not supported at position " + (stream.pos - + 1)); + } + if (len === 0) { + return null; + } // undefined + buf = 0; + for (var i = 0; i < len; ++i) { + buf = (buf * 256) + stream.get(); + } + return buf; + }; + /** + * Retrieve the hexadecimal value (as a string) of the current ASN.1 element + * @returns {string} + * @public + */ + ASN1.prototype.getHexStringValue = function() { + var hexString = this.toHexString(); + var offset = this.header * 2; + var length = this.length * 2; + return hexString.substr(offset, length); + }; + ASN1.decode = function(str) { + var stream; + if (!(str instanceof Stream)) { + stream = new Stream(str, 0); + } else { + stream = str; + } + var streamStart = new Stream(stream); + var tag = new ASN1Tag(stream); + var len = ASN1.decodeLength(stream); + var start = stream.pos; + var header = start - streamStart.pos; + var sub = null; + var getSub = function() { + var ret = []; + if (len !== null) { + // definite length + var end = start + len; + while (stream.pos < end) { + ret[ret.length] = ASN1.decode(stream); + } + if (stream.pos != end) { + throw new Error( + "Content size is not correct for container starting at offset " + + start); + } + } else { + // undefined length + try { + for (;;) { + var s = ASN1.decode(stream); + if (s.tag.isEOC()) { + break; + } + ret[ret.length] = s; + } + len = start - stream + .pos; // undefined lengths are represented as negative values + } catch (e) { + throw new Error( + "Exception while decoding undefined length content: " + e); + } + } + return ret; + }; + if (tag.tagConstructed) { + // must have valid content + sub = getSub(); + } else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == + 0x04))) { + // sometimes BitString and OctetString are used to encapsulate ASN.1 + try { + if (tag.tagNumber == 0x03) { + if (stream.get() != 0) { + throw new Error("BIT STRINGs with unused bits cannot encapsulate."); + } + } + sub = getSub(); + for (var i = 0; i < sub.length; ++i) { + if (sub[i].tag.isEOC()) { + throw new Error("EOC is not supposed to be actual content."); + } + } + } catch (e) { + // but silently ignore when they don't + sub = null; + } + } + if (sub === null) { + if (len === null) { + throw new Error( + "We can't skip over an invalid tag with undefined length at offset " + + start); + } + stream.pos = start + Math.abs(len); + } + return new ASN1(streamStart, header, len, tag, sub); + }; + return ASN1; + }()); + var ASN1Tag = /** @class */ (function() { + function ASN1Tag(stream) { + var buf = stream.get(); + this.tagClass = buf >> 6; + this.tagConstructed = ((buf & 0x20) !== 0); + this.tagNumber = buf & 0x1F; + if (this.tagNumber == 0x1F) { // long tag + var n = new Int10(); + do { + buf = stream.get(); + n.mulAdd(128, buf & 0x7F); + } while (buf & 0x80); + this.tagNumber = n.simplify(); + } + } + ASN1Tag.prototype.isUniversal = function() { + return this.tagClass === 0x00; + }; + ASN1Tag.prototype.isEOC = function() { + return this.tagClass === 0x00 && this.tagNumber === 0x00; + }; + return ASN1Tag; + }()); + + // Copyright (c) 2005 Tom Wu + // Bits per digit + var dbits; + // JavaScript engine analysis + var canary = 0xdeadbeefcafe; + var j_lm = ((canary & 0xffffff) == 0xefcafe); + //#region + var lowprimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, + 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, + 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, + 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, + 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, + 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, + 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, + 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, + 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 + ]; + var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]; + //#endregion + // (public) Constructor + var BigInteger = /** @class */ (function() { + function BigInteger(a, b, c) { + if (a != null) { + if ("number" == typeof a) { + this.fromNumber(a, b, c); + } else if (b == null && "string" != typeof a) { + this.fromString(a, 256); + } else { + this.fromString(a, b); + } + } + } + //#region PUBLIC + // BigInteger.prototype.toString = bnToString; + // (public) return string representation in given radix + BigInteger.prototype.toString = function(b) { + if (this.s < 0) { + return "-" + this.negate().toString(b); + } + var k; + if (b == 16) { + k = 4; + } else if (b == 8) { + k = 3; + } else if (b == 2) { + k = 1; + } else if (b == 32) { + k = 5; + } else if (b == 4) { + k = 2; + } else { + return this.toRadix(b); + } + var km = (1 << k) - 1; + var d; + var m = false; + var r = ""; + var i = this.t; + var p = this.DB - (i * this.DB) % k; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) > 0) { + m = true; + r = int2char(d); + } + while (i >= 0) { + if (p < k) { + d = (this[i] & ((1 << p) - 1)) << (k - p); + d |= this[--i] >> (p += this.DB - k); + } else { + d = (this[i] >> (p -= k)) & km; + if (p <= 0) { + p += this.DB; + --i; + } + } + if (d > 0) { + m = true; + } + if (m) { + r += int2char(d); + } + } + } + return m ? r : "0"; + }; + // BigInteger.prototype.negate = bnNegate; + // (public) -this + BigInteger.prototype.negate = function() { + var r = nbi(); + BigInteger.ZERO.subTo(this, r); + return r; + }; + // BigInteger.prototype.abs = bnAbs; + // (public) |this| + BigInteger.prototype.abs = function() { + return (this.s < 0) ? this.negate() : this; + }; + // BigInteger.prototype.compareTo = bnCompareTo; + // (public) return + if this > a, - if this < a, 0 if equal + BigInteger.prototype.compareTo = function(a) { + var r = this.s - a.s; + if (r != 0) { + return r; + } + var i = this.t; + r = i - a.t; + if (r != 0) { + return (this.s < 0) ? -r : r; + } + while (--i >= 0) { + if ((r = this[i] - a[i]) != 0) { + return r; + } + } + return 0; + }; + // BigInteger.prototype.bitLength = bnBitLength; + // (public) return the number of bits in "this" + BigInteger.prototype.bitLength = function() { + if (this.t <= 0) { + return 0; + } + return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)); + }; + // BigInteger.prototype.mod = bnMod; + // (public) this mod a + BigInteger.prototype.mod = function(a) { + var r = nbi(); + this.abs().divRemTo(a, null, r); + if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { + a.subTo(r, r); + } + return r; + }; + // BigInteger.prototype.modPowInt = bnModPowInt; + // (public) this^e % m, 0 <= e < 2^32 + BigInteger.prototype.modPowInt = function(e, m) { + var z; + if (e < 256 || m.isEven()) { + z = new Classic(m); + } else { + z = new Montgomery(m); + } + return this.exp(e, z); + }; + // BigInteger.prototype.clone = bnClone; + // (public) + BigInteger.prototype.clone = function() { + var r = nbi(); + this.copyTo(r); + return r; + }; + // BigInteger.prototype.intValue = bnIntValue; + // (public) return value as integer + BigInteger.prototype.intValue = function() { + if (this.s < 0) { + if (this.t == 1) { + return this[0] - this.DV; + } else if (this.t == 0) { + return -1; + } + } else if (this.t == 1) { + return this[0]; + } else if (this.t == 0) { + return 0; + } + // assumes 16 < DB < 32 + return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]; + }; + // BigInteger.prototype.byteValue = bnByteValue; + // (public) return value as byte + BigInteger.prototype.byteValue = function() { + return (this.t == 0) ? this.s : (this[0] << 24) >> 24; + }; + // BigInteger.prototype.shortValue = bnShortValue; + // (public) return value as short (assumes DB>=16) + BigInteger.prototype.shortValue = function() { + return (this.t == 0) ? this.s : (this[0] << 16) >> 16; + }; + // BigInteger.prototype.signum = bnSigNum; + // (public) 0 if this == 0, 1 if this > 0 + BigInteger.prototype.signum = function() { + if (this.s < 0) { + return -1; + } else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) { + return 0; + } else { + return 1; + } + }; + // BigInteger.prototype.toByteArray = bnToByteArray; + // (public) convert to bigendian byte array + BigInteger.prototype.toByteArray = function() { + var i = this.t; + var r = []; + r[0] = this.s; + var p = this.DB - (i * this.DB) % 8; + var d; + var k = 0; + if (i-- > 0) { + if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) { + r[k++] = d | (this.s << (this.DB - p)); + } + while (i >= 0) { + if (p < 8) { + d = (this[i] & ((1 << p) - 1)) << (8 - p); + d |= this[--i] >> (p += this.DB - 8); + } else { + d = (this[i] >> (p -= 8)) & 0xff; + if (p <= 0) { + p += this.DB; + --i; + } + } + if ((d & 0x80) != 0) { + d |= -256; + } + if (k == 0 && (this.s & 0x80) != (d & 0x80)) { + ++k; + } + if (k > 0 || d != this.s) { + r[k++] = d; + } + } + } + return r; + }; + // BigInteger.prototype.equals = bnEquals; + BigInteger.prototype.equals = function(a) { + return (this.compareTo(a) == 0); + }; + // BigInteger.prototype.min = bnMin; + BigInteger.prototype.min = function(a) { + return (this.compareTo(a) < 0) ? this : a; + }; + // BigInteger.prototype.max = bnMax; + BigInteger.prototype.max = function(a) { + return (this.compareTo(a) > 0) ? this : a; + }; + // BigInteger.prototype.and = bnAnd; + BigInteger.prototype.and = function(a) { + var r = nbi(); + this.bitwiseTo(a, op_and, r); + return r; + }; + // BigInteger.prototype.or = bnOr; + BigInteger.prototype.or = function(a) { + var r = nbi(); + this.bitwiseTo(a, op_or, r); + return r; + }; + // BigInteger.prototype.xor = bnXor; + BigInteger.prototype.xor = function(a) { + var r = nbi(); + this.bitwiseTo(a, op_xor, r); + return r; + }; + // BigInteger.prototype.andNot = bnAndNot; + BigInteger.prototype.andNot = function(a) { + var r = nbi(); + this.bitwiseTo(a, op_andnot, r); + return r; + }; + // BigInteger.prototype.not = bnNot; + // (public) ~this + BigInteger.prototype.not = function() { + var r = nbi(); + for (var i = 0; i < this.t; ++i) { + r[i] = this.DM & ~this[i]; + } + r.t = this.t; + r.s = ~this.s; + return r; + }; + // BigInteger.prototype.shiftLeft = bnShiftLeft; + // (public) this << n + BigInteger.prototype.shiftLeft = function(n) { + var r = nbi(); + if (n < 0) { + this.rShiftTo(-n, r); + } else { + this.lShiftTo(n, r); + } + return r; + }; + // BigInteger.prototype.shiftRight = bnShiftRight; + // (public) this >> n + BigInteger.prototype.shiftRight = function(n) { + var r = nbi(); + if (n < 0) { + this.lShiftTo(-n, r); + } else { + this.rShiftTo(n, r); + } + return r; + }; + // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; + // (public) returns index of lowest 1-bit (or -1 if none) + BigInteger.prototype.getLowestSetBit = function() { + for (var i = 0; i < this.t; ++i) { + if (this[i] != 0) { + return i * this.DB + lbit(this[i]); + } + } + if (this.s < 0) { + return this.t * this.DB; + } + return -1; + }; + // BigInteger.prototype.bitCount = bnBitCount; + // (public) return number of set bits + BigInteger.prototype.bitCount = function() { + var r = 0; + var x = this.s & this.DM; + for (var i = 0; i < this.t; ++i) { + r += cbit(this[i] ^ x); + } + return r; + }; + // BigInteger.prototype.testBit = bnTestBit; + // (public) true iff nth bit is set + BigInteger.prototype.testBit = function(n) { + var j = Math.floor(n / this.DB); + if (j >= this.t) { + return (this.s != 0); + } + return ((this[j] & (1 << (n % this.DB))) != 0); + }; + // BigInteger.prototype.setBit = bnSetBit; + // (public) this | (1< 1) { + var g2 = nbi(); + z.sqrTo(g[1], g2); + while (n <= km) { + g[n] = nbi(); + z.mulTo(g2, g[n - 2], g[n]); + n += 2; + } + } + var j = e.t - 1; + var w; + var is1 = true; + var r2 = nbi(); + var t; + i = nbits(e[j]) - 1; + while (j >= 0) { + if (i >= k1) { + w = (e[j] >> (i - k1)) & km; + } else { + w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i); + if (j > 0) { + w |= e[j - 1] >> (this.DB + i - k1); + } + } + n = k; + while ((w & 1) == 0) { + w >>= 1; + --n; + } + if ((i -= n) < 0) { + i += this.DB; + --j; + } + if (is1) { // ret == 1, don't bother squaring or multiplying it + g[w].copyTo(r); + is1 = false; + } else { + while (n > 1) { + z.sqrTo(r, r2); + z.sqrTo(r2, r); + n -= 2; + } + if (n > 0) { + z.sqrTo(r, r2); + } else { + t = r; + r = r2; + r2 = t; + } + z.mulTo(r2, g[w], r); + } + while (j >= 0 && (e[j] & (1 << i)) == 0) { + z.sqrTo(r, r2); + t = r; + r = r2; + r2 = t; + if (--i < 0) { + i = this.DB - 1; + --j; + } + } + } + return z.revert(r); + }; + // BigInteger.prototype.modInverse = bnModInverse; + // (public) 1/this % m (HAC 14.61) + BigInteger.prototype.modInverse = function(m) { + var ac = m.isEven(); + if ((this.isEven() && ac) || m.signum() == 0) { + return BigInteger.ZERO; + } + var u = m.clone(); + var v = this.clone(); + var a = nbv(1); + var b = nbv(0); + var c = nbv(0); + var d = nbv(1); + while (u.signum() != 0) { + while (u.isEven()) { + u.rShiftTo(1, u); + if (ac) { + if (!a.isEven() || !b.isEven()) { + a.addTo(this, a); + b.subTo(m, b); + } + a.rShiftTo(1, a); + } else if (!b.isEven()) { + b.subTo(m, b); + } + b.rShiftTo(1, b); + } + while (v.isEven()) { + v.rShiftTo(1, v); + if (ac) { + if (!c.isEven() || !d.isEven()) { + c.addTo(this, c); + d.subTo(m, d); + } + c.rShiftTo(1, c); + } else if (!d.isEven()) { + d.subTo(m, d); + } + d.rShiftTo(1, d); + } + if (u.compareTo(v) >= 0) { + u.subTo(v, u); + if (ac) { + a.subTo(c, a); + } + b.subTo(d, b); + } else { + v.subTo(u, v); + if (ac) { + c.subTo(a, c); + } + d.subTo(b, d); + } + } + if (v.compareTo(BigInteger.ONE) != 0) { + return BigInteger.ZERO; + } + if (d.compareTo(m) >= 0) { + return d.subtract(m); + } + if (d.signum() < 0) { + d.addTo(m, d); + } else { + return d; + } + if (d.signum() < 0) { + return d.add(m); + } else { + return d; + } + }; + // BigInteger.prototype.pow = bnPow; + // (public) this^e + BigInteger.prototype.pow = function(e) { + return this.exp(e, new NullExp()); + }; + // BigInteger.prototype.gcd = bnGCD; + // (public) gcd(this,a) (HAC 14.54) + BigInteger.prototype.gcd = function(a) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(); + var g = y.getLowestSetBit(); + if (g < 0) { + return x; + } + if (i < g) { + g = i; + } + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + while (x.signum() > 0) { + if ((i = x.getLowestSetBit()) > 0) { + x.rShiftTo(i, x); + } + if ((i = y.getLowestSetBit()) > 0) { + y.rShiftTo(i, y); + } + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + } + if (g > 0) { + y.lShiftTo(g, y); + } + return y; + }; + // BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + // (public) test primality with certainty >= 1-.5^t + BigInteger.prototype.isProbablePrime = function(t) { + var i; + var x = this.abs(); + if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { + for (i = 0; i < lowprimes.length; ++i) { + if (x[0] == lowprimes[i]) { + return true; + } + } + return false; + } + if (x.isEven()) { + return false; + } + i = 1; + while (i < lowprimes.length) { + var m = lowprimes[i]; + var j = i + 1; + while (j < lowprimes.length && m < lplim) { + m *= lowprimes[j++]; + } + m = x.modInt(m); + while (i < j) { + if (m % lowprimes[i++] == 0) { + return false; + } + } + } + return x.millerRabin(t); + }; + //#endregion PUBLIC + //#region PROTECTED + // BigInteger.prototype.copyTo = bnpCopyTo; + // (protected) copy this to r + BigInteger.prototype.copyTo = function(r) { + for (var i = this.t - 1; i >= 0; --i) { + r[i] = this[i]; + } + r.t = this.t; + r.s = this.s; + }; + // BigInteger.prototype.fromInt = bnpFromInt; + // (protected) set from integer value x, -DV <= x < DV + BigInteger.prototype.fromInt = function(x) { + this.t = 1; + this.s = (x < 0) ? -1 : 0; + if (x > 0) { + this[0] = x; + } else if (x < -1) { + this[0] = x + this.DV; + } else { + this.t = 0; + } + }; + // BigInteger.prototype.fromString = bnpFromString; + // (protected) set from string and radix + BigInteger.prototype.fromString = function(s, b) { + var k; + if (b == 16) { + k = 4; + } else if (b == 8) { + k = 3; + } else if (b == 256) { + k = 8; + /* byte array */ + } else if (b == 2) { + k = 1; + } else if (b == 32) { + k = 5; + } else if (b == 4) { + k = 2; + } else { + this.fromRadix(s, b); + return; + } + this.t = 0; + this.s = 0; + var i = s.length; + var mi = false; + var sh = 0; + while (--i >= 0) { + var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-") { + mi = true; + } + continue; + } + mi = false; + if (sh == 0) { + this[this.t++] = x; + } else if (sh + k > this.DB) { + this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh; + this[this.t++] = (x >> (this.DB - sh)); + } else { + this[this.t - 1] |= x << sh; + } + sh += k; + if (sh >= this.DB) { + sh -= this.DB; + } + } + if (k == 8 && ((+s[0]) & 0x80) != 0) { + this.s = -1; + if (sh > 0) { + this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh; + } + } + this.clamp(); + if (mi) { + BigInteger.ZERO.subTo(this, this); + } + }; + // BigInteger.prototype.clamp = bnpClamp; + // (protected) clamp off excess high words + BigInteger.prototype.clamp = function() { + var c = this.s & this.DM; + while (this.t > 0 && this[this.t - 1] == c) { + --this.t; + } + }; + // BigInteger.prototype.dlShiftTo = bnpDLShiftTo; + // (protected) r = this << n*DB + BigInteger.prototype.dlShiftTo = function(n, r) { + var i; + for (i = this.t - 1; i >= 0; --i) { + r[i + n] = this[i]; + } + for (i = n - 1; i >= 0; --i) { + r[i] = 0; + } + r.t = this.t + n; + r.s = this.s; + }; + // BigInteger.prototype.drShiftTo = bnpDRShiftTo; + // (protected) r = this >> n*DB + BigInteger.prototype.drShiftTo = function(n, r) { + for (var i = n; i < this.t; ++i) { + r[i - n] = this[i]; + } + r.t = Math.max(this.t - n, 0); + r.s = this.s; + }; + // BigInteger.prototype.lShiftTo = bnpLShiftTo; + // (protected) r = this << n + BigInteger.prototype.lShiftTo = function(n, r) { + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << cbs) - 1; + var ds = Math.floor(n / this.DB); + var c = (this.s << bs) & this.DM; + for (var i = this.t - 1; i >= 0; --i) { + r[i + ds + 1] = (this[i] >> cbs) | c; + c = (this[i] & bm) << bs; + } + for (var i = ds - 1; i >= 0; --i) { + r[i] = 0; + } + r[ds] = c; + r.t = this.t + ds + 1; + r.s = this.s; + r.clamp(); + }; + // BigInteger.prototype.rShiftTo = bnpRShiftTo; + // (protected) r = this >> n + BigInteger.prototype.rShiftTo = function(n, r) { + r.s = this.s; + var ds = Math.floor(n / this.DB); + if (ds >= this.t) { + r.t = 0; + return; + } + var bs = n % this.DB; + var cbs = this.DB - bs; + var bm = (1 << bs) - 1; + r[0] = this[ds] >> bs; + for (var i = ds + 1; i < this.t; ++i) { + r[i - ds - 1] |= (this[i] & bm) << cbs; + r[i - ds] = this[i] >> bs; + } + if (bs > 0) { + r[this.t - ds - 1] |= (this.s & bm) << cbs; + } + r.t = this.t - ds; + r.clamp(); + }; + // BigInteger.prototype.subTo = bnpSubTo; + // (protected) r = this - a + BigInteger.prototype.subTo = function(a, r) { + var i = 0; + var c = 0; + var m = Math.min(a.t, this.t); + while (i < m) { + c += this[i] - a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + if (a.t < this.t) { + c -= a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c -= a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c < -1) { + r[i++] = this.DV + c; + } else if (c > 0) { + r[i++] = c; + } + r.t = i; + r.clamp(); + }; + // BigInteger.prototype.multiplyTo = bnpMultiplyTo; + // (protected) r = this * a, r != this,a (HAC 14.12) + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyTo = function(a, r) { + var x = this.abs(); + var y = a.abs(); + var i = x.t; + r.t = i + y.t; + while (--i >= 0) { + r[i] = 0; + } + for (i = 0; i < y.t; ++i) { + r[i + x.t] = x.am(0, y[i], r, i, 0, x.t); + } + r.s = 0; + r.clamp(); + if (this.s != a.s) { + BigInteger.ZERO.subTo(r, r); + } + }; + // BigInteger.prototype.squareTo = bnpSquareTo; + // (protected) r = this^2, r != this (HAC 14.16) + BigInteger.prototype.squareTo = function(r) { + var x = this.abs(); + var i = r.t = 2 * x.t; + while (--i >= 0) { + r[i] = 0; + } + for (i = 0; i < x.t - 1; ++i) { + var c = x.am(i, x[i], r, 2 * i, 0, 1); + if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x + .DV) { + r[i + x.t] -= x.DV; + r[i + x.t + 1] = 1; + } + } + if (r.t > 0) { + r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1); + } + r.s = 0; + r.clamp(); + }; + // BigInteger.prototype.divRemTo = bnpDivRemTo; + // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) + // r != q, this != m. q or r may be null. + BigInteger.prototype.divRemTo = function(m, q, r) { + var pm = m.abs(); + if (pm.t <= 0) { + return; + } + var pt = this.abs(); + if (pt.t < pm.t) { + if (q != null) { + q.fromInt(0); + } + if (r != null) { + this.copyTo(r); + } + return; + } + if (r == null) { + r = nbi(); + } + var y = nbi(); + var ts = this.s; + var ms = m.s; + var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus + if (nsh > 0) { + pm.lShiftTo(nsh, y); + pt.lShiftTo(nsh, r); + } else { + pm.copyTo(y); + pt.copyTo(r); + } + var ys = y.t; + var y0 = y[ys - 1]; + if (y0 == 0) { + return; + } + var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0); + var d1 = this.FV / yt; + var d2 = (1 << this.F1) / yt; + var e = 1 << this.F2; + var i = r.t; + var j = i - ys; + var t = (q == null) ? nbi() : q; + y.dlShiftTo(j, t); + if (r.compareTo(t) >= 0) { + r[r.t++] = 1; + r.subTo(t, r); + } + BigInteger.ONE.dlShiftTo(ys, t); + t.subTo(y, y); // "negative" y so we can replace sub with am later + while (y.t < ys) { + y[y.t++] = 0; + } + while (--j >= 0) { + // Estimate quotient digit + var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2); + if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out + y.dlShiftTo(j, t); + r.subTo(t, r); + while (r[i] < --qd) { + r.subTo(t, r); + } + } + } + if (q != null) { + r.drShiftTo(ys, q); + if (ts != ms) { + BigInteger.ZERO.subTo(q, q); + } + } + r.t = ys; + r.clamp(); + if (nsh > 0) { + r.rShiftTo(nsh, r); + } // Denormalize remainder + if (ts < 0) { + BigInteger.ZERO.subTo(r, r); + } + }; + // BigInteger.prototype.invDigit = bnpInvDigit; + // (protected) return "-1/this % 2^DB"; useful for Mont. reduction + // justification: + // xy == 1 (mod m) + // xy = 1+km + // xy(2-xy) = (1+km)(1-km) + // x[y(2-xy)] = 1-k^2m^2 + // x[y(2-xy)] == 1 (mod m^2) + // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 + // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. + // JS multiply "overflows" differently from C/C++, so care is needed here. + BigInteger.prototype.invDigit = function() { + if (this.t < 1) { + return 0; + } + var x = this[0]; + if ((x & 1) == 0) { + return 0; + } + var y = x & 3; // y == 1/x mod 2^2 + y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 + y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 + y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 + // last step - calculate inverse mod DV directly; + // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints + y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits + // we really want the negative inverse, and -DV < y < DV + return (y > 0) ? this.DV - y : -y; + }; + // BigInteger.prototype.isEven = bnpIsEven; + // (protected) true iff this is even + BigInteger.prototype.isEven = function() { + return ((this.t > 0) ? (this[0] & 1) : this.s) == 0; + }; + // BigInteger.prototype.exp = bnpExp; + // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) + BigInteger.prototype.exp = function(e, z) { + if (e > 0xffffffff || e < 1) { + return BigInteger.ONE; + } + var r = nbi(); + var r2 = nbi(); + var g = z.convert(this); + var i = nbits(e) - 1; + g.copyTo(r); + while (--i >= 0) { + z.sqrTo(r, r2); + if ((e & (1 << i)) > 0) { + z.mulTo(r2, g, r); + } else { + var t = r; + r = r2; + r2 = t; + } + } + return z.revert(r); + }; + // BigInteger.prototype.chunkSize = bnpChunkSize; + // (protected) return x s.t. r^x < DV + BigInteger.prototype.chunkSize = function(r) { + return Math.floor(Math.LN2 * this.DB / Math.log(r)); + }; + // BigInteger.prototype.toRadix = bnpToRadix; + // (protected) convert to radix string + BigInteger.prototype.toRadix = function(b) { + if (b == null) { + b = 10; + } + if (this.signum() == 0 || b < 2 || b > 36) { + return "0"; + } + var cs = this.chunkSize(b); + var a = Math.pow(b, cs); + var d = nbv(a); + var y = nbi(); + var z = nbi(); + var r = ""; + this.divRemTo(d, y, z); + while (y.signum() > 0) { + r = (a + z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d, y, z); + } + return z.intValue().toString(b) + r; + }; + // BigInteger.prototype.fromRadix = bnpFromRadix; + // (protected) convert from radix string + BigInteger.prototype.fromRadix = function(s, b) { + this.fromInt(0); + if (b == null) { + b = 10; + } + var cs = this.chunkSize(b); + var d = Math.pow(b, cs); + var mi = false; + var j = 0; + var w = 0; + for (var i = 0; i < s.length; ++i) { + var x = intAt(s, i); + if (x < 0) { + if (s.charAt(i) == "-" && this.signum() == 0) { + mi = true; + } + continue; + } + w = b * w + x; + if (++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w, 0); + j = 0; + w = 0; + } + } + if (j > 0) { + this.dMultiply(Math.pow(b, j)); + this.dAddOffset(w, 0); + } + if (mi) { + BigInteger.ZERO.subTo(this, this); + } + }; + // BigInteger.prototype.fromNumber = bnpFromNumber; + // (protected) alternate constructor + BigInteger.prototype.fromNumber = function(a, b, c) { + if ("number" == typeof b) { + // new BigInteger(int,int,RNG) + if (a < 2) { + this.fromInt(1); + } else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) { + // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + } + if (this.isEven()) { + this.dAddOffset(1, 0); + } // force odd + while (!this.isProbablePrime(b)) { + this.dAddOffset(2, 0); + if (this.bitLength() > a) { + this.subTo(BigInteger.ONE.shiftLeft(a - 1), this); + } + } + } + } else { + // new BigInteger(int,RNG) + var x = []; + var t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) { + x[0] &= ((1 << t) - 1); + } else { + x[0] = 0; + } + this.fromString(x, 256); + } + }; + // BigInteger.prototype.bitwiseTo = bnpBitwiseTo; + // (protected) r = this op a (bitwise) + BigInteger.prototype.bitwiseTo = function(a, op, r) { + var i; + var f; + var m = Math.min(a.t, this.t); + for (i = 0; i < m; ++i) { + r[i] = op(this[i], a[i]); + } + if (a.t < this.t) { + f = a.s & this.DM; + for (i = m; i < this.t; ++i) { + r[i] = op(this[i], f); + } + r.t = this.t; + } else { + f = this.s & this.DM; + for (i = m; i < a.t; ++i) { + r[i] = op(f, a[i]); + } + r.t = a.t; + } + r.s = op(this.s, a.s); + r.clamp(); + }; + // BigInteger.prototype.changeBit = bnpChangeBit; + // (protected) this op (1<>= this.DB; + } + if (a.t < this.t) { + c += a.s; + while (i < this.t) { + c += this[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while (i < a.t) { + c += a[i]; + r[i++] = c & this.DM; + c >>= this.DB; + } + c += a.s; + } + r.s = (c < 0) ? -1 : 0; + if (c > 0) { + r[i++] = c; + } else if (c < -1) { + r[i++] = this.DV + c; + } + r.t = i; + r.clamp(); + }; + // BigInteger.prototype.dMultiply = bnpDMultiply; + // (protected) this *= n, this >= 0, 1 < n < DV + BigInteger.prototype.dMultiply = function(n) { + this[this.t] = this.am(0, n - 1, this, 0, 0, this.t); + ++this.t; + this.clamp(); + }; + // BigInteger.prototype.dAddOffset = bnpDAddOffset; + // (protected) this += n << w words, this >= 0 + BigInteger.prototype.dAddOffset = function(n, w) { + if (n == 0) { + return; + } + while (this.t <= w) { + this[this.t++] = 0; + } + this[w] += n; + while (this[w] >= this.DV) { + this[w] -= this.DV; + if (++w >= this.t) { + this[this.t++] = 0; + } + ++this[w]; + } + }; + // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; + // (protected) r = lower n words of "this * a", a.t <= n + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyLowerTo = function(a, n, r) { + var i = Math.min(this.t + a.t, n); + r.s = 0; // assumes a,this >= 0 + r.t = i; + while (i > 0) { + r[--i] = 0; + } + for (var j = r.t - this.t; i < j; ++i) { + r[i + this.t] = this.am(0, a[i], r, i, 0, this.t); + } + for (var j = Math.min(a.t, n); i < j; ++i) { + this.am(0, a[i], r, i, 0, n - i); + } + r.clamp(); + }; + // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; + // (protected) r = "this * a" without lower n words, n > 0 + // "this" should be the larger one if appropriate. + BigInteger.prototype.multiplyUpperTo = function(a, n, r) { + --n; + var i = r.t = this.t + a.t - n; + r.s = 0; // assumes a,this >= 0 + while (--i >= 0) { + r[i] = 0; + } + for (i = Math.max(n - this.t, 0); i < a.t; ++i) { + r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n); + } + r.clamp(); + r.drShiftTo(1, r); + }; + // BigInteger.prototype.modInt = bnpModInt; + // (protected) this % n, n < 2^26 + BigInteger.prototype.modInt = function(n) { + if (n <= 0) { + return 0; + } + var d = this.DV % n; + var r = (this.s < 0) ? n - 1 : 0; + if (this.t > 0) { + if (d == 0) { + r = this[0] % n; + } else { + for (var i = this.t - 1; i >= 0; --i) { + r = (d * r + this[i]) % n; + } + } + } + return r; + }; + // BigInteger.prototype.millerRabin = bnpMillerRabin; + // (protected) true if probably prime (HAC 4.24, Miller-Rabin) + BigInteger.prototype.millerRabin = function(t) { + var n1 = this.subtract(BigInteger.ONE); + var k = n1.getLowestSetBit(); + if (k <= 0) { + return false; + } + var r = n1.shiftRight(k); + t = (t + 1) >> 1; + if (t > lowprimes.length) { + t = lowprimes.length; + } + var a = nbi(); + for (var i = 0; i < t; ++i) { + // Pick bases at random, instead of starting at 2 + a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]); + var y = a.modPow(r, this); + if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while (j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2, this); + if (y.compareTo(BigInteger.ONE) == 0) { + return false; + } + } + if (y.compareTo(n1) != 0) { + return false; + } + } + } + return true; + }; + // BigInteger.prototype.square = bnSquare; + // (public) this^2 + BigInteger.prototype.square = function() { + var r = nbi(); + this.squareTo(r); + return r; + }; + //#region ASYNC + // Public API method + BigInteger.prototype.gcda = function(a, callback) { + var x = (this.s < 0) ? this.negate() : this.clone(); + var y = (a.s < 0) ? a.negate() : a.clone(); + if (x.compareTo(y) < 0) { + var t = x; + x = y; + y = t; + } + var i = x.getLowestSetBit(); + var g = y.getLowestSetBit(); + if (g < 0) { + callback(x); + return; + } + if (i < g) { + g = i; + } + if (g > 0) { + x.rShiftTo(g, x); + y.rShiftTo(g, y); + } + // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen. + var gcda1 = function() { + if ((i = x.getLowestSetBit()) > 0) { + x.rShiftTo(i, x); + } + if ((i = y.getLowestSetBit()) > 0) { + y.rShiftTo(i, y); + } + if (x.compareTo(y) >= 0) { + x.subTo(y, x); + x.rShiftTo(1, x); + } else { + y.subTo(x, y); + y.rShiftTo(1, y); + } + if (!(x.signum() > 0)) { + if (g > 0) { + y.lShiftTo(g, y); + } + setTimeout(function() { + callback(y); + }, 0); // escape + } else { + setTimeout(gcda1, 0); + } + }; + setTimeout(gcda1, 10); + }; + // (protected) alternate constructor + BigInteger.prototype.fromNumberAsync = function(a, b, c, callback) { + if ("number" == typeof b) { + if (a < 2) { + this.fromInt(1); + } else { + this.fromNumber(a, c); + if (!this.testBit(a - 1)) { + this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this); + } + if (this.isEven()) { + this.dAddOffset(1, 0); + } + var bnp_1 = this; + var bnpfn1_1 = function() { + bnp_1.dAddOffset(2, 0); + if (bnp_1.bitLength() > a) { + bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1); + } + if (bnp_1.isProbablePrime(b)) { + setTimeout(function() { + callback(); + }, 0); // escape + } else { + setTimeout(bnpfn1_1, 0); + } + }; + setTimeout(bnpfn1_1, 0); + } + } else { + var x = []; + var t = a & 7; + x.length = (a >> 3) + 1; + b.nextBytes(x); + if (t > 0) { + x[0] &= ((1 << t) - 1); + } else { + x[0] = 0; + } + this.fromString(x, 256); + } + }; + return BigInteger; + }()); + //#region REDUCERS + //#region NullExp + var NullExp = /** @class */ (function() { + function NullExp() {} + // NullExp.prototype.convert = nNop; + NullExp.prototype.convert = function(x) { + return x; + }; + // NullExp.prototype.revert = nNop; + NullExp.prototype.revert = function(x) { + return x; + }; + // NullExp.prototype.mulTo = nMulTo; + NullExp.prototype.mulTo = function(x, y, r) { + x.multiplyTo(y, r); + }; + // NullExp.prototype.sqrTo = nSqrTo; + NullExp.prototype.sqrTo = function(x, r) { + x.squareTo(r); + }; + return NullExp; + }()); + // Modular reduction using "classic" algorithm + var Classic = /** @class */ (function() { + function Classic(m) { + this.m = m; + } + // Classic.prototype.convert = cConvert; + Classic.prototype.convert = function(x) { + if (x.s < 0 || x.compareTo(this.m) >= 0) { + return x.mod(this.m); + } else { + return x; + } + }; + // Classic.prototype.revert = cRevert; + Classic.prototype.revert = function(x) { + return x; + }; + // Classic.prototype.reduce = cReduce; + Classic.prototype.reduce = function(x) { + x.divRemTo(this.m, null, x); + }; + // Classic.prototype.mulTo = cMulTo; + Classic.prototype.mulTo = function(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Classic.prototype.sqrTo = cSqrTo; + Classic.prototype.sqrTo = function(x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Classic; + }()); + //#endregion + //#region Montgomery + // Montgomery reduction + var Montgomery = /** @class */ (function() { + function Montgomery(m) { + this.m = m; + this.mp = m.invDigit(); + this.mpl = this.mp & 0x7fff; + this.mph = this.mp >> 15; + this.um = (1 << (m.DB - 15)) - 1; + this.mt2 = 2 * m.t; + } + // Montgomery.prototype.convert = montConvert; + // xR mod m + Montgomery.prototype.convert = function(x) { + var r = nbi(); + x.abs().dlShiftTo(this.m.t, r); + r.divRemTo(this.m, null, r); + if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) { + this.m.subTo(r, r); + } + return r; + }; + // Montgomery.prototype.revert = montRevert; + // x/R mod m + Montgomery.prototype.revert = function(x) { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + }; + // Montgomery.prototype.reduce = montReduce; + // x = x/R mod m (HAC 14.32) + Montgomery.prototype.reduce = function(x) { + while (x.t <= this.mt2) { + // pad x so am has enough room later + x[x.t++] = 0; + } + for (var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x[i]*mp mod DV + var j = x[i] & 0x7fff; + var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this + .um) << 15)) & x.DM; + // use am to combine the multiply-shift-add into one call + j = i + this.m.t; + x[j] += this.m.am(0, u0, x, i, 0, this.m.t); + // propagate carry + while (x[j] >= x.DV) { + x[j] -= x.DV; + x[++j]++; + } + } + x.clamp(); + x.drShiftTo(this.m.t, x); + if (x.compareTo(this.m) >= 0) { + x.subTo(this.m, x); + } + }; + // Montgomery.prototype.mulTo = montMulTo; + // r = "xy/R mod m"; x,y != r + Montgomery.prototype.mulTo = function(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Montgomery.prototype.sqrTo = montSqrTo; + // r = "x^2/R mod m"; x != r + Montgomery.prototype.sqrTo = function(x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Montgomery; + }()); + //#endregion Montgomery + //#region Barrett + // Barrett modular reduction + var Barrett = /** @class */ (function() { + function Barrett(m) { + this.m = m; + // setup Barrett + this.r2 = nbi(); + this.q3 = nbi(); + BigInteger.ONE.dlShiftTo(2 * m.t, this.r2); + this.mu = this.r2.divide(m); + } + // Barrett.prototype.convert = barrettConvert; + Barrett.prototype.convert = function(x) { + if (x.s < 0 || x.t > 2 * this.m.t) { + return x.mod(this.m); + } else if (x.compareTo(this.m) < 0) { + return x; + } else { + var r = nbi(); + x.copyTo(r); + this.reduce(r); + return r; + } + }; + // Barrett.prototype.revert = barrettRevert; + Barrett.prototype.revert = function(x) { + return x; + }; + // Barrett.prototype.reduce = barrettReduce; + // x = x mod m (HAC 14.42) + Barrett.prototype.reduce = function(x) { + x.drShiftTo(this.m.t - 1, this.r2); + if (x.t > this.m.t + 1) { + x.t = this.m.t + 1; + x.clamp(); + } + this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3); + this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2); + while (x.compareTo(this.r2) < 0) { + x.dAddOffset(1, this.m.t + 1); + } + x.subTo(this.r2, x); + while (x.compareTo(this.m) >= 0) { + x.subTo(this.m, x); + } + }; + // Barrett.prototype.mulTo = barrettMulTo; + // r = x*y mod m; x,y != r + Barrett.prototype.mulTo = function(x, y, r) { + x.multiplyTo(y, r); + this.reduce(r); + }; + // Barrett.prototype.sqrTo = barrettSqrTo; + // r = x^2 mod m; x != r + Barrett.prototype.sqrTo = function(x, r) { + x.squareTo(r); + this.reduce(r); + }; + return Barrett; + }()); + //#endregion + //#endregion REDUCERS + // return new, unset BigInteger + function nbi() { + return new BigInteger(null); + } + + function parseBigInt(str, r) { + return new BigInteger(str, r); + } + // am: Compute w_j += (x*this_i), propagate carries, + // c is initial carry, returns final carry. + // c < 3*dvalue, x < 2*dvalue, this_i < dvalue + // We need to select the fastest one that works in this environment. + // am1: use a single mult and divide to get the high bits, + // max digit bits should be 26 because + // max internal value = 2*dvalue^2-2*dvalue (< 2^53) + function am1(i, x, w, j, c, n) { + while (--n >= 0) { + var v = x * this[i++] + w[j] + c; + c = Math.floor(v / 0x4000000); + w[j++] = v & 0x3ffffff; + } + return c; + } + // am2 avoids a big mult-and-extract completely. + // Max digit bits should be <= 30 because we do bitwise ops + // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) + function am2(i, x, w, j, c, n) { + var xl = x & 0x7fff; + var xh = x >> 15; + while (--n >= 0) { + var l = this[i] & 0x7fff; + var h = this[i++] >> 15; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff); + c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30); + w[j++] = l & 0x3fffffff; + } + return c; + } + // Alternately, set max digit bits to 28 since some + // browsers slow down when dealing with 32-bit numbers. + function am3(i, x, w, j, c, n) { + var xl = x & 0x3fff; + var xh = x >> 14; + while (--n >= 0) { + var l = this[i] & 0x3fff; + var h = this[i++] >> 14; + var m = xh * l + h * xl; + l = xl * l + ((m & 0x3fff) << 14) + w[j] + c; + c = (l >> 28) + (m >> 14) + xh * h; + w[j++] = l & 0xfffffff; + } + return c; + } + var inBrowser = typeof navigator2 !== "undefined"; + if (inBrowser && j_lm && (navigator2.appName == "Microsoft Internet Explorer")) { + BigInteger.prototype.am = am2; + dbits = 30; + } else if (inBrowser && j_lm && (navigator2.appName != "Netscape")) { + BigInteger.prototype.am = am1; + dbits = 26; + } else { // Mozilla/Netscape seems to prefer am3 + BigInteger.prototype.am = am3; + dbits = 28; + } + BigInteger.prototype.DB = dbits; + BigInteger.prototype.DM = ((1 << dbits) - 1); + BigInteger.prototype.DV = (1 << dbits); + var BI_FP = 52; + BigInteger.prototype.FV = Math.pow(2, BI_FP); + BigInteger.prototype.F1 = BI_FP - dbits; + BigInteger.prototype.F2 = 2 * dbits - BI_FP; + // Digit conversions + var BI_RC = []; + var rr; + var vv; + rr = "0".charCodeAt(0); + for (vv = 0; vv <= 9; ++vv) { + BI_RC[rr++] = vv; + } + rr = "a".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) { + BI_RC[rr++] = vv; + } + rr = "A".charCodeAt(0); + for (vv = 10; vv < 36; ++vv) { + BI_RC[rr++] = vv; + } + + function intAt(s, i) { + var c = BI_RC[s.charCodeAt(i)]; + return (c == null) ? -1 : c; + } + // return bigint initialized to value + function nbv(i) { + var r = nbi(); + r.fromInt(i); + return r; + } + // returns bit length of the integer x + function nbits(x) { + var r = 1; + var t; + if ((t = x >>> 16) != 0) { + x = t; + r += 16; + } + if ((t = x >> 8) != 0) { + x = t; + r += 8; + } + if ((t = x >> 4) != 0) { + x = t; + r += 4; + } + if ((t = x >> 2) != 0) { + x = t; + r += 2; + } + if ((t = x >> 1) != 0) { + x = t; + r += 1; + } + return r; + } + // "constants" + BigInteger.ZERO = nbv(0); + BigInteger.ONE = nbv(1); + + // prng4.js - uses Arcfour as a PRNG + var Arcfour = /** @class */ (function() { + function Arcfour() { + this.i = 0; + this.j = 0; + this.S = []; + } + // Arcfour.prototype.init = ARC4init; + // Initialize arcfour context from key, an array of ints, each from [0..255] + Arcfour.prototype.init = function(key) { + var i; + var j; + var t; + for (i = 0; i < 256; ++i) { + this.S[i] = i; + } + j = 0; + for (i = 0; i < 256; ++i) { + j = (j + this.S[i] + key[i % key.length]) & 255; + t = this.S[i]; + this.S[i] = this.S[j]; + this.S[j] = t; + } + this.i = 0; + this.j = 0; + }; + // Arcfour.prototype.next = ARC4next; + Arcfour.prototype.next = function() { + var t; + this.i = (this.i + 1) & 255; + this.j = (this.j + this.S[this.i]) & 255; + t = this.S[this.i]; + this.S[this.i] = this.S[this.j]; + this.S[this.j] = t; + return this.S[(t + this.S[this.i]) & 255]; + }; + return Arcfour; + }()); + // Plug in your RNG constructor here + function prng_newstate() { + return new Arcfour(); + } + // Pool size must be a multiple of 4 and greater than 32. + // An array of bytes the size of the pool will be passed to init() + var rng_psize = 256; + + // Random number generator - requires a PRNG backend, e.g. prng4.js + var rng_state; + var rng_pool = null; + var rng_pptr; + // Initialize the pool with junk if needed. + if (rng_pool == null) { + rng_pool = []; + rng_pptr = 0; + var t = void 0; + if (window2.crypto && window2.crypto.getRandomValues) { + // Extract entropy (2048 bits) from RNG if available + var z = new Uint32Array(256); + window2.crypto.getRandomValues(z); + for (t = 0; t < z.length; ++t) { + rng_pool[rng_pptr++] = z[t] & 255; + } + } + // Use mouse events for entropy, if we do not have enough entropy by the time + // we need it, entropy will be generated by Math.random. + var onMouseMoveListener_1 = function(ev) { + this.count = this.count || 0; + if (this.count >= 256 || rng_pptr >= rng_psize) { + if (window2.removeEventListener) { + window2.removeEventListener("mousemove", onMouseMoveListener_1, false); + } else if (window2.detachEvent) { + window2.detachEvent("onmousemove", onMouseMoveListener_1); + } + return; + } + try { + var mouseCoordinates = ev.x + ev.y; + rng_pool[rng_pptr++] = mouseCoordinates & 255; + this.count += 1; + } catch (e) { + // Sometimes Firefox will deny permission to access event properties for some reason. Ignore. + } + }; + if (window2.addEventListener) { + window2.addEventListener("mousemove", onMouseMoveListener_1, false); + } else if (window2.attachEvent) { + window2.attachEvent("onmousemove", onMouseMoveListener_1); + } + } + + function rng_get_byte() { + if (rng_state == null) { + rng_state = prng_newstate(); + // At this point, we may not have collected enough entropy. If not, fall back to Math.random + while (rng_pptr < rng_psize) { + var random = Math.floor(65536 * Math.random()); + rng_pool[rng_pptr++] = random & 255; + } + rng_state.init(rng_pool); + for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) { + rng_pool[rng_pptr] = 0; + } + rng_pptr = 0; + } + // TODO: allow reseeding after first request + return rng_state.next(); + } + var SecureRandom = /** @class */ (function() { + function SecureRandom() {} + SecureRandom.prototype.nextBytes = function(ba) { + for (var i = 0; i < ba.length; ++i) { + ba[i] = rng_get_byte(); + } + }; + return SecureRandom; + }()); + + // Depends on jsbn.js and rng.js + // function linebrk(s,n) { + // var ret = ""; + // var i = 0; + // while(i + n < s.length) { + // ret += s.substring(i,i+n) + "\n"; + // i += n; + // } + // return ret + s.substring(i,s.length); + // } + // function byte2Hex(b) { + // if(b < 0x10) + // return "0" + b.toString(16); + // else + // return b.toString(16); + // } + function pkcs1pad1(s, n) { + if (n < s.length + 22) { + console.error("Message too long for RSA"); + return null; + } + var len = n - s.length - 6; + var filler = ""; + for (var f = 0; f < len; f += 2) { + filler += "ff"; + } + var m = "0001" + filler + "00" + s; + return parseBigInt(m, 16); + } + // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint + function pkcs1pad2(s, n) { + if (n < s.length + 11) { // TODO: fix for utf-8 + console.error("Message too long for RSA"); + return null; + } + var ba = []; + var i = s.length - 1; + while (i >= 0 && n > 0) { + var c = s.charCodeAt(i--); + if (c < 128) { // encode using utf-8 + ba[--n] = c; + } else if ((c > 127) && (c < 2048)) { + ba[--n] = (c & 63) | 128; + ba[--n] = (c >> 6) | 192; + } else { + ba[--n] = (c & 63) | 128; + ba[--n] = ((c >> 6) & 63) | 128; + ba[--n] = (c >> 12) | 224; + } + } + ba[--n] = 0; + var rng = new SecureRandom(); + var x = []; + while (n > 2) { // random non-zero pad + x[0] = 0; + while (x[0] == 0) { + rng.nextBytes(x); + } + ba[--n] = x[0]; + } + ba[--n] = 2; + ba[--n] = 0; + return new BigInteger(ba); + } + // "empty" RSA key constructor + var RSAKey = /** @class */ (function() { + function RSAKey() { + this.n = null; + this.e = 0; + this.d = null; + this.p = null; + this.q = null; + this.dmp1 = null; + this.dmq1 = null; + this.coeff = null; + } + //#region PROTECTED + // protected + // RSAKey.prototype.doPublic = RSADoPublic; + // Perform raw public operation on "x": return x^e (mod n) + RSAKey.prototype.doPublic = function(x) { + return x.modPowInt(this.e, this.n); + }; + // RSAKey.prototype.doPrivate = RSADoPrivate; + // Perform raw private operation on "x": return x^d (mod n) + RSAKey.prototype.doPrivate = function(x) { + if (this.p == null || this.q == null) { + return x.modPow(this.d, this.n); + } + // TODO: re-calculate any missing CRT params + var xp = x.mod(this.p).modPow(this.dmp1, this.p); + var xq = x.mod(this.q).modPow(this.dmq1, this.q); + while (xp.compareTo(xq) < 0) { + xp = xp.add(this.p); + } + return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); + }; + //#endregion PROTECTED + //#region PUBLIC + // RSAKey.prototype.setPublic = RSASetPublic; + // Set the public key fields N and e from hex strings + RSAKey.prototype.setPublic = function(N, E) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + } else { + console.error("Invalid RSA public key"); + } + }; + // RSAKey.prototype.encrypt = RSAEncrypt; + // Return the PKCS#1 RSA encryption of "text" as an even-length hex string + RSAKey.prototype.encrypt = function(text) { + var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); + if (m == null) { + return null; + } + var c = this.doPublic(m); + if (c == null) { + return null; + } + var h = c.toString(16); + if ((h.length & 1) == 0) { + return h; + } else { + return "0" + h; + } + }; + // RSAKey.prototype.setPrivate = RSASetPrivate; + // Set the private key fields N, e, and d from hex strings + RSAKey.prototype.setPrivate = function(N, E, D) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + this.d = parseBigInt(D, 16); + } else { + console.error("Invalid RSA private key"); + } + }; + // RSAKey.prototype.setPrivateEx = RSASetPrivateEx; + // Set the private key fields N, e, d and CRT params from hex strings + RSAKey.prototype.setPrivateEx = function(N, E, D, P, Q, DP, DQ, C) { + if (N != null && E != null && N.length > 0 && E.length > 0) { + this.n = parseBigInt(N, 16); + this.e = parseInt(E, 16); + this.d = parseBigInt(D, 16); + this.p = parseBigInt(P, 16); + this.q = parseBigInt(Q, 16); + this.dmp1 = parseBigInt(DP, 16); + this.dmq1 = parseBigInt(DQ, 16); + this.coeff = parseBigInt(C, 16); + } else { + console.error("Invalid RSA private key"); + } + }; + // RSAKey.prototype.generate = RSAGenerate; + // Generate a new random private key B bits long, using public expt E + RSAKey.prototype.generate = function(B, E) { + var rng = new SecureRandom(); + var qs = B >> 1; + this.e = parseInt(E, 16); + var ee = new BigInteger(E, 16); + for (;;) { + for (;;) { + this.p = new BigInteger(B - qs, 1, rng); + if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == + 0 && this.p.isProbablePrime(10)) { + break; + } + } + for (;;) { + this.q = new BigInteger(qs, 1, rng); + if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == + 0 && this.q.isProbablePrime(10)) { + break; + } + } + if (this.p.compareTo(this.q) <= 0) { + var t = this.p; + this.p = this.q; + this.q = t; + } + var p1 = this.p.subtract(BigInteger.ONE); + var q1 = this.q.subtract(BigInteger.ONE); + var phi = p1.multiply(q1); + if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { + this.n = this.p.multiply(this.q); + this.d = ee.modInverse(phi); + this.dmp1 = this.d.mod(p1); + this.dmq1 = this.d.mod(q1); + this.coeff = this.q.modInverse(this.p); + break; + } + } + }; + // RSAKey.prototype.decrypt = RSADecrypt; + // Return the PKCS#1 RSA decryption of "ctext". + // "ctext" is an even-length hex string and the output is a plain string. + RSAKey.prototype.decrypt = function(ctext) { + var c = parseBigInt(ctext, 16); + var m = this.doPrivate(c); + if (m == null) { + return null; + } + return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); + }; + // Generate a new random private key B bits long, using public expt E + RSAKey.prototype.generateAsync = function(B, E, callback) { + var rng = new SecureRandom(); + var qs = B >> 1; + this.e = parseInt(E, 16); + var ee = new BigInteger(E, 16); + var rsa = this; + // These functions have non-descript names because they were originally for(;;) loops. + // I don't know about cryptography to give them better names than loop1-4. + var loop1 = function() { + var loop4 = function() { + if (rsa.p.compareTo(rsa.q) <= 0) { + var t = rsa.p; + rsa.p = rsa.q; + rsa.q = t; + } + var p1 = rsa.p.subtract(BigInteger.ONE); + var q1 = rsa.q.subtract(BigInteger.ONE); + var phi = p1.multiply(q1); + if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) { + rsa.n = rsa.p.multiply(rsa.q); + rsa.d = ee.modInverse(phi); + rsa.dmp1 = rsa.d.mod(p1); + rsa.dmq1 = rsa.d.mod(q1); + rsa.coeff = rsa.q.modInverse(rsa.p); + setTimeout(function() { + callback(); + }, 0); // escape + } else { + setTimeout(loop1, 0); + } + }; + var loop3 = function() { + rsa.q = nbi(); + rsa.q.fromNumberAsync(qs, 1, rng, function() { + rsa.q.subtract(BigInteger.ONE).gcda(ee, function(r) { + if (r.compareTo(BigInteger.ONE) == 0 && rsa + .q.isProbablePrime(10)) { + setTimeout(loop4, 0); + } else { + setTimeout(loop3, 0); + } + }); + }); + }; + var loop2 = function() { + rsa.p = nbi(); + rsa.p.fromNumberAsync(B - qs, 1, rng, function() { + rsa.p.subtract(BigInteger.ONE).gcda(ee, function(r) { + if (r.compareTo(BigInteger.ONE) == 0 && rsa + .p.isProbablePrime(10)) { + setTimeout(loop3, 0); + } else { + setTimeout(loop2, 0); + } + }); + }); + }; + setTimeout(loop2, 0); + }; + setTimeout(loop1, 0); + }; + RSAKey.prototype.sign = function(text, digestMethod, digestName) { + var header = getDigestHeader(digestName); + var digest = header + digestMethod(text).toString(); + var m = pkcs1pad1(digest, this.n.bitLength() / 4); + if (m == null) { + return null; + } + var c = this.doPrivate(m); + if (c == null) { + return null; + } + var h = c.toString(16); + if ((h.length & 1) == 0) { + return h; + } else { + return "0" + h; + } + }; + RSAKey.prototype.verify = function(text, signature, digestMethod) { + var c = parseBigInt(signature, 16); + var m = this.doPublic(c); + if (m == null) { + return null; + } + var unpadded = m.toString(16).replace(/^1f+00/, ""); + var digest = removeDigestHeader(unpadded); + return digest == digestMethod(text).toString(); + }; + return RSAKey; + }()); + // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext + function pkcs1unpad2(d, n) { + var b = d.toByteArray(); + var i = 0; + while (i < b.length && b[i] == 0) { + ++i; + } + if (b.length - i != n - 1 || b[i] != 2) { + return null; + } + ++i; + while (b[i] != 0) { + if (++i >= b.length) { + return null; + } + } + var ret = ""; + while (++i < b.length) { + var c = b[i] & 255; + if (c < 128) { // utf-8 decode + ret += String.fromCharCode(c); + } else if ((c > 191) && (c < 224)) { + ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63)); + ++i; + } else { + ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63)); + i += 2; + } + } + return ret; + } + // https://tools.ietf.org/html/rfc3447#page-43 + var DIGEST_HEADERS = { + md2: "3020300c06082a864886f70d020205000410", + md5: "3020300c06082a864886f70d020505000410", + sha1: "3021300906052b0e03021a05000414", + sha224: "302d300d06096086480165030402040500041c", + sha256: "3031300d060960864801650304020105000420", + sha384: "3041300d060960864801650304020205000430", + sha512: "3051300d060960864801650304020305000440", + ripemd160: "3021300906052b2403020105000414", + }; + + function getDigestHeader(name) { + return DIGEST_HEADERS[name] || ""; + } + + function removeDigestHeader(str) { + for (var name_1 in DIGEST_HEADERS) { + if (DIGEST_HEADERS.hasOwnProperty(name_1)) { + var header = DIGEST_HEADERS[name_1]; + var len = header.length; + if (str.substr(0, len) == header) { + return str.substr(len); + } + } + } + return str; + } + // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string + // function RSAEncryptB64(text) { + // var h = this.encrypt(text); + // if(h) return hex2b64(h); else return null; + // } + // public + // RSAKey.prototype.encrypt_b64 = RSAEncryptB64; + + /*! + Copyright (c) 2011, Yahoo! Inc. All rights reserved. + Code licensed under the BSD License: + http://developer.yahoo.com/yui/license.html + version: 2.9.0 + */ + var YAHOO = {}; + YAHOO.lang = { + /** + * Utility to set up the prototype, constructor and superclass properties to + * support an inheritance strategy that can chain constructors and methods. + * Static members will not be inherited. + * + * @method extend + * @static + * @param {Function} subc the object to modify + * @param {Function} superc the object to inherit + * @param {Object} overrides additional properties/methods to add to the + * subclass prototype. These will override the + * matching items obtained from the superclass + * if present. + */ + extend: function(subc, superc, overrides) { + if (!superc || !subc) { + throw new Error("YAHOO.lang.extend failed, please check that " + + "all dependencies are included."); + } + + var F = function() {}; + F.prototype = superc.prototype; + subc.prototype = new F(); + subc.prototype.constructor = subc; + subc.superclass = superc.prototype; + + if (superc.prototype.constructor == Object.prototype.constructor) { + superc.prototype.constructor = superc; + } + + if (overrides) { + var i; + for (i in overrides) { + subc.prototype[i] = overrides[i]; + } + + /* + * IE will not enumerate native functions in a derived object even if the + * function was overridden. This is a workaround for specific functions + * we care about on the Object prototype. + * @property _IEEnumFix + * @param {Function} r the object to receive the augmentation + * @param {Function} s the object that supplies the properties to augment + * @static + * @private + */ + var _IEEnumFix = function() {}, + ADD = ["toString", "valueOf"]; + try { + if (/MSIE/.test(navigator2.userAgent)) { + _IEEnumFix = function(r, s) { + for (i = 0; i < ADD.length; i = i + 1) { + var fname = ADD[i], + f = s[fname]; + if (typeof f === 'function' && f != Object.prototype[fname]) { + r[fname] = f; + } + } + }; + } + } catch (ex) {} + _IEEnumFix(subc.prototype, overrides); + } + } + }; + + /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license + */ + + /** + * @fileOverview + * @name asn1-1.0.js + * @author Kenji Urushima kenji.urushima@gmail.com + * @version asn1 1.0.13 (2017-Jun-02) + * @since jsrsasign 2.1 + * @license MIT License + */ + + /** + * kjur's class library name space + *

+ * This name space provides following name spaces: + *

    + *
  • {@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder
  • + *
  • {@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL
  • + *
  • {@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature + * class and utilities
  • + *
+ *

+ * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2. + * @name KJUR + * @namespace kjur's class library name space + */ + var KJUR = {}; + + /** + * kjur's ASN.1 class library name space + *

+ * This is ITU-T X.690 ASN.1 DER encoder class library and + * class structure and methods is very similar to + * org.bouncycastle.asn1 package of + * well known BouncyCaslte Cryptography Library. + *

PROVIDING ASN.1 PRIMITIVES

+ * Here are ASN.1 DER primitive classes. + *
    + *
  • 0x01 {@link KJUR.asn1.DERBoolean}
  • + *
  • 0x02 {@link KJUR.asn1.DERInteger}
  • + *
  • 0x03 {@link KJUR.asn1.DERBitString}
  • + *
  • 0x04 {@link KJUR.asn1.DEROctetString}
  • + *
  • 0x05 {@link KJUR.asn1.DERNull}
  • + *
  • 0x06 {@link KJUR.asn1.DERObjectIdentifier}
  • + *
  • 0x0a {@link KJUR.asn1.DEREnumerated}
  • + *
  • 0x0c {@link KJUR.asn1.DERUTF8String}
  • + *
  • 0x12 {@link KJUR.asn1.DERNumericString}
  • + *
  • 0x13 {@link KJUR.asn1.DERPrintableString}
  • + *
  • 0x14 {@link KJUR.asn1.DERTeletexString}
  • + *
  • 0x16 {@link KJUR.asn1.DERIA5String}
  • + *
  • 0x17 {@link KJUR.asn1.DERUTCTime}
  • + *
  • 0x18 {@link KJUR.asn1.DERGeneralizedTime}
  • + *
  • 0x30 {@link KJUR.asn1.DERSequence}
  • + *
  • 0x31 {@link KJUR.asn1.DERSet}
  • + *
+ *

OTHER ASN.1 CLASSES

+ *
    + *
  • {@link KJUR.asn1.ASN1Object}
  • + *
  • {@link KJUR.asn1.DERAbstractString}
  • + *
  • {@link KJUR.asn1.DERAbstractTime}
  • + *
  • {@link KJUR.asn1.DERAbstractStructured}
  • + *
  • {@link KJUR.asn1.DERTaggedObject}
  • + *
+ *

SUB NAME SPACES

+ *
    + *
  • {@link KJUR.asn1.cades} - CAdES long term signature format
  • + *
  • {@link KJUR.asn1.cms} - Cryptographic Message Syntax
  • + *
  • {@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)
  • + *
  • {@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format
  • + *
  • {@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL
  • + *
+ *

+ * NOTE: Please ignore method summary and document of this namespace. + * This caused by a bug of jsdoc2. + * @name KJUR.asn1 + * @namespace + */ + if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {}; + + /** + * ASN1 utilities class + * @name KJUR.asn1.ASN1Util + * @class ASN1 utilities class + * @since asn1 1.0.2 + */ + KJUR.asn1.ASN1Util = new function() { + this.integerToByteHex = function(i) { + var h = i.toString(16); + if ((h.length % 2) == 1) h = '0' + h; + return h; + }; + this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) { + var h = bigIntegerValue.toString(16); + if (h.substr(0, 1) != '-') { + if (h.length % 2 == 1) { + h = '0' + h; + } else { + if (!h.match(/^[0-7]/)) { + h = '00' + h; + } + } + } else { + var hPos = h.substr(1); + var xorLen = hPos.length; + if (xorLen % 2 == 1) { + xorLen += 1; + } else { + if (!h.match(/^[0-7]/)) { + xorLen += 2; + } + } + var hMask = ''; + for (var i = 0; i < xorLen; i++) { + hMask += 'f'; + } + var biMask = new BigInteger(hMask, 16); + var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE); + h = biNeg.toString(16).replace(/^-/, ''); + } + return h; + }; + /** + * get PEM string from hexadecimal data and header string + * @name getPEMStringFromHex + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} dataHex hexadecimal string of PEM body + * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY') + * @return {String} PEM formatted string of input data + * @description + * This method converts a hexadecimal string to a PEM string with + * a specified header. Its line break will be CRLF("\r\n"). + * @example + * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY'); + * // value of pem will be: + * -----BEGIN PRIVATE KEY----- + * YWFh + * -----END PRIVATE KEY----- + */ + this.getPEMStringFromHex = function(dataHex, pemHeader) { + return hextopem(dataHex, pemHeader); + }; + + /** + * generate ASN1Object specifed by JSON parameters + * @name newObject + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {Array} param JSON parameter to generate ASN1Object + * @return {KJUR.asn1.ASN1Object} generated object + * @since asn1 1.0.3 + * @description + * generate any ASN1Object specified by JSON param + * including ASN.1 primitive or structured. + * Generally 'param' can be described as follows: + *
+ * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER} + *
+ * 'TYPE-OF-ASN1OBJ' can be one of following symbols: + *
    + *
  • 'bool' - DERBoolean
  • + *
  • 'int' - DERInteger
  • + *
  • 'bitstr' - DERBitString
  • + *
  • 'octstr' - DEROctetString
  • + *
  • 'null' - DERNull
  • + *
  • 'oid' - DERObjectIdentifier
  • + *
  • 'enum' - DEREnumerated
  • + *
  • 'utf8str' - DERUTF8String
  • + *
  • 'numstr' - DERNumericString
  • + *
  • 'prnstr' - DERPrintableString
  • + *
  • 'telstr' - DERTeletexString
  • + *
  • 'ia5str' - DERIA5String
  • + *
  • 'utctime' - DERUTCTime
  • + *
  • 'gentime' - DERGeneralizedTime
  • + *
  • 'seq' - DERSequence
  • + *
  • 'set' - DERSet
  • + *
  • 'tag' - DERTaggedObject
  • + *
+ * @example + * newObject({'prnstr': 'aaa'}); + * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]}) + * // ASN.1 Tagged Object + * newObject({'tag': {'tag': 'a1', + * 'explicit': true, + * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}}); + * // more simple representation of ASN.1 Tagged Object + * newObject({'tag': ['a1', + * true, + * {'seq': [ + * {'int': 3}, + * {'prnstr': 'aaa'}]} + * ]}); + */ + this.newObject = function(param) { + var _KJUR = KJUR, + _KJUR_asn1 = _KJUR.asn1, + _DERBoolean = _KJUR_asn1.DERBoolean, + _DERInteger = _KJUR_asn1.DERInteger, + _DERBitString = _KJUR_asn1.DERBitString, + _DEROctetString = _KJUR_asn1.DEROctetString, + _DERNull = _KJUR_asn1.DERNull, + _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier, + _DEREnumerated = _KJUR_asn1.DEREnumerated, + _DERUTF8String = _KJUR_asn1.DERUTF8String, + _DERNumericString = _KJUR_asn1.DERNumericString, + _DERPrintableString = _KJUR_asn1.DERPrintableString, + _DERTeletexString = _KJUR_asn1.DERTeletexString, + _DERIA5String = _KJUR_asn1.DERIA5String, + _DERUTCTime = _KJUR_asn1.DERUTCTime, + _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime, + _DERSequence = _KJUR_asn1.DERSequence, + _DERSet = _KJUR_asn1.DERSet, + _DERTaggedObject = _KJUR_asn1.DERTaggedObject, + _newObject = _KJUR_asn1.ASN1Util.newObject; + + var keys = Object.keys(param); + if (keys.length != 1) + throw "key of param shall be only one."; + var key = keys[0]; + + if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:" + .indexOf(":" + key + ":") == -1) + throw "undefined key: " + key; + + if (key == "bool") return new _DERBoolean(param[key]); + if (key == "int") return new _DERInteger(param[key]); + if (key == "bitstr") return new _DERBitString(param[key]); + if (key == "octstr") return new _DEROctetString(param[key]); + if (key == "null") return new _DERNull(param[key]); + if (key == "oid") return new _DERObjectIdentifier(param[key]); + if (key == "enum") return new _DEREnumerated(param[key]); + if (key == "utf8str") return new _DERUTF8String(param[key]); + if (key == "numstr") return new _DERNumericString(param[key]); + if (key == "prnstr") return new _DERPrintableString(param[key]); + if (key == "telstr") return new _DERTeletexString(param[key]); + if (key == "ia5str") return new _DERIA5String(param[key]); + if (key == "utctime") return new _DERUTCTime(param[key]); + if (key == "gentime") return new _DERGeneralizedTime(param[key]); + + if (key == "seq") { + var paramList = param[key]; + var a = []; + for (var i = 0; i < paramList.length; i++) { + var asn1Obj = _newObject(paramList[i]); + a.push(asn1Obj); + } + return new _DERSequence({ + 'array': a + }); + } + + if (key == "set") { + var paramList = param[key]; + var a = []; + for (var i = 0; i < paramList.length; i++) { + var asn1Obj = _newObject(paramList[i]); + a.push(asn1Obj); + } + return new _DERSet({ + 'array': a + }); + } + + if (key == "tag") { + var tagParam = param[key]; + if (Object.prototype.toString.call(tagParam) === '[object Array]' && + tagParam.length == 3) { + var obj = _newObject(tagParam[2]); + return new _DERTaggedObject({ + tag: tagParam[0], + explicit: tagParam[1], + obj: obj + }); + } else { + var newParam = {}; + if (tagParam.explicit !== undefined) + newParam.explicit = tagParam.explicit; + if (tagParam.tag !== undefined) + newParam.tag = tagParam.tag; + if (tagParam.obj === undefined) + throw "obj shall be specified for 'tag'."; + newParam.obj = _newObject(tagParam.obj); + return new _DERTaggedObject(newParam); + } + } + }; + + /** + * get encoded hexadecimal string of ASN1Object specifed by JSON parameters + * @name jsonToASN1HEX + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {Array} param JSON parameter to generate ASN1Object + * @return hexadecimal string of ASN1Object + * @since asn1 1.0.4 + * @description + * As for ASN.1 object representation of JSON object, + * please see {@link newObject}. + * @example + * jsonToASN1HEX({'prnstr': 'aaa'}); + */ + this.jsonToASN1HEX = function(param) { + var asn1Obj = this.newObject(param); + return asn1Obj.getEncodedHex(); + }; + }; + + /** + * get dot noted oid number string from hexadecimal value of OID + * @name oidHexToInt + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} hex hexadecimal value of object identifier + * @return {String} dot noted string of object identifier + * @since jsrsasign 4.8.3 asn1 1.0.7 + * @description + * This static method converts from hexadecimal string representation of + * ASN.1 value of object identifier to oid number string. + * @example + * KJUR.asn1.ASN1Util.oidHexToInt('550406') → "2.5.4.6" + */ + KJUR.asn1.ASN1Util.oidHexToInt = function(hex) { + var s = ""; + var i01 = parseInt(hex.substr(0, 2), 16); + var i0 = Math.floor(i01 / 40); + var i1 = i01 % 40; + var s = i0 + "." + i1; + + var binbuf = ""; + for (var i = 2; i < hex.length; i += 2) { + var value = parseInt(hex.substr(i, 2), 16); + var bin = ("00000000" + value.toString(2)).slice(-8); + binbuf = binbuf + bin.substr(1, 7); + if (bin.substr(0, 1) == "0") { + var bi = new BigInteger(binbuf, 2); + s = s + "." + bi.toString(10); + binbuf = ""; + } + } + return s; + }; + + /** + * get hexadecimal value of object identifier from dot noted oid value + * @name oidIntToHex + * @memberOf KJUR.asn1.ASN1Util + * @function + * @param {String} oidString dot noted string of object identifier + * @return {String} hexadecimal value of object identifier + * @since jsrsasign 4.8.3 asn1 1.0.7 + * @description + * This static method converts from object identifier value string. + * to hexadecimal string representation of it. + * @example + * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") → "550406" + */ + KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) { + var itox = function(i) { + var h = i.toString(16); + if (h.length == 1) h = '0' + h; + return h; + }; + + var roidtox = function(roid) { + var h = ''; + var bi = new BigInteger(roid, 10); + var b = bi.toString(2); + var padLen = 7 - b.length % 7; + if (padLen == 7) padLen = 0; + var bPad = ''; + for (var i = 0; i < padLen; i++) bPad += '0'; + b = bPad + b; + for (var i = 0; i < b.length - 1; i += 7) { + var b8 = b.substr(i, 7); + if (i != b.length - 7) b8 = '1' + b8; + h += itox(parseInt(b8, 2)); + } + return h; + }; + + if (!oidString.match(/^[0-9.]+$/)) { + throw "malformed oid string: " + oidString; + } + var h = ''; + var a = oidString.split('.'); + var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); + h += itox(i0); + a.splice(0, 2); + for (var i = 0; i < a.length; i++) { + h += roidtox(a[i]); + } + return h; + }; + + + // ******************************************************************** + // Abstract ASN.1 Classes + // ******************************************************************** + + // ******************************************************************** + + /** + * base class for ASN.1 DER encoder object + * @name KJUR.asn1.ASN1Object + * @class base class for ASN.1 DER encoder object + * @property {Boolean} isModified flag whether internal data was changed + * @property {String} hTLV hexadecimal string of ASN.1 TLV + * @property {String} hT hexadecimal string of ASN.1 TLV tag(T) + * @property {String} hL hexadecimal string of ASN.1 TLV length(L) + * @property {String} hV hexadecimal string of ASN.1 TLV value(V) + * @description + */ + KJUR.asn1.ASN1Object = function() { + var hV = ''; + + /** + * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V) + * @name getLengthHexFromValue + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV length(L) + */ + this.getLengthHexFromValue = function() { + if (typeof this.hV == "undefined" || this.hV == null) { + throw "this.hV is null or undefined."; + } + if (this.hV.length % 2 == 1) { + throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV; + } + var n = this.hV.length / 2; + var hN = n.toString(16); + if (hN.length % 2 == 1) { + hN = "0" + hN; + } + if (n < 128) { + return hN; + } else { + var hNlen = hN.length / 2; + if (hNlen > 15) { + throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16); + } + var head = 128 + hNlen; + return head.toString(16) + hN; + } + }; + + /** + * get hexadecimal string of ASN.1 TLV bytes + * @name getEncodedHex + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV + */ + this.getEncodedHex = function() { + if (this.hTLV == null || this.isModified) { + this.hV = this.getFreshValueHex(); + this.hL = this.getLengthHexFromValue(); + this.hTLV = this.hT + this.hL + this.hV; + this.isModified = false; + //alert("first time: " + this.hTLV); + } + return this.hTLV; + }; + + /** + * get hexadecimal string of ASN.1 TLV value(V) bytes + * @name getValueHex + * @memberOf KJUR.asn1.ASN1Object# + * @function + * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes + */ + this.getValueHex = function() { + this.getEncodedHex(); + return this.hV; + }; + + this.getFreshValueHex = function() { + return ''; + }; + }; + + // == BEGIN DERAbstractString ================================================ + /** + * base class for ASN.1 DER string classes + * @name KJUR.asn1.DERAbstractString + * @class base class for ASN.1 DER string classes + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @property {String} s internal string of value + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * NOTE: 'params' can be omitted. + */ + KJUR.asn1.DERAbstractString = function(params) { + KJUR.asn1.DERAbstractString.superclass.constructor.call(this); + + /** + * get string value of this string object + * @name getString + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @return {String} string value of this string object + */ + this.getString = function() { + return this.s; + }; + + /** + * set value by a string + * @name setString + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @param {String} newS value by a string to set + */ + this.setString = function(newS) { + this.hTLV = null; + this.isModified = true; + this.s = newS; + this.hV = stohex(this.s); + }; + + /** + * set value by a hexadecimal string + * @name setStringHex + * @memberOf KJUR.asn1.DERAbstractString# + * @function + * @param {String} newHexString value by a hexadecimal string to set + */ + this.setStringHex = function(newHexString) { + this.hTLV = null; + this.isModified = true; + this.s = null; + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params == "string") { + this.setString(params); + } else if (typeof params['str'] != "undefined") { + this.setString(params['str']); + } else if (typeof params['hex'] != "undefined") { + this.setStringHex(params['hex']); + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object); + // == END DERAbstractString ================================================ + + // == BEGIN DERAbstractTime ================================================== + /** + * base class for ASN.1 DER Generalized/UTCTime class + * @name KJUR.asn1.DERAbstractTime + * @class base class for ASN.1 DER Generalized/UTCTime class + * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ + KJUR.asn1.DERAbstractTime = function(params) { + KJUR.asn1.DERAbstractTime.superclass.constructor.call(this); + + // --- PRIVATE METHODS -------------------- + this.localDateToUTC = function(d) { + utc = d.getTime() + (d.getTimezoneOffset() * 60000); + var utcDate = new Date(utc); + return utcDate; + }; + + /* + * format date string by Data object + * @name formatDate + * @memberOf KJUR.asn1.AbstractTime; + * @param {Date} dateObject + * @param {string} type 'utc' or 'gen' + * @param {boolean} withMillis flag for with millisections or not + * @description + * 'withMillis' flag is supported from asn1 1.0.6. + */ + this.formatDate = function(dateObject, type, withMillis) { + var pad = this.zeroPadding; + var d = this.localDateToUTC(dateObject); + var year = String(d.getFullYear()); + if (type == 'utc') year = year.substr(2, 2); + var month = pad(String(d.getMonth() + 1), 2); + var day = pad(String(d.getDate()), 2); + var hour = pad(String(d.getHours()), 2); + var min = pad(String(d.getMinutes()), 2); + var sec = pad(String(d.getSeconds()), 2); + var s = year + month + day + hour + min + sec; + if (withMillis === true) { + var millis = d.getMilliseconds(); + if (millis != 0) { + var sMillis = pad(String(millis), 3); + sMillis = sMillis.replace(/[0]+$/, ""); + s = s + "." + sMillis; + } + } + return s + "Z"; + }; + + this.zeroPadding = function(s, len) { + if (s.length >= len) return s; + return new Array(len - s.length + 1).join('0') + s; + }; + + // --- PUBLIC METHODS -------------------- + /** + * get string value of this string object + * @name getString + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @return {String} string value of this time object + */ + this.getString = function() { + return this.s; + }; + + /** + * set value by a string + * @name setString + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @param {String} newS value by a string to set such like "130430235959Z" + */ + this.setString = function(newS) { + this.hTLV = null; + this.isModified = true; + this.s = newS; + this.hV = stohex(newS); + }; + + /** + * set value by a Date object + * @name setByDateValue + * @memberOf KJUR.asn1.DERAbstractTime# + * @function + * @param {Integer} year year of date (ex. 2013) + * @param {Integer} month month of date between 1 and 12 (ex. 12) + * @param {Integer} day day of month + * @param {Integer} hour hours of date + * @param {Integer} min minutes of date + * @param {Integer} sec seconds of date + */ + this.setByDateValue = function(year, month, day, hour, min, sec) { + var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0)); + this.setByDate(dateObject); + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + }; + YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object); + // == END DERAbstractTime ================================================== + + // == BEGIN DERAbstractStructured ============================================ + /** + * base class for ASN.1 DER structured class + * @name KJUR.asn1.DERAbstractStructured + * @class base class for ASN.1 DER structured class + * @property {Array} asn1Array internal array of ASN1Object + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ + KJUR.asn1.DERAbstractStructured = function(params) { + KJUR.asn1.DERAbstractString.superclass.constructor.call(this); + + /** + * set value by array of ASN1Object + * @name setByASN1ObjectArray + * @memberOf KJUR.asn1.DERAbstractStructured# + * @function + * @param {array} asn1ObjectArray array of ASN1Object to set + */ + this.setByASN1ObjectArray = function(asn1ObjectArray) { + this.hTLV = null; + this.isModified = true; + this.asn1Array = asn1ObjectArray; + }; + + /** + * append an ASN1Object to internal array + * @name appendASN1Object + * @memberOf KJUR.asn1.DERAbstractStructured# + * @function + * @param {ASN1Object} asn1Object to add + */ + this.appendASN1Object = function(asn1Object) { + this.hTLV = null; + this.isModified = true; + this.asn1Array.push(asn1Object); + }; + + this.asn1Array = new Array(); + if (typeof params != "undefined") { + if (typeof params['array'] != "undefined") { + this.asn1Array = params['array']; + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object); + + + // ******************************************************************** + // ASN.1 Object Classes + // ******************************************************************** + + // ******************************************************************** + /** + * class for ASN.1 DER Boolean + * @name KJUR.asn1.DERBoolean + * @class class for ASN.1 DER Boolean + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ + KJUR.asn1.DERBoolean = function() { + KJUR.asn1.DERBoolean.superclass.constructor.call(this); + this.hT = "01"; + this.hTLV = "0101ff"; + }; + YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object); + + // ******************************************************************** + /** + * class for ASN.1 DER Integer + * @name KJUR.asn1.DERInteger + * @class class for ASN.1 DER Integer + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • int - specify initial ASN.1 value(V) by integer value
  • + *
  • bigint - specify initial ASN.1 value(V) by BigInteger object
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * NOTE: 'params' can be omitted. + */ + KJUR.asn1.DERInteger = function(params) { + KJUR.asn1.DERInteger.superclass.constructor.call(this); + this.hT = "02"; + + /** + * set value by Tom Wu's BigInteger object + * @name setByBigInteger + * @memberOf KJUR.asn1.DERInteger# + * @function + * @param {BigInteger} bigIntegerValue to set + */ + this.setByBigInteger = function(bigIntegerValue) { + this.hTLV = null; + this.isModified = true; + this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); + }; + + /** + * set value by integer value + * @name setByInteger + * @memberOf KJUR.asn1.DERInteger + * @function + * @param {Integer} integer value to set + */ + this.setByInteger = function(intValue) { + var bi = new BigInteger(String(intValue), 10); + this.setByBigInteger(bi); + }; + + /** + * set value by integer value + * @name setValueHex + * @memberOf KJUR.asn1.DERInteger# + * @function + * @param {String} hexadecimal string of integer value + * @description + *
+ * NOTE: Value shall be represented by minimum octet length of + * two's complement representation. + * @example + * new KJUR.asn1.DERInteger(123); + * new KJUR.asn1.DERInteger({'int': 123}); + * new KJUR.asn1.DERInteger({'hex': '1fad'}); + */ + this.setValueHex = function(newHexString) { + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['bigint'] != "undefined") { + this.setByBigInteger(params['bigint']); + } else if (typeof params['int'] != "undefined") { + this.setByInteger(params['int']); + } else if (typeof params == "number") { + this.setByInteger(params); + } else if (typeof params['hex'] != "undefined") { + this.setValueHex(params['hex']); + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object); + + // ******************************************************************** + /** + * class for ASN.1 DER encoded BitString primitive + * @name KJUR.asn1.DERBitString + * @class class for ASN.1 DER encoded BitString primitive + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • bin - specify binary string (ex. '10111')
  • + *
  • array - specify array of boolean (ex. [true,false,true,true])
  • + *
  • hex - specify hexadecimal string of ASN.1 value(V) including unused bits
  • + *
  • obj - specify {@link KJUR.asn1.ASN1Util.newObject} + * argument for "BitString encapsulates" structure.
  • + *
+ * NOTE1: 'params' can be omitted.
+ * NOTE2: 'obj' parameter have been supported since + * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
+ * @example + * // default constructor + * o = new KJUR.asn1.DERBitString(); + * // initialize with binary string + * o = new KJUR.asn1.DERBitString({bin: "1011"}); + * // initialize with boolean array + * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]}); + * // initialize with hexadecimal string (04 is unused bits) + * o = new KJUR.asn1.DEROctetString({hex: "04bac0"}); + * // initialize with ASN1Util.newObject argument for encapsulated + * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); + * // above generates a ASN.1 data like this: + * // BIT STRING, encapsulates { + * // SEQUENCE { + * // INTEGER 3 + * // PrintableString 'aaa' + * // } + * // } + */ + KJUR.asn1.DERBitString = function(params) { + if (params !== undefined && typeof params.obj !== "undefined") { + var o = KJUR.asn1.ASN1Util.newObject(params.obj); + params.hex = "00" + o.getEncodedHex(); + } + KJUR.asn1.DERBitString.superclass.constructor.call(this); + this.hT = "03"; + + /** + * set ASN.1 value(V) by a hexadecimal string including unused bits + * @name setHexValueIncludingUnusedBits + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {String} newHexStringIncludingUnusedBits + */ + this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) { + this.hTLV = null; + this.isModified = true; + this.hV = newHexStringIncludingUnusedBits; + }; + + /** + * set ASN.1 value(V) by unused bit and hexadecimal string of value + * @name setUnusedBitsAndHexValue + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {Integer} unusedBits + * @param {String} hValue + */ + this.setUnusedBitsAndHexValue = function(unusedBits, hValue) { + if (unusedBits < 0 || 7 < unusedBits) { + throw "unused bits shall be from 0 to 7: u = " + unusedBits; + } + var hUnusedBits = "0" + unusedBits; + this.hTLV = null; + this.isModified = true; + this.hV = hUnusedBits + hValue; + }; + + /** + * set ASN.1 DER BitString by binary string
+ * @name setByBinaryString + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {String} binaryString binary value string (i.e. '10111') + * @description + * Its unused bits will be calculated automatically by length of + * 'binaryValue'.
+ * NOTE: Trailing zeros '0' will be ignored. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.setByBooleanArray("01011"); + */ + this.setByBinaryString = function(binaryString) { + binaryString = binaryString.replace(/0+$/, ''); + var unusedBits = 8 - binaryString.length % 8; + if (unusedBits == 8) unusedBits = 0; + for (var i = 0; i <= unusedBits; i++) { + binaryString += '0'; + } + var h = ''; + for (var i = 0; i < binaryString.length - 1; i += 8) { + var b = binaryString.substr(i, 8); + var x = parseInt(b, 2).toString(16); + if (x.length == 1) x = '0' + x; + h += x; + } + this.hTLV = null; + this.isModified = true; + this.hV = '0' + unusedBits + h; + }; + + /** + * set ASN.1 TLV value(V) by an array of boolean
+ * @name setByBooleanArray + * @memberOf KJUR.asn1.DERBitString# + * @function + * @param {array} booleanArray array of boolean (ex. [true, false, true]) + * @description + * NOTE: Trailing falses will be ignored in the ASN.1 DER Object. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.setByBooleanArray([false, true, false, true, true]); + */ + this.setByBooleanArray = function(booleanArray) { + var s = ''; + for (var i = 0; i < booleanArray.length; i++) { + if (booleanArray[i] == true) { + s += '1'; + } else { + s += '0'; + } + } + this.setByBinaryString(s); + }; + + /** + * generate an array of falses with specified length
+ * @name newFalseArray + * @memberOf KJUR.asn1.DERBitString + * @function + * @param {Integer} nLength length of array to generate + * @return {array} array of boolean falses + * @description + * This static method may be useful to initialize boolean array. + * @example + * o = new KJUR.asn1.DERBitString(); + * o.newFalseArray(3) → [false, false, false] + */ + this.newFalseArray = function(nLength) { + var a = new Array(nLength); + for (var i = 0; i < nLength; i++) { + a[i] = false; + } + return a; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) { + this.setHexValueIncludingUnusedBits(params); + } else if (typeof params['hex'] != "undefined") { + this.setHexValueIncludingUnusedBits(params['hex']); + } else if (typeof params['bin'] != "undefined") { + this.setByBinaryString(params['bin']); + } else if (typeof params['array'] != "undefined") { + this.setByBooleanArray(params['array']); + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object); + + // ******************************************************************** + /** + * class for ASN.1 DER OctetString
+ * @name KJUR.asn1.DEROctetString + * @class class for ASN.1 DER OctetString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * This class provides ASN.1 OctetString simple type.
+ * Supported "params" attributes are: + *
    + *
  • str - to set a string as a value
  • + *
  • hex - to set a hexadecimal string as a value
  • + *
  • obj - to set a encapsulated ASN.1 value by JSON object + * which is defined in {@link KJUR.asn1.ASN1Util.newObject}
  • + *
+ * NOTE: A parameter 'obj' have been supported + * for "OCTET STRING, encapsulates" structure. + * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25). + * @see KJUR.asn1.DERAbstractString - superclass + * @example + * // default constructor + * o = new KJUR.asn1.DEROctetString(); + * // initialize with string + * o = new KJUR.asn1.DEROctetString({str: "aaa"}); + * // initialize with hexadecimal string + * o = new KJUR.asn1.DEROctetString({hex: "616161"}); + * // initialize with ASN1Util.newObject argument + * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}}); + * // above generates a ASN.1 data like this: + * // OCTET STRING, encapsulates { + * // SEQUENCE { + * // INTEGER 3 + * // PrintableString 'aaa' + * // } + * // } + */ + KJUR.asn1.DEROctetString = function(params) { + if (params !== undefined && typeof params.obj !== "undefined") { + var o = KJUR.asn1.ASN1Util.newObject(params.obj); + params.hex = o.getEncodedHex(); + } + KJUR.asn1.DEROctetString.superclass.constructor.call(this, params); + this.hT = "04"; + }; + YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString); + + // ******************************************************************** + /** + * class for ASN.1 DER Null + * @name KJUR.asn1.DERNull + * @class class for ASN.1 DER Null + * @extends KJUR.asn1.ASN1Object + * @description + * @see KJUR.asn1.ASN1Object - superclass + */ + KJUR.asn1.DERNull = function() { + KJUR.asn1.DERNull.superclass.constructor.call(this); + this.hT = "05"; + this.hTLV = "0500"; + }; + YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object); + + // ******************************************************************** + /** + * class for ASN.1 DER ObjectIdentifier + * @name KJUR.asn1.DERObjectIdentifier + * @class class for ASN.1 DER ObjectIdentifier + * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'}) + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * NOTE: 'params' can be omitted. + */ + KJUR.asn1.DERObjectIdentifier = function(params) { + var itox = function(i) { + var h = i.toString(16); + if (h.length == 1) h = '0' + h; + return h; + }; + var roidtox = function(roid) { + var h = ''; + var bi = new BigInteger(roid, 10); + var b = bi.toString(2); + var padLen = 7 - b.length % 7; + if (padLen == 7) padLen = 0; + var bPad = ''; + for (var i = 0; i < padLen; i++) bPad += '0'; + b = bPad + b; + for (var i = 0; i < b.length - 1; i += 7) { + var b8 = b.substr(i, 7); + if (i != b.length - 7) b8 = '1' + b8; + h += itox(parseInt(b8, 2)); + } + return h; + }; + + KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this); + this.hT = "06"; + + /** + * set value by a hexadecimal string + * @name setValueHex + * @memberOf KJUR.asn1.DERObjectIdentifier# + * @function + * @param {String} newHexString hexadecimal value of OID bytes + */ + this.setValueHex = function(newHexString) { + this.hTLV = null; + this.isModified = true; + this.s = null; + this.hV = newHexString; + }; + + /** + * set value by a OID string
+ * @name setValueOidString + * @memberOf KJUR.asn1.DERObjectIdentifier# + * @function + * @param {String} oidString OID string (ex. 2.5.4.13) + * @example + * o = new KJUR.asn1.DERObjectIdentifier(); + * o.setValueOidString("2.5.4.13"); + */ + this.setValueOidString = function(oidString) { + if (!oidString.match(/^[0-9.]+$/)) { + throw "malformed oid string: " + oidString; + } + var h = ''; + var a = oidString.split('.'); + var i0 = parseInt(a[0]) * 40 + parseInt(a[1]); + h += itox(i0); + a.splice(0, 2); + for (var i = 0; i < a.length; i++) { + h += roidtox(a[i]); + } + this.hTLV = null; + this.isModified = true; + this.s = null; + this.hV = h; + }; + + /** + * set value by a OID name + * @name setValueName + * @memberOf KJUR.asn1.DERObjectIdentifier# + * @function + * @param {String} oidName OID name (ex. 'serverAuth') + * @since 1.0.1 + * @description + * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'. + * Otherwise raise error. + * @example + * o = new KJUR.asn1.DERObjectIdentifier(); + * o.setValueName("serverAuth"); + */ + this.setValueName = function(oidName) { + var oid = KJUR.asn1.x509.OID.name2oid(oidName); + if (oid !== '') { + this.setValueOidString(oid); + } else { + throw "DERObjectIdentifier oidName undefined: " + oidName; + } + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (params !== undefined) { + if (typeof params === "string") { + if (params.match(/^[0-2].[0-9.]+$/)) { + this.setValueOidString(params); + } else { + this.setValueName(params); + } + } else if (params.oid !== undefined) { + this.setValueOidString(params.oid); + } else if (params.hex !== undefined) { + this.setValueHex(params.hex); + } else if (params.name !== undefined) { + this.setValueName(params.name); + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object); + + // ******************************************************************** + /** + * class for ASN.1 DER Enumerated + * @name KJUR.asn1.DEREnumerated + * @class class for ASN.1 DER Enumerated + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • int - specify initial ASN.1 value(V) by integer value
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
+ * NOTE: 'params' can be omitted. + * @example + * new KJUR.asn1.DEREnumerated(123); + * new KJUR.asn1.DEREnumerated({int: 123}); + * new KJUR.asn1.DEREnumerated({hex: '1fad'}); + */ + KJUR.asn1.DEREnumerated = function(params) { + KJUR.asn1.DEREnumerated.superclass.constructor.call(this); + this.hT = "0a"; + + /** + * set value by Tom Wu's BigInteger object + * @name setByBigInteger + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {BigInteger} bigIntegerValue to set + */ + this.setByBigInteger = function(bigIntegerValue) { + this.hTLV = null; + this.isModified = true; + this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue); + }; + + /** + * set value by integer value + * @name setByInteger + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {Integer} integer value to set + */ + this.setByInteger = function(intValue) { + var bi = new BigInteger(String(intValue), 10); + this.setByBigInteger(bi); + }; + + /** + * set value by integer value + * @name setValueHex + * @memberOf KJUR.asn1.DEREnumerated# + * @function + * @param {String} hexadecimal string of integer value + * @description + *
+ * NOTE: Value shall be represented by minimum octet length of + * two's complement representation. + */ + this.setValueHex = function(newHexString) { + this.hV = newHexString; + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['int'] != "undefined") { + this.setByInteger(params['int']); + } else if (typeof params == "number") { + this.setByInteger(params); + } else if (typeof params['hex'] != "undefined") { + this.setValueHex(params['hex']); + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object); + + // ******************************************************************** + /** + * class for ASN.1 DER UTF8String + * @name KJUR.asn1.DERUTF8String + * @class class for ASN.1 DER UTF8String + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ + KJUR.asn1.DERUTF8String = function(params) { + KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params); + this.hT = "0c"; + }; + YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString); + + // ******************************************************************** + /** + * class for ASN.1 DER NumericString + * @name KJUR.asn1.DERNumericString + * @class class for ASN.1 DER NumericString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ + KJUR.asn1.DERNumericString = function(params) { + KJUR.asn1.DERNumericString.superclass.constructor.call(this, params); + this.hT = "12"; + }; + YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString); + + // ******************************************************************** + /** + * class for ASN.1 DER PrintableString + * @name KJUR.asn1.DERPrintableString + * @class class for ASN.1 DER PrintableString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ + KJUR.asn1.DERPrintableString = function(params) { + KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params); + this.hT = "13"; + }; + YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString); + + // ******************************************************************** + /** + * class for ASN.1 DER TeletexString + * @name KJUR.asn1.DERTeletexString + * @class class for ASN.1 DER TeletexString + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ + KJUR.asn1.DERTeletexString = function(params) { + KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params); + this.hT = "14"; + }; + YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString); + + // ******************************************************************** + /** + * class for ASN.1 DER IA5String + * @name KJUR.asn1.DERIA5String + * @class class for ASN.1 DER IA5String + * @param {Array} params associative array of parameters (ex. {'str': 'aaa'}) + * @extends KJUR.asn1.DERAbstractString + * @description + * @see KJUR.asn1.DERAbstractString - superclass + */ + KJUR.asn1.DERIA5String = function(params) { + KJUR.asn1.DERIA5String.superclass.constructor.call(this, params); + this.hT = "16"; + }; + YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString); + + // ******************************************************************** + /** + * class for ASN.1 DER UTCTime + * @name KJUR.asn1.DERUTCTime + * @class class for ASN.1 DER UTCTime + * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'}) + * @extends KJUR.asn1.DERAbstractTime + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
  • date - specify Date object.
  • + *
+ * NOTE: 'params' can be omitted. + *

EXAMPLES

+ * @example + * d1 = new KJUR.asn1.DERUTCTime(); + * d1.setString('130430125959Z'); + * + * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'}); + * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))}); + * d4 = new KJUR.asn1.DERUTCTime('130430125959Z'); + */ + KJUR.asn1.DERUTCTime = function(params) { + KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params); + this.hT = "17"; + + /** + * set value by a Date object
+ * @name setByDate + * @memberOf KJUR.asn1.DERUTCTime# + * @function + * @param {Date} dateObject Date object to set ASN.1 value(V) + * @example + * o = new KJUR.asn1.DERUTCTime(); + * o.setByDate(new Date("2016/12/31")); + */ + this.setByDate = function(dateObject) { + this.hTLV = null; + this.isModified = true; + this.date = dateObject; + this.s = this.formatDate(this.date, 'utc'); + this.hV = stohex(this.s); + }; + + this.getFreshValueHex = function() { + if (typeof this.date == "undefined" && typeof this.s == "undefined") { + this.date = new Date(); + this.s = this.formatDate(this.date, 'utc'); + this.hV = stohex(this.s); + } + return this.hV; + }; + + if (params !== undefined) { + if (params.str !== undefined) { + this.setString(params.str); + } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) { + this.setString(params); + } else if (params.hex !== undefined) { + this.setStringHex(params.hex); + } else if (params.date !== undefined) { + this.setByDate(params.date); + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime); + + // ******************************************************************** + /** + * class for ASN.1 DER GeneralizedTime + * @name KJUR.asn1.DERGeneralizedTime + * @class class for ASN.1 DER GeneralizedTime + * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'}) + * @property {Boolean} withMillis flag to show milliseconds or not + * @extends KJUR.asn1.DERAbstractTime + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')
  • + *
  • hex - specify initial ASN.1 value(V) by a hexadecimal string
  • + *
  • date - specify Date object.
  • + *
  • millis - specify flag to show milliseconds (from 1.0.6)
  • + *
+ * NOTE1: 'params' can be omitted. + * NOTE2: 'withMillis' property is supported from asn1 1.0.6. + */ + KJUR.asn1.DERGeneralizedTime = function(params) { + KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params); + this.hT = "18"; + this.withMillis = false; + + /** + * set value by a Date object + * @name setByDate + * @memberOf KJUR.asn1.DERGeneralizedTime# + * @function + * @param {Date} dateObject Date object to set ASN.1 value(V) + * @example + * When you specify UTC time, use 'Date.UTC' method like this:
+ * o1 = new DERUTCTime(); + * o1.setByDate(date); + * + * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59 + */ + this.setByDate = function(dateObject) { + this.hTLV = null; + this.isModified = true; + this.date = dateObject; + this.s = this.formatDate(this.date, 'gen', this.withMillis); + this.hV = stohex(this.s); + }; + + this.getFreshValueHex = function() { + if (this.date === undefined && this.s === undefined) { + this.date = new Date(); + this.s = this.formatDate(this.date, 'gen', this.withMillis); + this.hV = stohex(this.s); + } + return this.hV; + }; + + if (params !== undefined) { + if (params.str !== undefined) { + this.setString(params.str); + } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) { + this.setString(params); + } else if (params.hex !== undefined) { + this.setStringHex(params.hex); + } else if (params.date !== undefined) { + this.setByDate(params.date); + } + if (params.millis === true) { + this.withMillis = true; + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime); + + // ******************************************************************** + /** + * class for ASN.1 DER Sequence + * @name KJUR.asn1.DERSequence + * @class class for ASN.1 DER Sequence + * @extends KJUR.asn1.DERAbstractStructured + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • array - specify array of ASN1Object to set elements of content
  • + *
+ * NOTE: 'params' can be omitted. + */ + KJUR.asn1.DERSequence = function(params) { + KJUR.asn1.DERSequence.superclass.constructor.call(this, params); + this.hT = "30"; + this.getFreshValueHex = function() { + var h = ''; + for (var i = 0; i < this.asn1Array.length; i++) { + var asn1Obj = this.asn1Array[i]; + h += asn1Obj.getEncodedHex(); + } + this.hV = h; + return this.hV; + }; + }; + YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured); + + // ******************************************************************** + /** + * class for ASN.1 DER Set + * @name KJUR.asn1.DERSet + * @class class for ASN.1 DER Set + * @extends KJUR.asn1.DERAbstractStructured + * @description + *
+ * As for argument 'params' for constructor, you can specify one of + * following properties: + *
    + *
  • array - specify array of ASN1Object to set elements of content
  • + *
  • sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.
  • + *
+ * NOTE1: 'params' can be omitted.
+ * NOTE2: sortflag is supported since 1.0.5. + */ + KJUR.asn1.DERSet = function(params) { + KJUR.asn1.DERSet.superclass.constructor.call(this, params); + this.hT = "31"; + this.sortFlag = true; // item shall be sorted only in ASN.1 DER + this.getFreshValueHex = function() { + var a = new Array(); + for (var i = 0; i < this.asn1Array.length; i++) { + var asn1Obj = this.asn1Array[i]; + a.push(asn1Obj.getEncodedHex()); + } + if (this.sortFlag == true) a.sort(); + this.hV = a.join(''); + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params.sortflag != "undefined" && + params.sortflag == false) + this.sortFlag = false; + } + }; + YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured); + + // ******************************************************************** + /** + * class for ASN.1 DER TaggedObject + * @name KJUR.asn1.DERTaggedObject + * @class class for ASN.1 DER TaggedObject + * @extends KJUR.asn1.ASN1Object + * @description + *
+ * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object. + * For example, if you find '[1]' tag in a ASN.1 dump, + * 'tagNoHex' will be 'a1'. + *
+ * As for optional argument 'params' for constructor, you can specify *ANY* of + * following properties: + *
    + *
  • explicit - specify true if this is explicit tag otherwise false + * (default is 'true').
  • + *
  • tag - specify tag (default is 'a0' which means [0])
  • + *
  • obj - specify ASN1Object which is tagged
  • + *
+ * @example + * d1 = new KJUR.asn1.DERUTF8String({'str':'a'}); + * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1}); + * hex = d2.getEncodedHex(); + */ + KJUR.asn1.DERTaggedObject = function(params) { + KJUR.asn1.DERTaggedObject.superclass.constructor.call(this); + this.hT = "a0"; + this.hV = ''; + this.isExplicit = true; + this.asn1Object = null; + + /** + * set value by an ASN1Object + * @name setString + * @memberOf KJUR.asn1.DERTaggedObject# + * @function + * @param {Boolean} isExplicitFlag flag for explicit/implicit tag + * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag + * @param {ASN1Object} asn1Object ASN.1 to encapsulate + */ + this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) { + this.hT = tagNoHex; + this.isExplicit = isExplicitFlag; + this.asn1Object = asn1Object; + if (this.isExplicit) { + this.hV = this.asn1Object.getEncodedHex(); + this.hTLV = null; + this.isModified = true; + } else { + this.hV = null; + this.hTLV = asn1Object.getEncodedHex(); + this.hTLV = this.hTLV.replace(/^../, tagNoHex); + this.isModified = false; + } + }; + + this.getFreshValueHex = function() { + return this.hV; + }; + + if (typeof params != "undefined") { + if (typeof params['tag'] != "undefined") { + this.hT = params['tag']; + } + if (typeof params['explicit'] != "undefined") { + this.isExplicit = params['explicit']; + } + if (typeof params['obj'] != "undefined") { + this.asn1Object = params['obj']; + this.setASN1Object(this.isExplicit, this.hT, this.asn1Object); + } + } + }; + YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object); + + /** + * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object. + * This object is just a decorator for parsing the key parameter + * @param {string|Object} key - The key in string format, or an object containing + * the parameters needed to build a RSAKey object. + * @constructor + */ + var JSEncryptRSAKey = /** @class */ (function(_super) { + __extends(JSEncryptRSAKey, _super); + + function JSEncryptRSAKey(key) { + var _this = _super.call(this) || this; + // Call the super constructor. + // RSAKey.call(this); + // If a key key was provided. + if (key) { + // If this is a string... + if (typeof key === "string") { + _this.parseKey(key); + } else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) || + JSEncryptRSAKey.hasPublicKeyProperty(key)) { + // Set the values for the key. + _this.parsePropertiesFrom(key); + } + } + return _this; + } + /** + * Method to parse a pem encoded string containing both a public or private key. + * The method will translate the pem encoded string in a der encoded string and + * will parse private key and public key parameters. This method accepts public key + * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1). + * + * @todo Check how many rsa formats use the same format of pkcs #1. + * + * The format is defined as: + * PublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * PublicKey BIT STRING + * } + * Where AlgorithmIdentifier is: + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm + * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) + * } + * and PublicKey is a SEQUENCE encapsulated in a BIT STRING + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * it's possible to examine the structure of the keys obtained from openssl using + * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/ + * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer + * @private + */ + JSEncryptRSAKey.prototype.parseKey = function(pem) { + try { + var modulus = 0; + var public_exponent = 0; + var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/; + var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem); + var asn1 = ASN1.decode(der); + // Fixes a bug with OpenSSL 1.0+ private keys + if (asn1.sub.length === 3) { + asn1 = asn1.sub[2].sub[0]; + } + if (asn1.sub.length === 9) { + // Parse the private key. + modulus = asn1.sub[1].getHexStringValue(); // bigint + this.n = parseBigInt(modulus, 16); + public_exponent = asn1.sub[2].getHexStringValue(); // int + this.e = parseInt(public_exponent, 16); + var private_exponent = asn1.sub[3].getHexStringValue(); // bigint + this.d = parseBigInt(private_exponent, 16); + var prime1 = asn1.sub[4].getHexStringValue(); // bigint + this.p = parseBigInt(prime1, 16); + var prime2 = asn1.sub[5].getHexStringValue(); // bigint + this.q = parseBigInt(prime2, 16); + var exponent1 = asn1.sub[6].getHexStringValue(); // bigint + this.dmp1 = parseBigInt(exponent1, 16); + var exponent2 = asn1.sub[7].getHexStringValue(); // bigint + this.dmq1 = parseBigInt(exponent2, 16); + var coefficient = asn1.sub[8].getHexStringValue(); // bigint + this.coeff = parseBigInt(coefficient, 16); + } else if (asn1.sub.length === 2) { + // Parse the public key. + var bit_string = asn1.sub[1]; + var sequence = bit_string.sub[0]; + modulus = sequence.sub[0].getHexStringValue(); + this.n = parseBigInt(modulus, 16); + public_exponent = sequence.sub[1].getHexStringValue(); + this.e = parseInt(public_exponent, 16); + } else { + return false; + } + return true; + } catch (ex) { + return false; + } + }; + /** + * Translate rsa parameters in a hex encoded string representing the rsa key. + * + * The translation follow the ASN.1 notation : + * RSAPrivateKey ::= SEQUENCE { + * version Version, + * modulus INTEGER, -- n + * publicExponent INTEGER, -- e + * privateExponent INTEGER, -- d + * prime1 INTEGER, -- p + * prime2 INTEGER, -- q + * exponent1 INTEGER, -- d mod (p1) + * exponent2 INTEGER, -- d mod (q-1) + * coefficient INTEGER, -- (inverse of q) mod p + * } + * @returns {string} DER Encoded String representing the rsa private key + * @private + */ + JSEncryptRSAKey.prototype.getPrivateBaseKey = function() { + var options = { + array: [ + new KJUR.asn1.DERInteger({ + int: 0 + }), + new KJUR.asn1.DERInteger({ + bigint: this.n + }), + new KJUR.asn1.DERInteger({ + int: this.e + }), + new KJUR.asn1.DERInteger({ + bigint: this.d + }), + new KJUR.asn1.DERInteger({ + bigint: this.p + }), + new KJUR.asn1.DERInteger({ + bigint: this.q + }), + new KJUR.asn1.DERInteger({ + bigint: this.dmp1 + }), + new KJUR.asn1.DERInteger({ + bigint: this.dmq1 + }), + new KJUR.asn1.DERInteger({ + bigint: this.coeff + }) + ] + }; + var seq = new KJUR.asn1.DERSequence(options); + return seq.getEncodedHex(); + }; + /** + * base64 (pem) encoded version of the DER encoded representation + * @returns {string} pem encoded representation without header and footer + * @public + */ + JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function() { + return hex2b64(this.getPrivateBaseKey()); + }; + /** + * Translate rsa parameters in a hex encoded string representing the rsa public key. + * The representation follow the ASN.1 notation : + * PublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * PublicKey BIT STRING + * } + * Where AlgorithmIdentifier is: + * AlgorithmIdentifier ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm + * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) + * } + * and PublicKey is a SEQUENCE encapsulated in a BIT STRING + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * @returns {string} DER Encoded String representing the rsa public key + * @private + */ + JSEncryptRSAKey.prototype.getPublicBaseKey = function() { + var first_sequence = new KJUR.asn1.DERSequence({ + array: [ + new KJUR.asn1.DERObjectIdentifier({ + oid: "1.2.840.113549.1.1.1" + }), + new KJUR.asn1.DERNull() + ] + }); + var second_sequence = new KJUR.asn1.DERSequence({ + array: [ + new KJUR.asn1.DERInteger({ + bigint: this.n + }), + new KJUR.asn1.DERInteger({ + int: this.e + }) + ] + }); + var bit_string = new KJUR.asn1.DERBitString({ + hex: "00" + second_sequence.getEncodedHex() + }); + var seq = new KJUR.asn1.DERSequence({ + array: [ + first_sequence, + bit_string + ] + }); + return seq.getEncodedHex(); + }; + /** + * base64 (pem) encoded version of the DER encoded representation + * @returns {string} pem encoded representation without header and footer + * @public + */ + JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function() { + return hex2b64(this.getPublicBaseKey()); + }; + /** + * wrap the string in block of width chars. The default value for rsa keys is 64 + * characters. + * @param {string} str the pem encoded string without header and footer + * @param {Number} [width=64] - the length the string has to be wrapped at + * @returns {string} + * @private + */ + JSEncryptRSAKey.wordwrap = function(str, width) { + width = width || 64; + if (!str) { + return str; + } + var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})"; + return str.match(RegExp(regex, "g")).join("\n"); + }; + /** + * Retrieve the pem encoded private key + * @returns {string} the pem encoded private key with header/footer + * @public + */ + JSEncryptRSAKey.prototype.getPrivateKey = function() { + var key = "-----BEGIN RSA PRIVATE KEY-----\n"; + key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n"; + key += "-----END RSA PRIVATE KEY-----"; + return key; + }; + /** + * Retrieve the pem encoded public key + * @returns {string} the pem encoded public key with header/footer + * @public + */ + JSEncryptRSAKey.prototype.getPublicKey = function() { + var key = "-----BEGIN PUBLIC KEY-----\n"; + key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n"; + key += "-----END PUBLIC KEY-----"; + return key; + }; + /** + * Check if the object contains the necessary parameters to populate the rsa modulus + * and public exponent parameters. + * @param {Object} [obj={}] - An object that may contain the two public key + * parameters + * @returns {boolean} true if the object contains both the modulus and the public exponent + * properties (n and e) + * @todo check for types of n and e. N should be a parseable bigInt object, E should + * be a parseable integer number + * @private + */ + JSEncryptRSAKey.hasPublicKeyProperty = function(obj) { + obj = obj || {}; + return (obj.hasOwnProperty("n") && + obj.hasOwnProperty("e")); + }; + /** + * Check if the object contains ALL the parameters of an RSA key. + * @param {Object} [obj={}] - An object that may contain nine rsa key + * parameters + * @returns {boolean} true if the object contains all the parameters needed + * @todo check for types of the parameters all the parameters but the public exponent + * should be parseable bigint objects, the public exponent should be a parseable integer number + * @private + */ + JSEncryptRSAKey.hasPrivateKeyProperty = function(obj) { + obj = obj || {}; + return (obj.hasOwnProperty("n") && + obj.hasOwnProperty("e") && + obj.hasOwnProperty("d") && + obj.hasOwnProperty("p") && + obj.hasOwnProperty("q") && + obj.hasOwnProperty("dmp1") && + obj.hasOwnProperty("dmq1") && + obj.hasOwnProperty("coeff")); + }; + /** + * Parse the properties of obj in the current rsa object. Obj should AT LEAST + * include the modulus and public exponent (n, e) parameters. + * @param {Object} obj - the object containing rsa parameters + * @private + */ + JSEncryptRSAKey.prototype.parsePropertiesFrom = function(obj) { + this.n = obj.n; + this.e = obj.e; + if (obj.hasOwnProperty("d")) { + this.d = obj.d; + this.p = obj.p; + this.q = obj.q; + this.dmp1 = obj.dmp1; + this.dmq1 = obj.dmq1; + this.coeff = obj.coeff; + } + }; + return JSEncryptRSAKey; + }(RSAKey)); + + /** + * + * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour + * possible parameters are: + * - default_key_size {number} default: 1024 the key size in bit + * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent + * - log {boolean} default: false whether log warn/error or not + * @constructor + */ + var JSEncrypt = /** @class */ (function() { + function JSEncrypt(options) { + options = options || {}; + this.default_key_size = parseInt(options.default_key_size, 10) || 1024; + this.default_public_exponent = options.default_public_exponent || + "010001"; // 65537 default openssl public exponent for rsa key type + this.log = options.log || false; + // The private and public key. + this.key = null; + } + /** + * Method to set the rsa key parameter (one method is enough to set both the public + * and the private key, since the private key contains the public key paramenters) + * Log a warning if logs are enabled + * @param {Object|string} key the pem encoded string or an object (with or without header/footer) + * @public + */ + JSEncrypt.prototype.setKey = function(key) { + if (this.log && this.key) { + console.warn("A key was already set, overriding existing."); + } + this.key = new JSEncryptRSAKey(key); + }; + /** + * Proxy method for setKey, for api compatibility + * @see setKey + * @public + */ + JSEncrypt.prototype.setPrivateKey = function(privkey) { + // Create the key. + this.setKey(privkey); + }; + /** + * Proxy method for setKey, for api compatibility + * @see setKey + * @public + */ + JSEncrypt.prototype.setPublicKey = function(pubkey) { + // Sets the public key. + this.setKey(pubkey); + }; + /** + * Proxy method for RSAKey object's decrypt, decrypt the string using the private + * components of the rsa key object. Note that if the object was not set will be created + * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor + * @param {string} str base64 encoded crypted string to decrypt + * @return {string} the decrypted string + * @public + */ + JSEncrypt.prototype.decrypt = function(str) { + // Return the decrypted string. + try { + return this.getKey().decrypt(b64tohex(str)); + } catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's encrypt, encrypt the string using the public + * components of the rsa key object. Note that if the object was not set will be created + * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor + * @param {string} str the string to encrypt + * @return {string} the encrypted string encoded in base64 + * @public + */ + JSEncrypt.prototype.encrypt = function(str) { + // Return the encrypted string. + try { + return hex2b64(this.getKey().encrypt(str)); + } catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's sign. + * @param {string} str the string to sign + * @param {function} digestMethod hash method + * @param {string} digestName the name of the hash algorithm + * @return {string} the signature encoded in base64 + * @public + */ + JSEncrypt.prototype.sign = function(str, digestMethod, digestName) { + // return the RSA signature of 'str' in 'hex' format. + try { + return hex2b64(this.getKey().sign(str, digestMethod, digestName)); + } catch (ex) { + return false; + } + }; + /** + * Proxy method for RSAKey object's verify. + * @param {string} str the string to verify + * @param {string} signature the signature encoded in base64 to compare the string to + * @param {function} digestMethod hash method + * @return {boolean} whether the data and signature match + * @public + */ + JSEncrypt.prototype.verify = function(str, signature, digestMethod) { + // Return the decrypted 'digest' of the signature. + try { + return this.getKey().verify(str, b64tohex(signature), digestMethod); + } catch (ex) { + return false; + } + }; + /** + * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object + * will be created and returned + * @param {callback} [cb] the callback to be called if we want the key to be generated + * in an async fashion + * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object + * @public + */ + JSEncrypt.prototype.getKey = function(cb) { + // Only create new if it does not exist. + if (!this.key) { + // Get a new private key. + this.key = new JSEncryptRSAKey(); + if (cb && {}.toString.call(cb) === "[object Function]") { + this.key.generateAsync(this.default_key_size, this.default_public_exponent, + cb); + return; + } + // Generate the key. + this.key.generate(this.default_key_size, this.default_public_exponent); + } + return this.key; + }; + /** + * Returns the pem encoded representation of the private key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the private key WITH header and footer + * @public + */ + JSEncrypt.prototype.getPrivateKey = function() { + // Return the private representation of this key. + return this.getKey().getPrivateKey(); + }; + /** + * Returns the pem encoded representation of the private key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the private key WITHOUT header and footer + * @public + */ + JSEncrypt.prototype.getPrivateKeyB64 = function() { + // Return the private representation of this key. + return this.getKey().getPrivateBaseKeyB64(); + }; + /** + * Returns the pem encoded representation of the public key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the public key WITH header and footer + * @public + */ + JSEncrypt.prototype.getPublicKey = function() { + // Return the private representation of this key. + return this.getKey().getPublicKey(); + }; + /** + * Returns the pem encoded representation of the public key + * If the key doesn't exists a new key will be created + * @returns {string} pem encoded representation of the public key WITHOUT header and footer + * @public + */ + JSEncrypt.prototype.getPublicKeyB64 = function() { + // Return the private representation of this key. + return this.getKey().getPublicBaseKeyB64(); + }; + JSEncrypt.version = "3.0.0-rc.1"; + return JSEncrypt; + }()); + + window2.JSEncrypt = JSEncrypt; + + exports.JSEncrypt = JSEncrypt; + exports.default = JSEncrypt; + + Object.defineProperty(exports, '__esModule', { + value: true + }); + +}))); diff --git a/utils/permission.js b/utils/permission.js new file mode 100644 index 0000000..d9249d9 --- /dev/null +++ b/utils/permission.js @@ -0,0 +1,245 @@ +/// null = 未请求,1 = 已允许,0 = 拒绝|受限, 2 = 系统未开启 + +var isIOS + +function album() { + var result = 0; + var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary"); + var authStatus = PHPhotoLibrary.authorizationStatus(); + if (authStatus === 0) { + result = null; + } else if (authStatus == 3) { + result = 1; + } else { + result = 0; + } + plus.ios.deleteObject(PHPhotoLibrary); + return result; +} + +function camera() { + var result = 0; + var AVCaptureDevice = plus.ios.import("AVCaptureDevice"); + var authStatus = AVCaptureDevice.authorizationStatusForMediaType('vide'); + if (authStatus === 0) { + result = null; + } else if (authStatus == 3) { + result = 1; + } else { + result = 0; + } + plus.ios.deleteObject(AVCaptureDevice); + return result; +} + +function location() { + var result = 0; + var cllocationManger = plus.ios.import("CLLocationManager"); + var enable = cllocationManger.locationServicesEnabled(); + var status = cllocationManger.authorizationStatus(); + if (!enable) { + result = 2; + } else if (status === 0) { + result = null; + } else if (status === 3 || status === 4) { + result = 1; + } else { + result = 0; + } + plus.ios.deleteObject(cllocationManger); + return result; +} + +function push() { + var result = 0; + var UIApplication = plus.ios.import("UIApplication"); + var app = UIApplication.sharedApplication(); + var enabledTypes = 0; + if (app.currentUserNotificationSettings) { + var settings = app.currentUserNotificationSettings(); + enabledTypes = settings.plusGetAttribute("types"); + if (enabledTypes == 0) { + result = 0; + console.log("推送权限没有开启"); + } else { + result = 1; + console.log("已经开启推送功能!") + } + plus.ios.deleteObject(settings); + } else { + enabledTypes = app.enabledRemoteNotificationTypes(); + if (enabledTypes == 0) { + result = 3; + console.log("推送权限没有开启!"); + } else { + result = 4; + console.log("已经开启推送功能!") + } + } + plus.ios.deleteObject(app); + plus.ios.deleteObject(UIApplication); + return result; +} + +function contact() { + var result = 0; + var CNContactStore = plus.ios.import("CNContactStore"); + var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0); + if (cnAuthStatus === 0) { + result = null; + } else if (cnAuthStatus == 3) { + result = 1; + } else { + result = 0; + } + plus.ios.deleteObject(CNContactStore); + return result; +} + +function record() { + var result = null; + var avaudiosession = plus.ios.import("AVAudioSession"); + var avaudio = avaudiosession.sharedInstance(); + var status = avaudio.recordPermission(); + console.log("permissionStatus:" + status); + if (status === 1970168948) { + result = null; + } else if (status === 1735552628) { + result = 1; + } else { + result = 0; + } + plus.ios.deleteObject(avaudiosession); + return result; +} + +function calendar() { + var result = null; + var EKEventStore = plus.ios.import("EKEventStore"); + var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0); + if (ekAuthStatus == 3) { + result = 1; + console.log("日历权限已经开启"); + } else { + console.log("日历权限没有开启"); + } + plus.ios.deleteObject(EKEventStore); + return result; +} + +function memo() { + var result = null; + var EKEventStore = plus.ios.import("EKEventStore"); + var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1); + if (ekAuthStatus == 3) { + result = 1; + console.log("备忘录权限已经开启"); + } else { + console.log("备忘录权限没有开启"); + } + plus.ios.deleteObject(EKEventStore); + return result; +} + + +function requestIOS(permissionID) { + return new Promise((resolve, reject) => { + switch (permissionID) { + case "push": + resolve(push()); + break; + case "location": + resolve(location()); + break; + case "record": + resolve(record()); + break; + case "camera": + resolve(camera()); + break; + case "album": + resolve(album()); + break; + case "contact": + resolve(contact()); + break; + case "calendar": + resolve(calendar()); + break; + case "memo": + resolve(memo()); + break; + default: + resolve(0); + break; + } + }); +} + +function requestAndroid(permissionID) { + return new Promise((resolve, reject) => { + plus.android.requestPermissions( + [permissionID], + function(resultObj) { + var result = 0; + for (var i = 0; i < resultObj.granted.length; i++) { + var grantedPermission = resultObj.granted[i]; + console.log('已获取的权限:' + grantedPermission); + result = 1 + } + for (var i = 0; i < resultObj.deniedPresent.length; i++) { + var deniedPresentPermission = resultObj.deniedPresent[i]; + console.log('拒绝本次申请的权限:' + deniedPresentPermission); + result = 0 + } + for (var i = 0; i < resultObj.deniedAlways.length; i++) { + var deniedAlwaysPermission = resultObj.deniedAlways[i]; + console.log('永久拒绝申请的权限:' + deniedAlwaysPermission); + result = -1 + } + resolve(result); + }, + function(error) { + console.log('result error: ' + error.message) + resolve({ + code: error.code, + message: error.message + }); + } + ); + }); +} + +function gotoAppPermissionSetting() { + if (permission.isIOS) { + var UIApplication = plus.ios.import("UIApplication"); + var application2 = UIApplication.sharedApplication(); + var NSURL2 = plus.ios.import("NSURL"); + var setting2 = NSURL2.URLWithString("app-settings:"); + application2.openURL(setting2); + plus.ios.deleteObject(setting2); + plus.ios.deleteObject(NSURL2); + plus.ios.deleteObject(application2); + } else { + var Intent = plus.android.importClass("android.content.Intent"); + var Settings = plus.android.importClass("android.provider.Settings"); + var Uri = plus.android.importClass("android.net.Uri"); + var mainActivity = plus.android.runtimeMainActivity(); + var intent = new Intent(); + intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); + var uri = Uri.fromParts("package", mainActivity.getPackageName(), null); + intent.setData(uri); + mainActivity.startActivity(intent); + } +} + +const permission = { + get isIOS(){ + return typeof isIOS === 'boolean' ? isIOS : (isIOS = uni.getSystemInfoSync().platform === 'ios') + }, + requestIOS: requestIOS, + requestAndroid: requestAndroid, + gotoAppSetting: gotoAppPermissionSetting +} + +export default permission diff --git a/utils/request.js b/utils/request.js new file mode 100644 index 0000000..c5b01e0 --- /dev/null +++ b/utils/request.js @@ -0,0 +1,127 @@ +// import qs from 'qs' // 处理data +import store from '@/vuex/store' +const request = (params) => { + let _self = this; + let url = params.url; + let method = params.method || 'POST'; + let data = params.data || {}; + // data.token = "default-access_token" + // if (!params.token) { + // let token = uni.getStorageSync('token'); + // if (!token) { + // uni.navigateTo({ + // url: '/pages/login/login' + // }); + // } else { + // data.token = '179509245-9c91827e0224bdc18d0b118b8be1b5af'; + // } + // } + let token = '' + if (store.getters.saveToken !== '') { + token = store.getters.saveToken + } + let defaultOpot = { + // 'Content-Type': 'application/x-www-form-urlencoded', + 'Terminal-Type': 'innerH5', + 'Content-Type': 'application/json;charset=UTF-8', + } + let header = {} + method = method.toUpperCase() + if (method == 'POST') { + header = { + 'Content-Type': 'application/json;charset=UTF-8', + 'Authorization': token + } + // data = qs.stringify(data) + } + const requestUrl = `${store.getters.baseUrl}/` + url; + uni.showLoading({ + title: '加载中...' + }); + return new Promise((resolve, reject) => { + uni.request({ + url: requestUrl, + method: method, + header: Object.assign({}, defaultOpot, header), + data: data, + dataType: 'json', + }) + .then(res => { // 成功 + if (res.length === 1) { + uni.showModal({ + content: 'request:fail', + showCancel: false + }) + reject('request:fail') + } else if (res[1] && res[1].statusCode === 400) { + uni.showModal({ + content: res[1].data.message, + showCancel: false + }) + reject(res[1].data.message) + } else if (res[1] && res[1].statusCode === 401) { + uni.showModal({ + content: res[1].data.message, + showCancel: false + }) + store.dispatch('delUserInfo') + uni.redirectTo({ + url: '/pages/login/login' + }) + } else if (res[1] && res[1].statusCode === 200) { + let { + data: dataType + } = res[1] + resolve(dataType) + // switch (dataType.code * 1) { // 拦截返回参数 + // case 0: + // resolve(dataType) + // break; + // case 1003: + // uni.showModal({ + // title: '登录已过期', + // content: '很抱歉,登录已过期,请重新登录', + // confirmText: '重新登录', + // success: function(res) { + // if (res.confirm) { + // uni.navigateTo({ + // // 切记这儿需要哈pages.json保持一致;不能有.vue后缀 + // url: '/pages/login/login' + // }); + // } else if (res.cancel) { + // console.log('用户点击取消'); + // } + // } + // }) + // break; + // case -1: + // uni.showModal({ + // title: '请求数据失败', + // content: '获取数据失败!', + // confirmText: '确定', + // showCancel: false, + // success: function(res) { + // if (res.confirm) {} else if (res.cancel) { + // console.log('用户点击取消'); + // } + // } + // }) + // break + // } + }else { + uni.showModal({ + content: res[1].data.message, + showCancel: false + }) + reject(res[1].data.message) + } + }) + .catch(err => { // 错误 + reject(err) + }) + .finally(() => { + uni.hideLoading(); + }) + }) +} +export default request \ No newline at end of file diff --git a/utils/request1.js b/utils/request1.js new file mode 100644 index 0000000..90dbecf --- /dev/null +++ b/utils/request1.js @@ -0,0 +1,126 @@ +import store from '@/vuex/store' +const request1 = (params) => { + let _self = this; + let url = params.url; + let method = params.method || 'POST'; + let data = params.data || {}; + // data.token = "default-access_token" + // if (!params.token) { + // let token = uni.getStorageSync('token'); + // if (!token) { + // uni.navigateTo({ + // url: '/pages/login/login' + // }); + // } else { + // data.token = '179509245-9c91827e0224bdc18d0b118b8be1b5af'; + // } + // } + let token = '' + if (store.getters.saveToken !== '') { + token = store.getters.saveToken + } + let defaultOpot = { + // 'Content-Type': 'application/x-www-form-urlencoded', + 'Terminal-Type': 'innerH5', + 'Content-Type': 'application/json;charset=UTF-8', + } + let header = {} + method = method.toUpperCase() + if (method == 'POST') { + header = { + 'Content-Type': 'application/json;charset=UTF-8', + 'Authorization': token + } + // data = qs.stringify(data) + } + const requestUrl = url; + uni.showLoading({ + title: '加载中...' + }); + return new Promise((resolve, reject) => { + uni.request({ + url: requestUrl, + method: method, + header: Object.assign({}, defaultOpot, header), + data: data, + dataType: 'json', + }) + .then(res => { // 成功 + if (res.length === 1) { + uni.showModal({ + content: 'request:fail', + showCancel: false + }) + reject('request:fail') + } else if (res[1] && res[1].statusCode === 400) { + uni.showModal({ + content: res[1].data.message, + showCancel: false + }) + reject(res[1].data.message) + } else if (res[1] && res[1].statusCode === 401) { + uni.showModal({ + content: res[1].data.message, + showCancel: false + }) + store.dispatch('delUserInfo') + uni.redirectTo({ + url: '/pages/login/login' + }) + } else if (res[1] && res[1].statusCode === 200) { + let { + data: dataType + } = res[1] + resolve(dataType) + // switch (dataType.code * 1) { // 拦截返回参数 + // case 0: + // resolve(dataType) + // break; + // case 1003: + // uni.showModal({ + // title: '登录已过期', + // content: '很抱歉,登录已过期,请重新登录', + // confirmText: '重新登录', + // success: function(res) { + // if (res.confirm) { + // uni.navigateTo({ + // // 切记这儿需要哈pages.json保持一致;不能有.vue后缀 + // url: '/pages/login/login' + // }); + // } else if (res.cancel) { + // console.log('用户点击取消'); + // } + // } + // }) + // break; + // case -1: + // uni.showModal({ + // title: '请求数据失败', + // content: '获取数据失败!', + // confirmText: '确定', + // showCancel: false, + // success: function(res) { + // if (res.confirm) {} else if (res.cancel) { + // console.log('用户点击取消'); + // } + // } + // }) + // break + // } + }else { + uni.showModal({ + content: res[1].data.message, + showCancel: false + }) + reject(res[1].data.message) + } + }) + .catch(err => { // 错误 + reject(err) + }) + .finally(() => { + uni.hideLoading(); + }) + }) +} +export default request1 \ No newline at end of file diff --git a/vuex/modules/user.js b/vuex/modules/user.js new file mode 100644 index 0000000..a06b086 --- /dev/null +++ b/vuex/modules/user.js @@ -0,0 +1,77 @@ +import * as types from '../types' + +const baseUrl = process.env.NODE_ENV === 'development' ? 'http://10.1.3.90:8010' : 'http://10.1.3.90:8010' +const state = { + baseUrl: uni.getStorageSync('baseUrl') || baseUrl, + setTime: uni.getStorageSync('setTime') || 5000, + setPrintName: uni.getStorageSync('setPrintName') || '', + loginName: uni.getStorageSync('loginName') ? uni.getStorageSync('loginName') : '', + userInfo: uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo') : '', + saveToken: uni.getStorageSync('saveToken') || '' +} +const getters = { + baseUrl: state => state.baseUrl, + setTime: state => state.setTime, + setPrintName: state => state.setPrintName, + loginName: state => state.loginName, + userInfo: state => state.userInfo, + saveToken: state => state.saveToken +} +const actions = { + setConfig ({commit}, res) { + uni.setStorageSync('baseUrl', res.baseUrl) + uni.setStorageSync('setTime', res.setTime) + uni.setStorageSync('setPrintName', res.setPrintName) + commit(types.COM_CONFIG, res) + }, + saveLoginName({commit}, res) { + uni.setStorageSync('loginName', res) + commit(types.SAVE_LOGIN_NAME, res) + }, + delLoginName({commit}, res) { + uni.clearStorageSync('loginName') + commit(types.DEL_LOGIN_NAME, res) + }, + saveUserInfo({commit}, res) { + uni.setStorageSync('userInfo', res) + commit(types.SAVE_USER_INFO, res) + }, + delUserInfo({commit}, res) { + uni.removeStorageSync('userInfo') + uni.removeStorageSync('saveToken') + commit(types.DEL_USER_INFO, res) + }, + saveToken({commit}, res) { + uni.setStorageSync('saveToken', res) + commit(types.SAVE_TOKEN, res) + } +} +const mutations = { + [types.COM_CONFIG] (state, res) { + state.baseUrl = res.baseUrl + state.setTime = res.setTime + state.setPrintName = res.setPrintName + }, + [types.SAVE_LOGIN_NAME] (state, res) { + state.loginName = res + }, + [types.DEL_LOGIN_NAME] (state, res) { + state.loginName = res + }, + [types.SAVE_USER_INFO] (state, res) { + state.userInfo = res + }, + [types.DEL_USER_INFO] (state, res) { + state.userInfo = res + }, + [types.SAVE_TOKEN] (state, res) { + state.saveToken = res + } +} + +export default { + state, + getters, + actions, + mutations +} \ No newline at end of file diff --git a/vuex/store.js b/vuex/store.js new file mode 100644 index 0000000..095161f --- /dev/null +++ b/vuex/store.js @@ -0,0 +1,12 @@ +import Vue from 'vue' +import Vuex from 'vuex' + +import user from './modules/user' + +Vue.use(Vuex) + +export default new Vuex.Store({ + modules: { + user + } +}) diff --git a/vuex/types.js b/vuex/types.js new file mode 100644 index 0000000..4668940 --- /dev/null +++ b/vuex/types.js @@ -0,0 +1,9 @@ +/** + * user + */ +export const SAVE_LOGIN_NAME = 'SAVE_LOGIN_NAME' +export const DEL_LOGIN_NAME = 'DEL_LOGIN_NAME' +export const COM_CONFIG = 'COM_CONFIG' +export const SAVE_USER_INFO = 'SAVE_USER_INFO' +export const DEL_USER_INFO = 'DEL_USER_INFO' +export const SAVE_TOKEN = 'SAVE_TOKEN' \ No newline at end of file diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..9370773 --- /dev/null +++ b/yarn.lock @@ -0,0 +1,8 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +jsencrypt@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/jsencrypt/-/jsencrypt-3.2.1.tgz#09766983cc760088ff26b12fe7e574252af97727" + integrity sha512-k1sD5QV0KPn+D8uG9AdGzTQuamt82QZ3A3l6f7TRwMU6Oi2Vg0BsL+wZIQBONcraO1pc78ExMdvmBBJ8WhNYUA==