diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 126d5a34..263d36c5 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -34,6 +34,135 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+### [1.3.45](https://github.com/novlan1/t-comm/compare/v1.3.44...v1.3.45) (2023-12-21)
+
+
+### Code Refactoring ♻️
+
+* **img:** 拆分compress img ([bd7be32](https://github.com/novlan1/t-comm/commit/bd7be32893ead1ea7867491a005107534f45a22a))
+* **img:** 拆分compress img ([6c616a0](https://github.com/novlan1/t-comm/commit/6c616a0c7a6cc5d89d954a6413e58092faf850e1))
+
+
+### Features 🎉
+
+* **number:** add number ([f305e95](https://github.com/novlan1/t-comm/commit/f305e95099d841405f90ce94e9977de9d74d177d))
+
+### [1.3.44](https://github.com/novlan1/t-comm/compare/v1.3.43...v1.3.44) (2023-12-20)
+
+
+### Documentation 📖
+
+* update docs ([13ec46e](https://github.com/novlan1/t-comm/commit/13ec46e459deeed3effbf618760d82ac25f41740))
+
+
+### Chore 🚀
+
+* ts配置更新 ([ad70939](https://github.com/novlan1/t-comm/commit/ad709391906d406aed87c1d1292528657b1c2736))
+* update ts config ([222e0c0](https://github.com/novlan1/t-comm/commit/222e0c076863ef30695c895940af73ded69af7be))
+
+### [1.3.43](https://github.com/novlan1/t-comm/compare/v1.3.42...v1.3.43) (2023-12-19)
+
+
+### Features 🎉
+
+* **pad-zero:** add pad zero ([1a62a87](https://github.com/novlan1/t-comm/commit/1a62a87f86e96734e73db9f4f69e2bce8a585a7a))
+
+
+### Code Refactoring ♻️
+
+* 补充ts类型 ([1e2d63d](https://github.com/novlan1/t-comm/commit/1e2d63d8a1ba9bba8814e148c137b7f62a5abd54))
+* 补充ts类型 ([dc4b7d5](https://github.com/novlan1/t-comm/commit/dc4b7d58e31f1824f7ce4cc5d0da802bcabfdaec))
+* 补充ts类型 ([c3f56e7](https://github.com/novlan1/t-comm/commit/c3f56e7bfd2f8abb307099e510f85aa9536f676c))
+* 补充ts类型 ([eb35f2d](https://github.com/novlan1/t-comm/commit/eb35f2d57107a967c0f025e3cf36034fd078cd58))
+
+
+### Tests ✅
+
+* update test cases ([847cb39](https://github.com/novlan1/t-comm/commit/847cb3989efeaf1cfe4b93e48a182cabbd9a8355))
+
+### [1.3.42](https://github.com/novlan1/t-comm/compare/v1.3.41...v1.3.42) (2023-12-15)
+
+
+### Code Refactoring ♻️
+
+* **fs:** use writeFile and readFile of fs module ([602112b](https://github.com/novlan1/t-comm/commit/602112b76683a22aa23e9366f399d769ca07e1a5))
+
+
+### Features 🎉
+
+* **date:** add is same day ([3eb79ae](https://github.com/novlan1/t-comm/commit/3eb79aea1ce4a6b6485b53227f16051d7ee13044))
+
+### [1.3.41](https://github.com/novlan1/t-comm/compare/v1.3.40...v1.3.41) (2023-12-14)
+
+
+### Features 🎉
+
+* **polling:** add polling request ([feaea44](https://github.com/novlan1/t-comm/commit/feaea443a403125b215483a8a3a82d6515871c16))
+
+### [1.3.40](https://github.com/novlan1/t-comm/compare/v1.3.39...v1.3.40) (2023-12-12)
+
+
+### Features 🎉
+
+* **path:** add normalize path ([a36016e](https://github.com/novlan1/t-comm/commit/a36016e956e5a421c33d9b9b88bb23e3b9105d99))
+
+### [1.3.39](https://github.com/novlan1/t-comm/compare/v1.3.39-beta.0...v1.3.39) (2023-12-12)
+
+
+### Features 🎉
+
+* **fs:** add readyfileSync writeFileSync ([761b5f2](https://github.com/novlan1/t-comm/commit/761b5f27617a19dbd03a850493172944efc3bc26))
+* **msdk:** add set full screen and reset full screen ([03d2842](https://github.com/novlan1/t-comm/commit/03d2842fad0915e3865df5e0b8b293c28c9ee9e7))
+* **tag:** add getPreReleaseTag ([eca0cf5](https://github.com/novlan1/t-comm/commit/eca0cf541662c16b623cefdfb2da2c230a9697bf))
+
+### [1.3.39-beta.0](https://github.com/novlan1/t-comm/compare/v1.3.38...v1.3.39-beta.0) (2023-11-30)
+
+### [1.3.38](https://github.com/novlan1/t-comm/compare/v1.3.37...v1.3.38) (2023-11-30)
+
+
+### Bug Fixes 🐞
+
+* update insert change log ([eaf15ff](https://github.com/novlan1/t-comm/commit/eaf15ff9160987403bc16b856c6776c09d3d7ddc))
+
+### [1.3.37](https://github.com/novlan1/t-comm/compare/v1.3.37-beta.0...v1.3.37) (2023-11-30)
+
+
+### Features 🎉
+
+* **inset-doc-change-log:** add insert doc change log ([445b8c9](https://github.com/novlan1/t-comm/commit/445b8c9239b1969c4f49a9623d552a50e251c503))
+
+### [1.3.37-beta.0](https://github.com/novlan1/t-comm/compare/v1.3.37-alpha.0...v1.3.37-beta.0) (2023-11-30)
+
+
+### Chore 🚀
+
+* update scripts ([682bc6b](https://github.com/novlan1/t-comm/commit/682bc6b5d0a46f53c2a94a8a61d613b4abb8bb16))
+
+### [1.3.37-alpha.0](https://github.com/novlan1/t-comm/compare/v1.3.36...v1.3.37-alpha.0) (2023-11-30)
+
+
+### Documentation 📖
+
+* update docs ([d939363](https://github.com/novlan1/t-comm/commit/d939363e0016c99d526c19174d32a30f90ce20a7))
+
+
+### Chore 🚀
+
+* update change log ([d9e2bc2](https://github.com/novlan1/t-comm/commit/d9e2bc25cfe97f7c879e80631f076d53a1a2294c))
+* update docs ([cc00439](https://github.com/novlan1/t-comm/commit/cc004393381727b1d2ce76c8486e00c528f44d03))
### [1.3.36](https://github.com/novlan1/t-comm/compare/v1.3.35...v1.3.36) (2023-11-29)
diff --git a/docs/zh/base/number.md b/docs/zh/base/number.md
index 2fad5518..73748406 100644
--- a/docs/zh/base/number.md
+++ b/docs/zh/base/number.md
@@ -9,7 +9,10 @@ import {
getPartRatio,
getThousandSeparator,
getThousandSeparator2,
- random
+ random,
+ padZero,
+ addNumber,
+ range
} from 't-comm';
// or
@@ -20,7 +23,10 @@ import {
getPartRatio,
getThousandSeparator,
getThousandSeparator2,
- random
+ random,
+ padZero,
+ addNumber,
+ range
} from 't-comm/lib/base/number/index';
```
@@ -178,3 +184,76 @@ getThousandSeparator2('12345678 123456789')
```ts
random(0, 19) // 1
```
+
+
+## `padZero(num, [targetLength])`
+
+
+**描述**:
数字左侧加 0,直到满足长度要求
+
+**参数**:
+
+
+| 参数名 | 类型 | 默认值 | 描述 |
+| --- | --- | --- | --- |
+| num | string
\| number
| | 当前数字
|
+| [targetLength] | number
| 2
| 目标长度
|
+
+**返回**: string
+
+新的字符串
+
+**示例**
+
+```ts
+padZero(1, 3); // 001
+```
+
+
+## `addNumber(num1, num2)`
+
+
+**描述**:add num and avoid float number
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| num1 | number
| 第1个数字
|
+| num2 | number
| 第2个数字
|
+
+**返回**: number
+
+结果
+
+**示例**
+
+```ts
+addNumber(0.1, 0.2); // 0.3
+```
+
+
+## `range(num, min, max)`
+
+
+**描述**:根据边界值修正数字
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| num | number
| 待处理的数字
|
+| min | number
| 边界最小值
|
+| max | number
| 边界最大值
|
+
+**返回**: number
+
+处理结果
+
+**示例**
+
+```ts
+range(12, 1, 2); // 2
+```
diff --git a/docs/zh/base/regexp.md b/docs/zh/base/regexp.md
index fffb57a8..dc1f966d 100644
--- a/docs/zh/base/regexp.md
+++ b/docs/zh/base/regexp.md
@@ -3,11 +3,11 @@
## 引入方式
```ts
-import { getMatchListFromReg } from 't-comm';
+import { getMatchListFromReg, getPreReleaseTag } from 't-comm';
// or
-import { getMatchListFromReg} from 't-comm/lib/base/regexp/index';
+import { getMatchListFromReg, getPreReleaseTag} from 't-comm/lib/base/regexp/index';
```
@@ -33,3 +33,25 @@ getMatchListFromReg(content, /emit\('([^',]+)'/g);
// ['start', 'end']
```
+
+
+## `getPreReleaseTag(version)`
+
+
+**描述**:获取预发布版本标签,比如 alpha, beta
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| version | string
| 版本号
|
+
+**返回**: 标签
+
+**示例**
+
+```ts
+getPreReleaseTag('1.2.2-beta.0')
+// beta
+```
diff --git a/docs/zh/change-log.md b/docs/zh/change-log.md
new file mode 100644
index 00000000..0007f6a5
--- /dev/null
+++ b/docs/zh/change-log.md
@@ -0,0 +1,42 @@
+[[toc]]
+
+## 引入方式
+
+```ts
+import { insertDocChangeLog } from 't-comm';
+
+// or
+
+import { insertDocChangeLog} from 't-comm/lib/change-log/index';
+```
+
+
+## `insertDocChangeLog(params)`
+
+
+**描述**:同步最新版本的更新日志
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| params | object
| 参数
|
+| params.changelogPath | string
| 源 change-log路径
|
+| params.docChangelogPath | string
| 文档 change-log 路径
|
+| params.packageJsonPath | string
| package.json 路径
|
+
+
+
+**示例**
+
+```ts
+const DOC_CHANGE_LOG_PATH = './docs/CHANGELOG.md';
+const SOURCE_CHANGE_LOG_PATH = './CHANGELOG.md';
+
+insertDocChangeLog({
+ changelogPath: SOURCE_CHANGE_LOG_PATH,
+ docChangeLog: DOC_CHANGE_LOG_PATH,
+ packageJsonPath: './package.json',
+});
+```
diff --git a/docs/zh/date.md b/docs/zh/date.md
index 937b1529..9a0c7c46 100644
--- a/docs/zh/date.md
+++ b/docs/zh/date.md
@@ -7,6 +7,7 @@ import {
getMonthDay,
getMonthDay2,
isSameWeek,
+ isSameDay,
parseTime,
getTimeAgo,
getTimeAgoOrDate,
@@ -21,6 +22,7 @@ import {
getMonthDay,
getMonthDay2,
isSameWeek,
+ isSameDay,
parseTime,
getTimeAgo,
getTimeAgoOrDate,
@@ -122,6 +124,28 @@ isSameWeek(1601308800000, 1601913600000)
// false
```
+
+
+## `isSameDay(date1, date2)`
+
+
+**描述**:判断是否是同一天
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| date1 | number
| 时间戳
|
+| date2 | number
| 时间戳
|
+
+**返回**: 是否相同
+
+**示例**
+
+```ts
+isSameDay(1702613769418, 1702613769419) // true
+```
## `parseTime(time, cFormat)`
diff --git a/docs/zh/fs.md b/docs/zh/fs.md
new file mode 100644
index 00000000..3885e4fb
--- /dev/null
+++ b/docs/zh/fs.md
@@ -0,0 +1,62 @@
+[[toc]]
+
+## 引入方式
+
+```ts
+import { writeFileSync, readFileSync } from 't-comm';
+
+// or
+
+import { writeFileSync, readFileSync} from 't-comm/lib/fs/index';
+```
+
+
+## `writeFileSync(file, data, [isJson])`
+
+
+**描述**:写入文件
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| file | string
| 文件地址
|
+| data | any
| 文件数据
|
+| [isJson] | boolean
| 是否需要 json 序列化
|
+
+
+
+**示例**
+
+```ts
+writeFileSync('a', 'b.txt', false);
+
+writeFileSync({ a: 1 }, 'b.json', true);
+```
+
+
+## `readFileSync(file, [isJson])`
+
+
+**描述**:读取文件
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| file | string
| 文件地址
|
+| [isJson] | boolean
| 是否需要 json 反序列化
|
+
+**返回**: any
+
+文件内容
+
+**示例**
+
+```ts
+readFileSync('b.txt', false);
+
+readFileSync('b.json', true);
+```
diff --git a/docs/zh/image.md b/docs/zh/image.md
index c5082ccc..413273f7 100644
--- a/docs/zh/image.md
+++ b/docs/zh/image.md
@@ -6,10 +6,10 @@
import {
handleImgUnit,
getHttpsUrl,
- getCdnUrl,
- getCompressImgUrl,
tinyImage,
- isSupportedWebp
+ isSupportedWebp,
+ getCdnUrl,
+ getCompressImgUrl
} from 't-comm';
// or
@@ -17,10 +17,10 @@ import {
import {
handleImgUnit,
getHttpsUrl,
- getCdnUrl,
- getCompressImgUrl,
tinyImage,
- isSupportedWebp
+ isSupportedWebp,
+ getCdnUrl,
+ getCompressImgUrl
} from 't-comm/lib/image/index';
```
@@ -77,68 +77,68 @@ handleImgUnit('5rem')
**返回**: 新的地址
-
+
-## `getCdnUrl`
+## `tinyImage`
-**描述**:获取 cdn 链接
+**描述**:压缩图片,会依次执行 getHttpsUrl, getCdnUrl, getCompressImgUrl
**参数**:
-| 参数名 | 类型 | 描述 |
-| --- | --- | --- |
-| url | string
| 图片地址
|
+| 参数名 | 类型 | 默认值 | 描述 |
+| --- | --- | --- | --- |
+| url | string
| | 图片地址
|
+| [imageWidth] | number
| 0
| 宽度
|
+| [imageHeight] | number
| 0
| 高度
|
-**返回**: 新的地址
+**返回**: 新的 url 地址
-
+
-## `getCompressImgUrl`
+## `isSupportedWebp`
-**描述**:获取压缩后的图片
+**描述**:判断当前浏览器是否支持 webp
**参数**:
+**返回**: Promise.<boolean>
-| 参数名 | 类型 | 默认值 | 描述 |
-| --- | --- | --- | --- |
-| url | string
| | 图片地址
|
-| [imageWidth] | number
| 0
| 宽度
|
-| [imageHeight] | number
| 0
| 高度
|
-
-**返回**: 新的 url 地址
+是否支持
-
+
-## `tinyImage`
+## `getCdnUrl(url)`
-**描述**:压缩图片,会依次执行 getHttpsUrl, getCdnUrl, getCompressImgUrl
+**描述**:获取 cdn 链接
**参数**:
-| 参数名 | 类型 | 默认值 | 描述 |
-| --- | --- | --- | --- |
-| url | string
| | 图片地址
|
-| [imageWidth] | number
| 0
| 宽度
|
-| [imageHeight] | number
| 0
| 高度
|
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| url | string
| 图片地址
|
-**返回**: 新的 url 地址
+**返回**: 新的地址
-
+
-## `isSupportedWebp`
+## `getCompressImgUrl(url, [imageWidth], [imageHeight])`
-**描述**:判断当前浏览器是否支持 webp
+**描述**:获取压缩后的图片
**参数**:
-**返回**: Promise.<boolean>
-是否支持
+| 参数名 | 类型 | 默认值 | 描述 |
+| --- | --- | --- | --- |
+| url | string
| | 图片地址
|
+| [imageWidth] | number
| 0
| 宽度
|
+| [imageHeight] | number
| 0
| 高度
|
+
+**返回**: 新的 url 地址
diff --git a/docs/zh/mixin.md b/docs/zh/mixin.md
new file mode 100644
index 00000000..ee9ce070
--- /dev/null
+++ b/docs/zh/mixin.md
@@ -0,0 +1,36 @@
+[[toc]]
+
+## 引入方式
+
+```ts
+import { getMorsePwdMixin } from 't-comm';
+
+// or
+
+import { getMorsePwdMixin} from 't-comm/lib/mixin/index';
+```
+
+
+## `getMorsePwdMixin`
+
+
+**描述**:摩斯密码的 Vue mixin,方便实用
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| pwd | array
| 密钥
|
+| cb | function
| 回到函数
|
+
+**返回**: 换入内容
+
+**示例**
+
+```ts
+getMorsePwdMixin([1, 1, 1, 1, 1], function () {
+ if (isInIFrame()) return;
+ this.onShowLaunchApp();
+}),
+```
diff --git a/docs/zh/msdk.md b/docs/zh/msdk.md
index f8c247c9..cfa6cae2 100644
--- a/docs/zh/msdk.md
+++ b/docs/zh/msdk.md
@@ -3,14 +3,114 @@
## 引入方式
```ts
-import { callJsBrowserAdapter } from 't-comm';
+import {
+ callJsReSetFullScreen,
+ callJsSetFullScreen,
+ sendToMsdkNative,
+ closeMsdkWebview,
+ closeWebView,
+ callJsBrowserAdapter
+} from 't-comm';
// or
-import { callJsBrowserAdapter} from 't-comm/lib/msdk/index';
+import {
+ callJsReSetFullScreen,
+ callJsSetFullScreen,
+ sendToMsdkNative,
+ closeMsdkWebview,
+ closeWebView,
+ callJsBrowserAdapter
+} from 't-comm/lib/msdk/index';
```
+## `callJsReSetFullScreen`
+
+
+**描述**:设置 MSDK 浏览器退出全屏,需提前加载 sdk
+
+**参数**:
+
+
+
+**示例**
+
+```ts
+callJsReSetFullScreen();
+```
+
+
+## `callJsSetFullScreen`
+
+
+**描述**:设置 MSDK 浏览器全屏,需提前加载 sdk
+
+**参数**:
+
+
+| 参数名 | 描述 |
+| --- | --- |
+| isFullScreen | 是否全屏
|
+
+
+
+**示例**
+
+```ts
+callJsSetFullScreen();
+callJsSetFullScreen(false);
+```
+
+
+## `sendToMsdkNative(data)`
+
+
+**描述**:MSDK 浏览器中,向原生发送数据
+
+**参数**:
+
+
+| 参数名 | 类型 | 描述 |
+| --- | --- | --- |
+| data | string
| 发送的数据
sendToMsdkNative('123')
|
+
+
+
+
+
+## `closeMsdkWebview()`
+
+
+**描述**:MSDK 浏览器中,关闭 webView
+
+**参数**:
+
+
+
+**示例**
+
+```ts
+closeMsdkWebview()
+```
+
+
+## `closeWebView()`
+
+
+**描述**:关闭 webView,包含 msdk 浏览器和其他浏览器
+
+**参数**:
+
+
+
+**示例**
+
+```ts
+closeWebView()
+```
+
+
## `callJsBrowserAdapter()`
@@ -20,3 +120,8 @@ import { callJsBrowserAdapter} from 't-comm/lib/msdk/index';
+**示例**
+
+```ts
+callJsBrowserAdapter();
+```
diff --git a/docs/zh/path.md b/docs/zh/path.md
new file mode 100644
index 00000000..602bb93a
--- /dev/null
+++ b/docs/zh/path.md
@@ -0,0 +1,34 @@
+[[toc]]
+
+## 引入方式
+
+```ts
+import { normalizePath } from 't-comm';
+
+// or
+
+import { normalizePath} from 't-comm/lib/path/index';
+```
+
+
+## `normalizePath`
+
+
+**描述**:格式化路径
+
+**参数**:
+
+
+| 参数名 | 描述 |
+| --- | --- |
+| path | 文件路径,或目录路径
|
+
+**返回**: 格式化后的路径
+
+**示例**
+
+```ts
+normalizePath('xxx/xxx/xxx');
+
+normalizePath('xxx\\xxx\\xxx');
+```
diff --git a/docs/zh/polling.md b/docs/zh/polling.md
new file mode 100644
index 00000000..329da71f
--- /dev/null
+++ b/docs/zh/polling.md
@@ -0,0 +1,62 @@
+[[toc]]
+
+## 引入方式
+
+```ts
+import { PollingRequest } from 't-comm';
+
+// or
+
+import { PollingRequest } from 't-comm/lib/polling/index';
+```
+
+
+## PollingRequest
+
+
+**参数**:
+
+
+
+
+* [PollingRequest](#PollingRequest)
+ * [`new PollingRequest([maxPollingTime], [timeInterval])`](#new_PollingRequest_new)
+ * [`.reset()`](#PollingRequest+reset)
+ * [`.polling(func)`](#PollingRequest+polling)
+
+
+
+### `new PollingRequest([maxPollingTime], [timeInterval])`
+轮询
+
+
+| Param | Type | Default | Description |
+| --- | --- | --- | --- |
+| [maxPollingTime] | number
| 10
| 最大轮询次数
|
+| [timeInterval] | number
| 2000
| 轮询间隔
|
+
+**Example**
+```ts
+const polling = new PollingRequest(10);
+const cb = () => {
+ this.onGetTeamList(true);
+};
+polling.polling(cb);
+```
+
+
+### `pollingRequest.reset()`
+重置,即取消轮询
+
+**Kind**: instance method of [PollingRequest
](#PollingRequest)
+
+
+### `pollingRequest.polling(func)`
+开始轮询
+
+**Kind**: instance method of [PollingRequest
](#PollingRequest)
+
+| Param | Type | Description |
+| --- | --- | --- |
+| func | function
| 轮询方法
|
+
diff --git a/gulpfile.ts b/gulpfile.ts
index a82e6c41..c2a10ffd 100644
--- a/gulpfile.ts
+++ b/gulpfile.ts
@@ -44,7 +44,7 @@ export const build = series(
);
// 自定义生成 changelog
-export async function changelog(cb) {
+export async function changelog(cb: Function) {
const changelogPath: string = path.join(paths.root, 'CHANGELOG.md');
// 对命令 conventional-changelog -p angular -i CHANGELOG.md -w -r 0
diff --git a/package.json b/package.json
index 53d0b8db..ac94c5a9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "t-comm",
- "version": "1.3.36",
+ "version": "1.3.45",
"description": "丰富易用的工具库",
"main": "lib/index.js",
"module": "lib/index.esm.js",
@@ -59,9 +59,11 @@
"docs:deploy:mine": "node script/docs-jsdoc/docs-mine",
"docs:deploy": "node script/docs-jsdoc/deploy",
"release:first": "standard-version --first-release",
- "release-major": "standard-version --release-as major -a",
- "release-minor": "standard-version --release-as minor -a",
- "release-patch": "standard-version --release-as patch -a",
+ "release:major": "standard-version --release-as major -a",
+ "release:minor": "standard-version --release-as minor -a",
+ "release:patch": "standard-version --release-as patch -a",
+ "release:alpha": "standard-version --prerelease alpha -a",
+ "release:beta": "standard-version --prerelease beta -a",
"step:build": "node script/gulp/test-task",
"postinstall": "node -e \"try{require('./lib/npm-tip/post-install')}catch(e){}\""
},
@@ -81,6 +83,7 @@
"@types/gulp": "^4.0.9",
"@types/jest": "^27.4.0",
"@types/node": "^17.0.17",
+ "@types/sinon": "^17.0.2",
"@typescript-eslint/eslint-plugin": "^5.39.0",
"@typescript-eslint/parser": "^5.39.0",
"babel-core": "6.25",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8e2c2b39..4aec1057 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -17,6 +17,7 @@ specifiers:
'@types/gulp': ^4.0.9
'@types/jest': ^27.4.0
'@types/node': ^17.0.17
+ '@types/sinon': ^17.0.2
'@typescript-eslint/eslint-plugin': ^5.39.0
'@typescript-eslint/parser': ^5.39.0
axios: '*'
@@ -87,6 +88,7 @@ devDependencies:
'@types/gulp': 4.0.9
'@types/jest': 27.4.1
'@types/node': 17.0.21
+ '@types/sinon': 17.0.2
'@typescript-eslint/eslint-plugin': 5.39.0_fin4gqhsxg7lmbfdm7qx6k7c5e
'@typescript-eslint/parser': 5.39.0_xvcshhxeosngsn5bmcucl2prs4
babel-core: 6.25.0
@@ -2725,6 +2727,16 @@ packages:
'@types/node': 17.0.21
dev: true
+ /@types/sinon/17.0.2:
+ resolution: {integrity: sha512-Zt6heIGsdqERkxctIpvN5Pv3edgBrhoeb3yHyxffd4InN0AX2SVNKSrhdDZKGQICVOxWP/q4DyhpfPNMSrpIiA==}
+ dependencies:
+ '@types/sinonjs__fake-timers': 8.1.5
+ dev: true
+
+ /@types/sinonjs__fake-timers/8.1.5:
+ resolution: {integrity: sha512-mQkU2jY8jJEF7YHjHvsQO8+3ughTL1mcnn96igfhONmR+fUPSKIkefQYpSe8bsly2Ep7oQbn/6VG5/9/0qcArQ==}
+ dev: true
+
/@types/source-list-map/0.1.2:
resolution: {integrity: sha512-K5K+yml8LTo9bWJI/rECfIPrGgxdpeNbj+d53lwN4QjW1MCwlkhUms+gtdzigTeUyBr09+u8BwOIY3MXvHdcsA==}
dev: true
diff --git a/script/docs-jsdoc/change-log.js b/script/docs-jsdoc/change-log.js
index 4a4f2782..b666aa9c 100644
--- a/script/docs-jsdoc/change-log.js
+++ b/script/docs-jsdoc/change-log.js
@@ -1,103 +1,12 @@
-const { replaceAllPolyfill } = require('../../lib/index');
-const { execSync } = require('child_process');
-const fs = require('fs');
+const { insertDocChangeLog } = require('../../lib/index');
const DOC_CHANGE_LOG_PATH = './docs/CHANGELOG.md';
const SOURCE_CHANGE_LOG_PATH = './CHANGELOG.md';
-replaceAllPolyfill();
-function writeToJSON(file, data) {
- fs.writeFileSync(file, data, {
- encoding: 'utf-8',
- });
-}
-
-function readFile(file) {
- let res = fs.readFileSync(file, {
- encoding: 'utf-8',
- });
-
- try {
- res = JSON.parse(res);
- } catch (e) {}
-
- return res;
-}
-
-const replaceList = [
- {
- from: '🐛 Bug Fixes | Bug 修复',
- to: 'Bug Fixes 🐞',
- }, {
- from: '✨ Features | 新功能',
- to: 'Features 🎉',
- },
- {
- from: '✏️ Documentation | 文档',
- to: 'Documentation 📖',
- },
- {
- from: '♻️ Code Refactoring | 代码重构',
- to: 'Code Refactoring ♻️',
- },
- {
- from: '🚀 Chore | 构建/工程依赖/工具',
- to: 'Chore 🚀 ',
- },
- {
- from: '📦 Build System | 打包构建',
- to: 'Build System 📦',
- },
- {
- from: '✅ Tests | 测试',
- to: 'Tests ✅',
- },
- {
- from: '💄 Styles | 风格',
- to: 'Styles 💄',
- },
-];
-
-function replaceChangeLogKeywords(data = '') {
- let newData = data;
- for (const item of replaceList) {
- const { from, to } = item;
- newData = newData.replaceAll(from, to);
- }
- return newData;
-}
-
-
-function main() {
- const changeLog = readFile(SOURCE_CHANGE_LOG_PATH);
- const pkg = readFile('./package.json');
- const { version } = pkg;
-
- // version = '1.0.31';
- console.log('[version] ', version);
- if (!version) return;
-
- const reg = new RegExp(`(\\n[#]+\\s*\\[${version}\\].*?\\n)(?=[#]+\\s*\\[\\d+\\.\\d+\\.\\d+\\])`, 's');
- console.log('[reg]', reg);
-
- const match = changeLog.match(reg);
- console.log('[match]', match[1]);
-
- if (!match?.[1]) return;
-
- const docChangeLog = readFile(DOC_CHANGE_LOG_PATH);
-
- let newDocChangeLog = docChangeLog.replace(/(?=([#]{2,}))/, match[1]);
- newDocChangeLog = replaceChangeLogKeywords(newDocChangeLog);
-
- writeToJSON(DOC_CHANGE_LOG_PATH, newDocChangeLog);
-
- execSync('git add .', {
- stdio: 'inherit',
- });
-}
-
-
-main();
+insertDocChangeLog({
+ changelogPath: SOURCE_CHANGE_LOG_PATH,
+ docChangelogPath: DOC_CHANGE_LOG_PATH,
+ packageJsonPath: './package.json',
+});
diff --git a/src/base/number/index.ts b/src/base/number/index.ts
index caa3a42e..0747512b 100644
--- a/src/base/number/index.ts
+++ b/src/base/number/index.ts
@@ -5,4 +5,7 @@ export {
getThousandSeparator,
getThousandSeparator2,
random,
+ padZero,
+ addNumber,
+ range,
} from './number';
diff --git a/src/base/number/number.ts b/src/base/number/number.ts
index f3a7e586..4d056376 100644
--- a/src/base/number/number.ts
+++ b/src/base/number/number.ts
@@ -146,7 +146,7 @@ export function getThousandSeparator2(value: number | string) {
* random(0, 19) // 1
* ```
*/
-export function random(min, max) {
+export function random(min: number, max: number) {
if (min >= 0 && max > 0 && max >= min) {
const gap = max - min + 1;
return Math.floor(Math.random() * gap + min);
@@ -154,3 +154,53 @@ export function random(min, max) {
return 0;
}
+
+/**
+ * 数字左侧加 0,直到满足长度要求
+ * @param {string | number} num 当前数字
+ * @param {number} [targetLength=2] 目标长度
+ * @returns {string} 新的字符串
+ * @example
+ * ```ts
+ * padZero(1, 3); // 001
+ * ```
+ */
+export function padZero(num: number | string, targetLength = 2) {
+ let str = `${num}`;
+ while (str.length < targetLength) {
+ str = `0${str}`;
+ }
+ return str;
+}
+
+
+/**
+ * add num and avoid float number
+ * @param {number} num1 第1个数字
+ * @param {number} num2 第2个数字
+ * @returns {number} 结果
+ * @example
+ * ```ts
+ * addNumber(0.1, 0.2); // 0.3
+ * ```
+ */
+export function addNumber(num1: number, num2: number) {
+ const cardinal = Math.pow(10, 10);
+ return Math.round((num1 + num2) * cardinal) / cardinal;
+}
+
+
+/**
+ * 根据边界值修正数字
+ * @param {number} num 待处理的数字
+ * @param {number} min 边界最小值
+ * @param {number} max 边界最大值
+ * @returns {number} 处理结果
+ * @example
+ * ```ts
+ * range(12, 1, 2); // 2
+ * ```
+ */
+export function range(num: number, min: number, max: number) {
+ return Math.min(Math.max(num, min), max);
+}
diff --git a/src/base/regexp/index.ts b/src/base/regexp/index.ts
index bc76f66f..c6e76b53 100644
--- a/src/base/regexp/index.ts
+++ b/src/base/regexp/index.ts
@@ -1 +1 @@
-export { getMatchListFromReg } from './regexp';
+export { getMatchListFromReg, getPreReleaseTag } from './regexp';
diff --git a/src/base/regexp/regexp.ts b/src/base/regexp/regexp.ts
index b0e3ac8d..bf036c2e 100644
--- a/src/base/regexp/regexp.ts
+++ b/src/base/regexp/regexp.ts
@@ -11,7 +11,7 @@
* // ['start', 'end']
* ```
*/
-export function getMatchListFromReg(content, reg) {
+export function getMatchListFromReg(content: string, reg: RegExp) {
let match = reg.exec(content);
const result: Array = [];
@@ -22,3 +22,22 @@ export function getMatchListFromReg(content, reg) {
return result;
}
+
+const PRE_RELEASE_VERSION = /\d+\.\d+\.\d+-(\w+).\d+/;
+
+
+/**
+ * 获取预发布版本标签,比如 alpha, beta
+ * @param {string} version 版本号
+ * @returns 标签
+ * @example
+ * ```ts
+ * getPreReleaseTag('1.2.2-beta.0')
+ * // beta
+ * ```
+ */
+export function getPreReleaseTag(version: string) {
+ const match = version.match(PRE_RELEASE_VERSION);
+ if (!match || !match[1]) return '';
+ return match[1];
+}
diff --git a/src/change-log/change-log.ts b/src/change-log/change-log.ts
new file mode 100644
index 00000000..43814527
--- /dev/null
+++ b/src/change-log/change-log.ts
@@ -0,0 +1,106 @@
+import { replaceAllPolyfill } from '../base/string/replace-all';
+import { writeFileSync, readFileSync } from '../fs/fs';
+
+
+const replaceList = [
+ {
+ from: '🐛 Bug Fixes | Bug 修复',
+ to: 'Bug Fixes 🐞',
+ }, {
+ from: '✨ Features | 新功能',
+ to: 'Features 🎉',
+ },
+ {
+ from: '✏️ Documentation | 文档',
+ to: 'Documentation 📖',
+ },
+ {
+ from: '♻️ Code Refactoring | 代码重构',
+ to: 'Code Refactoring ♻️',
+ },
+ {
+ from: '🚀 Chore | 构建/工程依赖/工具',
+ to: 'Chore 🚀 ',
+ },
+ {
+ from: '📦 Build System | 打包构建',
+ to: 'Build System 📦',
+ },
+ {
+ from: '✅ Tests | 测试',
+ to: 'Tests ✅',
+ },
+ {
+ from: '💄 Styles | 风格',
+ to: 'Styles 💄',
+ },
+];
+
+function replaceChangeLogKeywords(data = '') {
+ replaceAllPolyfill();
+ let newData = data;
+
+ for (const item of replaceList) {
+ const { from, to } = item;
+ newData = newData.replaceAll(from, to);
+ }
+ return newData;
+}
+
+
+/**
+ * 同步最新版本的更新日志
+ * @param {object} params 参数
+ * @param {string} params.changelogPath 源 change-log路径
+ * @param {string} params.docChangelogPath 文档 change-log 路径
+ * @param {string} params.packageJsonPath package.json 路径
+ *
+ * @example
+ * ```ts
+ * const DOC_CHANGE_LOG_PATH = './docs/CHANGELOG.md';
+ * const SOURCE_CHANGE_LOG_PATH = './CHANGELOG.md';
+ *
+ * insertDocChangeLog({
+ * changelogPath: SOURCE_CHANGE_LOG_PATH,
+ * docChangeLog: DOC_CHANGE_LOG_PATH,
+ * packageJsonPath: './package.json',
+ * });
+ * ```
+ */
+export function insertDocChangeLog({
+ changelogPath,
+ docChangelogPath,
+ packageJsonPath,
+}: {
+ changelogPath: string;
+ docChangelogPath: string;
+ packageJsonPath: string;
+}) {
+ const changeLog = readFileSync(changelogPath, false);
+ const pkg = readFileSync(packageJsonPath, true);
+ const { version } = pkg;
+
+ // version = '1.0.31';
+ console.log('[insertDocChangeLog] version: ', version);
+ if (!version) return;
+
+ const reg = new RegExp(`(\\n[#]+\\s*\\[${version}\\].*?\\n)(?=[#]+\\s*\\[\\d+\\.\\d+\\.\\d+)`, 's');
+
+ const match = changeLog.match(reg);
+
+ if (!match?.[1]) return;
+ console.log('[insertDocChangeLog] match: ', match[1]);
+
+ const docChangeLog = readFileSync(docChangelogPath);
+
+ let newDocChangeLog = docChangeLog.replace(/(?=([#]{2,}))/, match[1]);
+ newDocChangeLog = replaceChangeLogKeywords(newDocChangeLog);
+
+ writeFileSync(docChangelogPath, newDocChangeLog);
+
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ require('child_process').execSync('git add .', {
+ stdio: 'inherit',
+ });
+}
+
diff --git a/src/change-log/index.ts b/src/change-log/index.ts
new file mode 100644
index 00000000..635997f4
--- /dev/null
+++ b/src/change-log/index.ts
@@ -0,0 +1 @@
+export { insertDocChangeLog } from './change-log';
diff --git a/src/city/city.ts b/src/city/city.ts
index 951e1c99..acdd3283 100644
--- a/src/city/city.ts
+++ b/src/city/city.ts
@@ -119,13 +119,13 @@ export function getAreaData(data = RAW_CITY_DATA, areaArray: Array = [
Object.keys(provData).forEach((key) => {
const provObject: any = {};
- provObject.text = provData[key];
+ provObject.text = provData[key as unknown as keyof typeof provData];
provObject.code = key;
areaArray.push(provObject);
});
Object.keys(cityData).forEach((key1) => {
- const cityList = cityData[key1];
+ const cityList = cityData[key1 as unknown as keyof typeof cityData];
const array: Array = [];
if (Array.isArray(cityList)) {
const cityObject: ProvType = {};
@@ -140,7 +140,7 @@ export function getAreaData(data = RAW_CITY_DATA, areaArray: Array = [
Object.keys(cityList).forEach((key2) => {
const cityObject: ProvType = {};
- cityObject.text = cityList[key2];
+ cityObject.text = cityList[key2 as unknown as keyof typeof cityList];
cityObject.code = key2;
array.push(cityObject);
});
@@ -202,24 +202,24 @@ export function getAreaCode(provinceStr = '', cityStr = '') {
* const res2 = getCityName(11)
* // ['北京', '北京']
*/
-export function getAreaName(provinceId, cityId?: number) {
+export function getAreaName(provinceId: string | number, cityId?: number) {
let provName = '';
// eslint-disable-next-line no-prototype-builtins
if (RAW_CITY_DATA.provData.hasOwnProperty(provinceId)) {
- provName = RAW_CITY_DATA.provData[provinceId];
+ provName = RAW_CITY_DATA.provData[provinceId as keyof typeof RAW_CITY_DATA.provData];
}
let cityName = '';
let cityList = {};
// eslint-disable-next-line no-prototype-builtins
if (RAW_CITY_DATA.cityData.hasOwnProperty(provinceId)) {
- cityList = RAW_CITY_DATA.cityData[provinceId];
+ cityList = RAW_CITY_DATA.cityData[provinceId as keyof typeof RAW_CITY_DATA.cityData];
}
if (Array.isArray(cityList)) {
cityName = provName;
} else if (cityId) {
- cityName = cityList[cityId];
+ cityName = cityList[cityId as keyof typeof cityList];
}
return [provName, cityName];
@@ -237,8 +237,8 @@ export function getAreaName(provinceId, cityId?: number) {
* const res2 = getCityName(11)
* // 北京
*/
-export function getProvName(provinceId) {
- const provName = RAW_CITY_DATA.provData[provinceId];
+export function getProvName(provinceId: string | number) {
+ const provName = RAW_CITY_DATA.provData[provinceId as keyof typeof RAW_CITY_DATA.provData];
return provName;
}
@@ -255,15 +255,15 @@ export function getProvName(provinceId) {
* const res2 = getCityName(11)
* // 北京
*/
-export function getCityName(provinceId, cityId?: number) {
- const provName = RAW_CITY_DATA.provData[provinceId];
+export function getCityName(provinceId: number | string, cityId?: number | string) {
+ const provName = RAW_CITY_DATA.provData[provinceId as keyof typeof RAW_CITY_DATA.provData];
let cityName = '';
- const cityList = RAW_CITY_DATA.cityData[provinceId];
+ const cityList = RAW_CITY_DATA.cityData[provinceId as keyof typeof RAW_CITY_DATA.cityData];
if (Array.isArray(cityList)) {
cityName = provName;
} else if (cityId && cityList) {
- cityName = cityList[cityId];
+ cityName = cityList[cityId as keyof typeof cityList];
}
return cityName;
}
diff --git a/src/color/parse.ts b/src/color/parse.ts
index 08d00a05..83669dc2 100644
--- a/src/color/parse.ts
+++ b/src/color/parse.ts
@@ -5,6 +5,10 @@ function commonParseRGBOrHSL({
value,
reg = /hsla|hsl|\(|\)/gm,
transformFunc = hsl2hsv,
+}: {
+ value: string;
+ reg?: RegExp;
+ transformFunc?: Function
}) {
let alpha = 100;
let h = 0;
diff --git a/src/component/add-emits.ts b/src/component/add-emits.ts
index 261eea45..d442cc8f 100644
--- a/src/component/add-emits.ts
+++ b/src/component/add-emits.ts
@@ -1,5 +1,6 @@
-import * as fs from 'fs';
import { getMatchListFromReg } from '../base/regexp/regexp';
+import { writeFileSync, readFileSync } from '../fs/fs';
+
/**
* 为 Vue 组件添加 emits 属性
@@ -12,12 +13,10 @@ import { getMatchListFromReg } from '../base/regexp/regexp';
* addNameForComponent('xxx.vue');
* ```
*/
-export function addEmitsForComponent(filePath, fileContent = '') {
+export function addEmitsForComponent(filePath: string, fileContent = '') {
let content = fileContent;
if (!content) {
- content = fs.readFileSync(filePath, {
- encoding: 'utf-8',
- });
+ content = readFileSync(filePath, false);
}
if (/emits:\s*\[/.test(content)) return;
@@ -31,15 +30,13 @@ export function addEmitsForComponent(filePath, fileContent = '') {
getEmitsStr(emits),
);
- fs.writeFileSync(filePath, newSource, {
- encoding: 'utf-8',
- });
+ writeFileSync(filePath, newSource);
return newSource;
}
-function getEmitList(source) {
+function getEmitList(source: string) {
const reg = /emit\('([^',]+)'/g;
const emits = getMatchListFromReg(source, reg);
@@ -50,7 +47,7 @@ function getEmitList(source) {
}
-function getEmitsStr(emits) {
+function getEmitsStr(emits: Array) {
const emitsStr = emits.map(item => `'${item}'`).join(',\n ');
return [
diff --git a/src/component/add-name.ts b/src/component/add-name.ts
index 25ec2298..8d6399d3 100644
--- a/src/component/add-name.ts
+++ b/src/component/add-name.ts
@@ -1,7 +1,7 @@
-import * as fs from 'fs';
+import { writeFileSync, readFileSync } from '../fs/fs';
-const getComponentNameStr = componentName => `export default {\n name: '${componentName}',`;
+const getComponentNameStr = (componentName: string) => `export default {\n name: '${componentName}',`;
/**
* 为 Vue 组件添加、修正 name 属性
@@ -14,21 +14,18 @@ const getComponentNameStr = componentName => `export default {\n name: '${compo
* addNameForComponent('xxx.vue', 'PressUploader');
* ```
*/
-export function addNameForComponent(filePath, componentName) {
- const content = fs.readFileSync(filePath, {
- encoding: 'utf-8',
- });
+export function addNameForComponent(filePath: string, componentName: string) {
+ const content = readFileSync(filePath);
const result = content
.replace(/export default {(?!\s+name)/, getComponentNameStr(componentName))
- .replace(/export default {\s+name: '(\w+)',/, (a, origin) => {
+ .replace(/export default {\s+name: '(\w+)',/, (a: string, origin: string) => {
console.log('[origin] ', origin);
return getComponentNameStr(componentName);
});
- fs.writeFileSync(filePath, result, {
- encoding: 'utf-8',
- });
+ writeFileSync(filePath, result);
+
return result;
}
diff --git a/src/component/extract-class.ts b/src/component/extract-class.ts
index 585ac7de..c7d50e61 100644
--- a/src/component/extract-class.ts
+++ b/src/component/extract-class.ts
@@ -1,4 +1,4 @@
-import * as fs from 'fs';
+import { writeFileSync, readFileSync } from '../fs/fs';
const DEFAULT_EXTRACT_REGEXP = /(?<=class=")([^"=/?).]+?)(?=")/g;
// /(?!class=")(?=tip)([^"]+)/g
@@ -20,17 +20,17 @@ export function extractClass({
filePath,
targetFilePath = './log/extract-class.md',
extractRegexp = DEFAULT_EXTRACT_REGEXP,
+}: {
+ filePath: string;
+ targetFilePath?: string;
+ extractRegexp?: RegExp;
}) {
- const content = fs.readFileSync(filePath, {
- encoding: 'utf-8',
- });
+ const content = readFileSync(filePath);
let res: Array = [];
res = Array.from(new Set(content.match(extractRegexp)));
console.log('[extractClass] res: ', res);
- fs.writeFileSync(targetFilePath, JSON.stringify(res, null, 2), {
- encoding: 'utf-8',
- });
+ writeFileSync(targetFilePath, res, true);
}
diff --git a/src/component/extract-event.ts b/src/component/extract-event.ts
index b83f47b1..198f5b8f 100644
--- a/src/component/extract-event.ts
+++ b/src/component/extract-event.ts
@@ -1,12 +1,11 @@
-import * as fs from 'fs';
+import { writeFileSync, readFileSync } from '../fs/fs';
const DEFAULT_EXTRACT_REGEXP = /\$emit\('([\w]+)'/g;
-function getEventList(filePath, extractRegexp) {
- const data = fs.readFileSync(filePath, {
- encoding: 'utf-8',
- });
- const eventList: Array> = [];
+function getEventList(filePath: string, extractRegexp: RegExp) {
+ const data = readFileSync(filePath);
+
+ const eventList: Array<{ name: string}> = [];
let match = extractRegexp.exec(data);
while (match) {
@@ -18,7 +17,7 @@ function getEventList(filePath, extractRegexp) {
return eventList;
}
-function genTable(list) {
+function genTable(list: Array<{ name: string }>) {
const table = [
'| 事件名 | 说明 | 参数 |',
'| ------------------ | ---------------- | --------- |',
@@ -49,11 +48,13 @@ export function extractEvent({
filePath,
targetFilePath = './log/extract-event.md',
extractRegexp = DEFAULT_EXTRACT_REGEXP,
+}: {
+ filePath: string;
+ targetFilePath?: string;
+ extractRegexp?: RegExp;
}) {
const eventList = getEventList(filePath, extractRegexp);
const table = genTable(eventList);
- fs.writeFileSync(targetFilePath, table, {
- encoding: 'utf-8',
- });
+ writeFileSync(targetFilePath, table);
}
diff --git a/src/component/extract-props.ts b/src/component/extract-props.ts
index 50d6f9c6..b234ef63 100644
--- a/src/component/extract-props.ts
+++ b/src/component/extract-props.ts
@@ -1,11 +1,11 @@
-import * as fs from 'fs';
import { hyphenate } from '../base/string/string';
+import { writeFileSync, readFileSync } from '../fs/fs';
const DEFAULT_EXTRACT_REGEXP = /([\w]+):\s*\{\s+type:\s*([\w]+),\s+default:\s(.*),/g;
-function parseDefaultValue(value) {
+function parseDefaultValue(value: string) {
if (value.indexOf('=>') > -1) {
value = value
.replace(/\(\)\s*=>\s*\(?/, '').replace(/\)?$/, '')
@@ -20,11 +20,10 @@ function parseDefaultValue(value) {
return `\`${value}\``;
}
-function getPropsList(filePath, extractRegexp) {
- const data = fs.readFileSync(filePath, {
- encoding: 'utf-8',
- });
- const propsList: Array> = [];
+function getPropsList(filePath: string, extractRegexp: RegExp) {
+ const data = readFileSync(filePath);
+
+ const propsList: Array<{ name: string; type: string; defaultValue: string; }> = [];
let match = extractRegexp.exec(data);
while (match) {
@@ -39,7 +38,7 @@ function getPropsList(filePath, extractRegexp) {
return propsList;
}
-function genTable(list) {
+function genTable(list: Array<{ name: string; type: string; defaultValue: string; }>) {
const table = [
'| 参数 | 说明 | 类型 | 默认值 |',
'| ------------------ | ---------------- | --------- | ------ |',
@@ -70,12 +69,14 @@ export function extractProps({
filePath,
targetFilePath = './log/extract-props.md',
extractRegexp = DEFAULT_EXTRACT_REGEXP,
+}: {
+ filePath: string;
+ targetFilePath?: string;
+ extractRegexp?: RegExp;
}) {
const propsList = getPropsList(filePath, extractRegexp);
const table = genTable(propsList);
- fs.writeFileSync(targetFilePath, table, {
- encoding: 'utf-8',
- });
+ writeFileSync(targetFilePath, table);
}
diff --git a/src/css/css.ts b/src/css/css.ts
index 78fedd72..0c538a7f 100644
--- a/src/css/css.ts
+++ b/src/css/css.ts
@@ -18,7 +18,7 @@ export function removeCss(href: string) {
}
-function loadStyle(url, urlClass) {
+function loadStyle(url: string, urlClass: string) {
const link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
@@ -64,7 +64,7 @@ export function loadStyles(urls: Array, urlClass: string) {
* );
* ```
*/
-export function loadCssCode(code, className) {
+export function loadCssCode(code: string, className: string) {
Array.prototype.slice.call(document.getElementsByClassName(className)).forEach(item => item.remove());
const style: HTMLStyleElement = document.createElement('style');
diff --git a/src/date/date.ts b/src/date/date.ts
index 07307f46..03d83de4 100644
--- a/src/date/date.ts
+++ b/src/date/date.ts
@@ -1,3 +1,4 @@
+import { timeStampFormat } from '../time/time';
/**
* 获取一个月有多少天
* 原理:new Date()第2个参数默认为1,就是每个月的1号,把它设置为0时,
@@ -83,3 +84,30 @@ export function isSameWeek(date1: number, date2: number) {
const md2 = toMonday(dt2);
return md1 === md2;
}
+
+function toZeroTime(date: Date) {
+ const time = new Date(date).getTime();
+ return timeStampFormat(time, 'yyyy-MM-dd');
+}
+
+
+/**
+ * 判断是否是同一天
+ * @param {number} date1 时间戳
+ * @param {number} date2 时间戳
+ * @returns 是否相同
+ * @example
+ * ```ts
+ * isSameDay(1702613769418, 1702613769419) // true
+ * ```
+ */
+export function isSameDay(date1: number, date2: number) {
+ const dt1 = new Date();
+ dt1.setTime(date1);
+ const dt2 = new Date();
+ dt2.setTime(date2);
+
+ const md1 = toZeroTime(dt1);
+ const md2 = toZeroTime(dt2);
+ return md1 === md2;
+}
diff --git a/src/date/index.ts b/src/date/index.ts
index f7a3d4c8..a020b199 100644
--- a/src/date/index.ts
+++ b/src/date/index.ts
@@ -2,6 +2,7 @@ export {
getMonthDay,
getMonthDay2,
isSameWeek,
+ isSameDay,
} from './date';
export {
parseTime,
diff --git a/src/debounce/index.ts b/src/debounce/index.ts
index 05621fda..eaff390a 100644
--- a/src/debounce/index.ts
+++ b/src/debounce/index.ts
@@ -17,10 +17,10 @@
* window.onscroll = debounce(count, 500)
* ```
*/
-export function debounce(fn, time) {
- let timer;
+export function debounce(fn: Function, time: number) {
+ let timer: ReturnType;
- return function (...args) {
+ return function (...args: Array) {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
diff --git a/src/devops/mp-ci/devops-mp-ci.ts b/src/devops/mp-ci/devops-mp-ci.ts
index 9943b4d4..b4aac203 100644
--- a/src/devops/mp-ci/devops-mp-ci.ts
+++ b/src/devops/mp-ci/devops-mp-ci.ts
@@ -33,7 +33,7 @@ async function updateOrCreateInstance({
devopsConfig,
templateIdMap,
onlyCollectNoUsedPipeline,
-}) {
+}: Record) {
const newConfig = JSON.parse(rainbowMap[mpCIKey].value);
const robotMapKey = isWxCI ? 'robotMap' : 'qqRobotMap';
const newInfo = newConfig[robotMapKey] || {};
@@ -105,7 +105,7 @@ async function realUpdateOrCreatePipeline({
mpCIKey,
newConfig,
forceUpdate,
-}) {
+}: Record) {
const res = await cgiName({
...devopsConfig,
templateId: isWxCI ? templateIdMap.WX_MP_CI : templateIdMap.QQ_MP_CI,
@@ -121,7 +121,7 @@ async function realUpdateOrCreatePipeline({
}),
],
})
- .catch((err) => {
+ .catch((err: any) => {
console.log('[cgiName] err', err);
});
@@ -145,7 +145,7 @@ async function handleChangedConfig({
forceUpdate?: boolean
}) {
const { ADDED: added, UPDATED: updated, DELETED: deleted, newObj: rainbowMap } = compareRes;
- const filterMpCI = list => list.filter(item => item.endsWith('_mp_ci'));
+ const filterMpCI = (list: Array) => list.filter(item => item.endsWith('_mp_ci'));
console.log('[compareRes]', added, updated, deleted);
let updatedMpCIs: Array = [];
@@ -169,7 +169,7 @@ export async function updateDevopsMpCIPipeline({
devopsConfig,
templateIdMap,
rainbowGroupSecretInfo,
-}) {
+}: Record) {
const resp = await queryGroupInfo({
secretInfo: rainbowGroupSecretInfo,
});
diff --git a/src/devops/mp-ci/helper.ts b/src/devops/mp-ci/helper.ts
index dacca326..89502601 100644
--- a/src/devops/mp-ci/helper.ts
+++ b/src/devops/mp-ci/helper.ts
@@ -13,7 +13,7 @@ const {
const remoteInstancesMap: Record = {};
-export function genOneFileFromRainbowGroup(list) {
+export function genOneFileFromRainbowGroup(list: Array) {
const obj = list.reduce((acc, item) => {
acc[item.key] = {
value: item.value,
@@ -25,9 +25,9 @@ export function genOneFileFromRainbowGroup(list) {
}
-export function parseRobotMap(obj = {}) {
+export function parseRobotMap(obj: Record = {}) {
const branches = Object.keys(obj);
- const res = {};
+ const res: Record = {};
for (const branch of branches) {
const envs = Object.keys(obj[branch]);
@@ -69,7 +69,7 @@ export function getPipelineName({
branch,
ciKey,
prefix,
-}) {
+}: Record) {
return [
prefix,
ciKey,
@@ -80,7 +80,7 @@ export function getPipelineName({
}
-export function parseInstanceName(name) {
+export function parseInstanceName(name: string) {
const list = name.split(CI_SEPARATOR);
const {
0: prefix,
@@ -105,7 +105,7 @@ export function getPipelineParam({
rainbowConfigKey,
repo,
isWxCI,
-}) {
+}: Record) {
const res = [
{
id: 'rainbowConfigKey',
@@ -165,15 +165,15 @@ export function getPipelineParam({
}
-export function compareFromLogFile(key, obj) {
+export function compareFromLogFile(key: string, obj: Record) {
const originFile = getJsonFromLog(key);
const compareRes = compareTwoObj(originFile, obj);
return compareRes;
}
-export const getTemplateInstanceFileName = isWxCI => `devops-template-instances-${isWxCI ? 'wx' : 'qq'}.json`;
-export const getRainbowMpCIFileName = isWxCI => `devops-mp-ci-rainbow-${isWxCI ? 'wx' : 'qq'}.json`;
+export const getTemplateInstanceFileName = (isWxCI: boolean) => `devops-template-instances-${isWxCI ? 'wx' : 'qq'}.json`;
+export const getRainbowMpCIFileName = (isWxCI: boolean) => `devops-mp-ci-rainbow-${isWxCI ? 'wx' : 'qq'}.json`;
export async function isPipelineUpdated({
@@ -182,7 +182,7 @@ export async function isPipelineUpdated({
forceUpdate,
devopsConfig,
templateIdMap,
-}) {
+}: Record) {
const {
prefix,
projectShortName,
@@ -232,7 +232,7 @@ export function getUnusedPipelineList({
usefulList,
isWxCI,
templateIdMap,
-}) {
+}: Record) {
const templateId = isWxCI ? templateIdMap.WX_MP_CI : templateIdMap.QQ_MP_CI;
const remoteInstances = remoteInstancesMap[templateId] || [];
diff --git a/src/devops/pipeline.ts b/src/devops/pipeline.ts
index 91a8e50d..76684973 100644
--- a/src/devops/pipeline.ts
+++ b/src/devops/pipeline.ts
@@ -154,7 +154,10 @@ export async function getPipelineList({
* @param {Array} list 结果列表,可不传,用于迭代
* @returns 流水线列表
*/
-export async function getAllPipelineList(args, list: Array = []) {
+export async function getAllPipelineList(
+ args: Parameters[0],
+ list: Array = [],
+): Promise {
const page = args.page || 1;
const res = await getPipelineList({
...args,
@@ -174,7 +177,7 @@ export async function getAllPipelineList(args, list: Array = []) {
}
-function findRunningTooLongPipelines(list, time, maxTime) {
+function findRunningTooLongPipelines(list: Array, time: number, maxTime: number) {
const res = list
.filter(item => item.latestBuildStatus === 'RUNNING')
.filter((item) => {
@@ -186,7 +189,7 @@ function findRunningTooLongPipelines(list, time, maxTime) {
}
-function genRobotMessage(dataList, host, projectId) {
+function genRobotMessage(dataList: Array, host: string, projectId: string) {
const list = [
`【流水线执行时间过长监控】${timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss')}<@guowangyang>`,
];
diff --git a/src/env-variable/env-variable.ts b/src/env-variable/env-variable.ts
index b352543d..1e946ae2 100644
--- a/src/env-variable/env-variable.ts
+++ b/src/env-variable/env-variable.ts
@@ -63,7 +63,7 @@ export function readEnvVariable(key: string, filepath: string): string {
try {
const sourceStr = fs.readFileSync(filepath, 'utf-8');
const sourceLine = sourceStr.split('\n');
- return getKeyValue(key, sourceLine);
+ return getKeyValue(key, sourceLine)!;
} catch (e) {
console.log('[readEnvVariable] 打开文件失败:', filepath);
process.exit(1);
diff --git a/src/env-variable/npm-token.ts b/src/env-variable/npm-token.ts
index 1d7ede2d..821d9a4d 100644
--- a/src/env-variable/npm-token.ts
+++ b/src/env-variable/npm-token.ts
@@ -1,6 +1,6 @@
-import * as fs from 'fs';
import * as path from 'path';
import { readEnvVariable } from '../env-variable/env-variable';
+import { writeFileSync } from '../fs/fs';
const npmTokenRoot = process.cwd();
@@ -32,9 +32,7 @@ export function writeEnvTokenToNpmRC() {
const content = NPM_RC_TPL.replace('{{TOKEN}}', token);
const npmRCFile = path.resolve(npmTokenRoot, '.npmrc');
- fs.writeFileSync(npmRCFile, content, {
- encoding: 'utf-8',
- });
+ writeFileSync(npmRCFile, content);
}
diff --git a/src/fs/fs.ts b/src/fs/fs.ts
new file mode 100644
index 00000000..0881f509
--- /dev/null
+++ b/src/fs/fs.ts
@@ -0,0 +1,50 @@
+import * as fs from 'fs';
+
+
+/**
+ * 写入文件
+ * @param {string} file 文件地址
+ * @param {any} data 文件数据
+ * @param {boolean} [isJson] 是否需要 json 序列化
+ * @example
+ * ```ts
+ * writeFileSync('a', 'b.txt', false);
+ *
+ * writeFileSync({ a: 1 }, 'b.json', true);
+ * ```
+ */
+export function writeFileSync(file: string, data: any, isJson = false) {
+ const fileData = isJson ? JSON.stringify(data, null, 2) : data;
+
+ fs.writeFileSync(file, fileData, {
+ encoding: 'utf-8',
+ });
+}
+
+
+/**
+ * 读取文件
+ * @param {string} file 文件地址
+ * @param {boolean} [isJson] 是否需要 json 反序列化
+ * @returns {any} 文件内容
+ * @example
+ * ```ts
+ * readFileSync('b.txt', false);
+ *
+ * readFileSync('b.json', true);
+ * ```
+ */
+export function readFileSync(file: string, isJson = false) {
+ const content = fs.readFileSync(file, {
+ encoding: 'utf-8',
+ });
+
+ let result: any = content;
+ if (isJson) {
+ try {
+ result = JSON.parse(content);
+ } catch (e) {}
+ }
+
+ return result;
+}
diff --git a/src/fs/index.ts b/src/fs/index.ts
new file mode 100644
index 00000000..9c42354a
--- /dev/null
+++ b/src/fs/index.ts
@@ -0,0 +1 @@
+export { writeFileSync, readFileSync } from './fs';
diff --git a/src/functional-component/functional-component.ts b/src/functional-component/functional-component.ts
index 34d86ab7..043b6af3 100644
--- a/src/functional-component/functional-component.ts
+++ b/src/functional-component/functional-component.ts
@@ -28,17 +28,17 @@ const storeData: any = {};
* }
* ```
*/
-export function showFunctionalComponent(vueInstance, dialogComponent, dialogOptions) {
+export function showFunctionalComponent(vueInstance: any, dialogComponent: any, dialogOptions: Record) {
return new Promise((resolve) => {
if (typeof dialogComponent === 'function') {
dialogComponent()
- .then((dialog) => {
+ .then((dialog: any) => {
const component = showDialog(vueInstance, dialog.default, dialogOptions);
if (component) {
resolve(component);
}
})
- .catch((err) => {
+ .catch((err: unknown) => {
console.error('[showFunctionalComponent] error: ', err);
});
} else {
@@ -51,7 +51,7 @@ export function showFunctionalComponent(vueInstance, dialogComponent, dialogOpti
}
-function showDialog(vueInstance, dialogComponent, dialogOptions) {
+function showDialog(vueInstance: any, dialogComponent: any, dialogOptions: Record) {
const scopeId = dialogComponent._scopeId;
const storeComponent = storeData[scopeId];
if (scopeId && storeComponent) {
@@ -127,7 +127,7 @@ function showDialog(vueInstance, dialogComponent, dialogOptions) {
* @param {array} dialogList 弹窗列表
* @param {Object} dialogComponent 弹窗组件,支持静态导入 import Dialog from '..' 和动态导入 const Dialog = () => import('...') 两种形式
*/
-export function showFunctionalComponentQueue(context, dialogList, dialogComponent) {
+export function showFunctionalComponentQueue(context: any, dialogList: Array, dialogComponent: any) {
const showDialog = () => {
if (dialogList.length > 0) {
const dialogInfo = dialogList.pop();
diff --git a/src/image/image.ts b/src/image/image.ts
index 6481cb9f..0ad3707e 100644
--- a/src/image/image.ts
+++ b/src/image/image.ts
@@ -22,7 +22,7 @@
* handleImgUnit('5rem')
* // 50
*/
-export const handleImgUnit = function (size) {
+export const handleImgUnit = function (size: string | number) {
if (!size || typeof size === 'number') {
return size;
}
@@ -63,7 +63,7 @@ const cdnMap = new Map([
['igame-10037599.image.myqcloud.com', 'igame-10037599.file.myqcloud.com'],
]);
-const isTencentPic = function (url) {
+const isTencentPic = function (url: string) {
return url && (url.indexOf(zhizhu) !== -1
|| url.indexOf(youtu) !== -1
|| url.indexOf(wxlogo) !== -1
@@ -73,7 +73,13 @@ const isTencentPic = function (url) {
|| url.indexOf(ossweb) !== -1);
};
-const startWithHttp = function (url) {
+const TENCENT_CLOUD_PICS = [
+ '.myqcloud.com/',
+ 'cyberimage.sgameglobal.com/',
+];
+
+
+const startWithHttp = function (url: string) {
const http = /http:/;
return http.test(url);
};
@@ -84,7 +90,7 @@ const startWithHttp = function (url) {
* @param url 图片地址
* @returns 新的地址
*/
-export const getHttpsUrl = function (url) {
+export const getHttpsUrl = function (url: string) {
if (startWithHttp(url) && isTencentPic(url)) {
url = url.replace('http', 'https');
}
@@ -96,21 +102,70 @@ export const getHttpsUrl = function (url) {
* @param {string} url 图片地址
* @returns 新的地址
*/
-export const getCdnUrl = function (url) {
+export function getCdnUrl(url = ''): string {
if (url) {
const domainStr = url.split('/');
if (domainStr && domainStr.length > 2) {
const domain = domainStr[2];
if (cdnMap.has(domain)) {
- url = url.replace(domain, cdnMap.get(domain));
+ url = url.replace(domain, cdnMap.get(domain)!);
}
return url;
}
} else {
return url;
}
-};
+ return '';
+}
+
+
+function getCompressTencentImgSize(imageWidth: number, imageHeight: number) {
+ let width = 0;
+ let height = 0;
+ if (imageWidth && imageHeight) {
+ width = imageWidth > 0 ? (imageWidth * 2) : 0;
+ height = imageHeight > 0 ? (imageHeight * 2) : 0;
+ }
+
+ // width和height都按10取整,解决图片大小微微改变的时候,图片闪烁的问题
+ width = formatInt(width, 1, true);
+ height = formatInt(height, 1, true);
+ // 有时候图片没设置长宽,导致图片100%时图片过大,选择宽度优先
+ if (width > 200 && height > 200 && width === height) {
+ height = 0;
+ }
+
+ if (width < 10 && height < 10) {
+ width = 0;
+ height = 0;
+ }
+
+ return {
+ width,
+ height,
+ };
+}
+
+
+function getCompressTencentImgUrl(url: string, imageWidth: number, imageHeight: number) {
+ // 如果是腾讯云的图片实现按需加载(1倍的时候感觉图片有点糊,放大到2倍)
+ const isTencentCloudPic = url
+ && TENCENT_CLOUD_PICS.some(item => url.indexOf(item) !== -1)
+ && url.indexOf('?') === -1;
+
+ if (!isTencentCloudPic) {
+ return url;
+ }
+ const { width, height } = getCompressTencentImgSize(imageWidth, imageHeight);
+
+ if (width > 150 || height > 150) {
+ url = `${url}?imageMogr2/format/yjpeg/quality/80/thumbnail/!${width > 0 ? width.toString() : ''}x${height > 0 ? height.toString() : ''}r`;
+ } else if (width > 0 || height > 0) {
+ url = `${url}?imageMogr2/thumbnail/!${width > 0 ? width.toString() : ''}x${height > 0 ? height.toString() : ''}r`;
+ }
+ return url;
+}
/**
* 获取压缩后的图片
@@ -119,52 +174,25 @@ export const getCdnUrl = function (url) {
* @param {number} [imageHeight=0] 高度
* @returns 新的 url 地址
*/
-export const getCompressImgUrl = function (url, imageWidth = 0, imageHeight = 0) {
+export function getCompressImgUrl(
+ url: string | { width?: number; height?: number; url?: string; replace?: Function },
+ imageWidth = 0,
+ imageHeight = 0,
+): string {
// 游戏内无法加载http,统一替换
- url = url?.replace('http:', 'https:');
+ url = url?.replace?.('http:', 'https:');
if (typeof url === 'object') {
imageWidth = url.width ? url.width : 0;
imageHeight = url.height ? url.height : 0;
url = url.url ? url.url : '';
}
- // 如果是腾讯云的图片实现按需加载(1倍的时候感觉图片有点糊,放大到2倍)
- const isTencentCloudPic = url
- && (url.indexOf('.myqcloud.com/') !== -1 || url.indexOf('cyberimage.sgameglobal.com/') !== -1)
- && url.indexOf('?') === -1;
- if (isTencentCloudPic) {
- let width = 0;
- let height = 0;
- if (imageWidth && imageHeight) {
- width = imageWidth > 0 ? (imageWidth * 2) : 0;
- height = imageHeight > 0 ? (imageHeight * 2) : 0;
- }
-
- // width和height都按10取整,解决图片大小微微改变的时候,图片闪烁的问题
- width = formatInt(width, 1, true);
- height = formatInt(height, 1, true);
- // 有时候图片没设置长宽,导致图片100%时图片过大,选择宽度优先
- if (width > 200 && height > 200 && width === height) {
- height = 0;
- }
-
- if (width < 10 && height < 10) {
- width = 0;
- height = 0;
- }
-
- if (width > 150 || height > 150) {
- url = `${url}?imageMogr2/format/yjpeg/quality/80/thumbnail/!${width > 0 ? width.toString() : ''}x${height > 0 ? height.toString() : ''}r`;
- } else if (width > 0 || height > 0) {
- url = `${url}?imageMogr2/thumbnail/!${width > 0 ? width.toString() : ''}x${height > 0 ? height.toString() : ''}r`;
- }
- return url;
- }
- return url;
-};
+ url = getCompressTencentImgUrl(url as string, imageWidth, imageHeight);
+ return url as string;
+}
-const formatInt = function (num, prec = 2, ceil = true) {
+const formatInt = function (num: number, prec = 2, ceil = true) {
const len = String(num).length;
if (len <= prec) {
return num;
@@ -184,7 +212,7 @@ const formatInt = function (num, prec = 2, ceil = true) {
* @param {number} [imageHeight=0] 高度
* @returns 新的 url 地址
*/
-export const tinyImage = function (url, imageWidth = 0, imageHeight = 0) {
+export const tinyImage = function (url: string, imageWidth = 0, imageHeight = 0) {
url = getHttpsUrl(url);
url = getCdnUrl(url);
url = getCompressImgUrl(url, imageWidth, imageHeight);
@@ -192,7 +220,13 @@ export const tinyImage = function (url, imageWidth = 0, imageHeight = 0) {
};
-const supportsWebp = ({ createImageBitmap, Image }) => {
+const supportsWebp = ({
+ createImageBitmap,
+ Image,
+}: {
+ createImageBitmap: Function;
+ Image: any
+}) => {
if (!createImageBitmap || !Image) return Promise.resolve(false);
return new Promise((resolve) => {
diff --git a/src/index.ts b/src/index.ts
index 7947f763..1afba60d 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -3,6 +3,7 @@ export * from './bite';
export * from './build-upload';
export * from './bundle-analyze';
export * from './canvas';
+export * from './change-log';
export * from './city';
export * from './clipboard';
export * from './color';
@@ -21,6 +22,7 @@ export * from './e2e-test';
export * from './env';
export * from './env-variable';
export * from './eslint-parser';
+export * from './fs';
export * from './functional-component';
export * from './git';
export * from './i18n';
@@ -41,7 +43,9 @@ export * from './node-img';
export * from './npm-tip';
export * from './open-source-report';
export * from './pages-statistics';
+export * from './path';
export * from './pipeline';
+export * from './polling';
export * from './promise';
export * from './publish';
export * from './rainbow';
diff --git a/src/launch-game/game-ddz.ts b/src/launch-game/game-ddz.ts
index 8ff0f7a8..66a6f5c0 100644
--- a/src/launch-game/game-ddz.ts
+++ b/src/launch-game/game-ddz.ts
@@ -2,6 +2,7 @@ import { getWxGameCircleUrl, launchInWX } from './helper';
import { getUrlPara } from '../url/url';
import { GAME_MAP } from '../launch-app/config';
import { initEnv } from '../env/env';
+import type { IBaseLaunchParams } from './types';
function ddzScheme({
@@ -9,6 +10,11 @@ function ddzScheme({
seriesId,
uin,
env,
+}: {
+ gameId: string | number;
+ seriesId: string | number;
+ uin: string | number;
+ env: Record;
}) {
const schemeHost = env.isIOS ? 'wx76fc280041c16519' : 'qqgame.hlddz.scheme';
@@ -68,7 +74,11 @@ export const launchDDZGameRoom = ({
wxJSLink = 'https://res2.wx.qq.com/open/js/jweixin-1.6.0.js',
env = initEnv(),
-}) => {
+}: {
+ gameId: string;
+ seriesId: string;
+ uin: string;
+} & IBaseLaunchParams) => {
const {
schemeUrl,
schemeParam,
diff --git a/src/launch-game/game-gn.ts b/src/launch-game/game-gn.ts
index fdad2ba0..680fdb46 100644
--- a/src/launch-game/game-gn.ts
+++ b/src/launch-game/game-gn.ts
@@ -5,6 +5,8 @@ import {
GAME_SCHEME_PREFIX_MAP,
DEFAULT_WX_JS_SDK,
} from './helper';
+import type { IBaseLaunchParams } from './types';
+
/**
* 拉起 GN
@@ -38,6 +40,9 @@ export function launchGNGameRoom({
wxJSLink = DEFAULT_WX_JS_SDK,
env = initEnv(),
+}: IBaseLaunchParams & {
+ roomId: string;
+ roomPwd: string;
}) {
const schemeParam = getGPSchemeParam(roomId, roomPwd);
diff --git a/src/launch-game/game-gp.ts b/src/launch-game/game-gp.ts
index 6df152c4..d582cbe5 100644
--- a/src/launch-game/game-gp.ts
+++ b/src/launch-game/game-gp.ts
@@ -5,6 +5,7 @@ import {
GAME_SCHEME_PREFIX_MAP,
DEFAULT_WX_JS_SDK,
} from './helper';
+import type { IBaseLaunchParams } from './types';
/**
@@ -39,6 +40,9 @@ export function launchGPGameRoom({
wxJSLink = DEFAULT_WX_JS_SDK,
env = initEnv(),
+}: IBaseLaunchParams & {
+ roomId: string;
+ roomPwd: string;
}) {
const schemeParam = getGPSchemeParam(roomId, roomPwd);
diff --git a/src/launch-game/game-mj.ts b/src/launch-game/game-mj.ts
index 0c38d03e..3b20e2f2 100644
--- a/src/launch-game/game-mj.ts
+++ b/src/launch-game/game-mj.ts
@@ -4,12 +4,17 @@ import {
GAME_SCHEME_PREFIX_MAP,
DEFAULT_WX_JS_SDK,
} from './helper';
+import type { IBaseLaunchParams } from './types';
function getMJSchemeParam({
seriesId,
gameId,
uin,
+}: {
+ gameId: string;
+ seriesId: string;
+ uin: string;
}) {
const schemeParam = `firmMatch=1&seriesid=${seriesId}&gameid=${gameId}&uin=${uin}`;
@@ -52,6 +57,10 @@ export function launchMJGameRoom({
wxJSLink = DEFAULT_WX_JS_SDK,
env = initEnv(),
+}: IBaseLaunchParams & {
+ gameId: string;
+ seriesId: string;
+ uin: string;
}) {
const schemeParam = getMJSchemeParam({
seriesId,
diff --git a/src/launch-game/helper.ts b/src/launch-game/helper.ts
index 2a04abec..4bd3cbc7 100644
--- a/src/launch-game/helper.ts
+++ b/src/launch-game/helper.ts
@@ -5,6 +5,7 @@ import { loader } from '../loader/little-loader';
import { initEnv } from '../env/env';
import { closeMsdkWebview } from '../msdk/msdk';
import { GAME_MAP } from '../launch-app/config';
+import type { IBaseLaunchParams } from './types';
export const GAME_SCHEME_PREFIX_MAP = {
@@ -23,19 +24,19 @@ const gidAppIdMap = {
[GAME_MAP.GP.GID]: 'wxc4c0253df149f02d',
} as const;
-export function getWxGameCircleUrl(gid) {
- const appId = gidAppIdMap[gid];
+export function getWxGameCircleUrl(gid: string | number) {
+ const appId = gidAppIdMap[gid as keyof typeof gidAppIdMap];
return ` https://game.weixin.qq.com/cgi-bin/h5/static/gamecenter/detail.html?appid=${appId}&ssid=39&autoinstall=1&type=1#wechat_redirect`;
}
-export function getGPSchemeParam(roomId, roomPwd) {
+export function getGPSchemeParam(roomId: string | number, roomPwd: string | number) {
const time = Math.floor(new Date().getTime() / 60000);
const schemeParam = `rmid:${roomId},rmpw:${roomPwd},t:${time}`;
return schemeParam;
}
-function getQRcodeUrl(launchParams) {
+function getQRcodeUrl(launchParams: Record) {
const qrCodeUrl = composeUrlQuery(window.location.href, {
enterGame: true,
...(launchParams || {}),
@@ -61,15 +62,10 @@ export function launchInWX({
wxJSLink: string;
schemeUrl: string;
schemeParam: string;
- launchParams?: Record;
- context?: any;
- qrCodeLib?: any;
- dialogHandler?: any
- otherDialogParams?: object;
resolve: Function;
reject: Function;
-}) {
+} & IBaseLaunchParams) {
loader(wxJSLink, () => {
window.WeixinJSBridge.invoke(
'launchApplication', {
@@ -77,7 +73,7 @@ export function launchInWX({
extInfo: schemeParam,
parameter: schemeParam,
},
- (res) => {
+ (res: any) => {
console.info('[launchCore wx] res: ', res);
if (res.err_msg.indexOf('ok') === -1) {
@@ -109,14 +105,14 @@ function showQRcode({
qrCodeLib, // qrcode npm library
dialogHandler,
otherDialogParams = {},
-}) {
- const qrCodeUrl = getQRcodeUrl(launchParams);
+}: IBaseLaunchParams) {
+ const qrCodeUrl = getQRcodeUrl(launchParams || {});
console.info('[showQRcode] url', qrCodeUrl);
if (!dialogHandler || !qrCodeLib) return;
qrCodeLib.toDataURL(qrCodeUrl)
- .then((url) => {
+ .then((url: string) => {
dialogHandler.show({
context,
title: '提示',
@@ -128,7 +124,7 @@ function showQRcode({
});
console.info(url);
})
- .catch((err) => {
+ .catch((err: any) => {
console.error(err);
});
}
@@ -146,6 +142,9 @@ export function launchCore({
schemePrefix = '',
wxJSLink = 'https://res.wx.qq.com/open/js/jweixin-1.4.0.js',
env = initEnv(),
+}: IBaseLaunchParams & {
+ schemePrefix?: string;
+ schemeParam?: any;
}) {
// const time = Math.floor(new Date().getTime() / 60000);
diff --git a/src/launch-game/types.ts b/src/launch-game/types.ts
new file mode 100644
index 00000000..1c91f090
--- /dev/null
+++ b/src/launch-game/types.ts
@@ -0,0 +1,11 @@
+export type IBaseLaunchParams = {
+ context?: any;
+ qrCodeLib?: any;
+ dialogHandler?: any;
+ otherDialogParams?: Record;
+
+ launchParams?: Record;
+
+ wxJSLink?: string;
+ env?: Record;
+};
diff --git a/src/loader/loader-unity.ts b/src/loader/loader-unity.ts
index e79158da..1c266983 100644
--- a/src/loader/loader-unity.ts
+++ b/src/loader/loader-unity.ts
@@ -8,7 +8,7 @@ import { loadJS as loaderPromise } from './loader';
* @param {function} [cb] 回调
* @returns {Promise} promise
*/
-export const loaderUnity = (source, cb, ...args) => {
+export const loaderUnity = (source: string, cb: Function, ...args: Array) => {
if (typeof cb === 'function') {
return loaderCb.call(this, source, cb, ...args);
}
diff --git a/src/location/location-handle-web.ts b/src/location/location-handle-web.ts
index 643836fb..d34fb6b5 100644
--- a/src/location/location-handle-web.ts
+++ b/src/location/location-handle-web.ts
@@ -7,7 +7,7 @@ import H5GeolocationLocation from './platform/h5-geolocation-location';
import MsdkLocation from './platform/msdk-location';
import SlugSdkLocation from './platform/slug-sdk-location';
-function locationHandle(options) {
+function locationHandle(options: any): any {
const { isInGame, isMsdkX, isWeixin, isSlugSdk, isMiniProgram } = getEnvUAType();
let handle;
if (options.useWxSdk && isWeixin) {
@@ -28,7 +28,7 @@ function locationHandle(options) {
return handle;
}
-locationHandle.failHandle = function (options, handle) {
+locationHandle.failHandle = function (options: any, handle: any) {
if (options.useTencentMapIfFail
&& handle
&& handle instanceof TipSdkLocation) {
diff --git a/src/location/location-interface.ts b/src/location/location-interface.ts
index 4a6a82e1..49f3df59 100644
--- a/src/location/location-interface.ts
+++ b/src/location/location-interface.ts
@@ -46,7 +46,7 @@ export interface LocationOptions {
forceUpdateLocation: boolean, // 是否忽略缓存,强制刷新定位信息
Dialog?: { // 提示弹窗
- confirm: (any) => Promise;
+ confirm: (_: any) => Promise;
};
useMsdkLocation?: boolean; // 是否使用msdk定位,中间层自己限定某些游戏
msdkLocationReqStr?: string; // msdk定位时,传递的reqData,默认为 JSON.stringify({ cmd: 'reqLocation' })
diff --git a/src/location/location-storage.ts b/src/location/location-storage.ts
index 3ccc8601..a201ae36 100644
--- a/src/location/location-storage.ts
+++ b/src/location/location-storage.ts
@@ -31,7 +31,7 @@ export default class LocationStorage {
}
// 存储缓存位置信息到sessionStorage和localStorage
- public static setLocationToStorage(location: LocationData, expireMS): void {
+ public static setLocationToStorage(location: LocationData, expireMS: number): void {
window.sessionStorage.setItem('position', JSON.stringify(location));
savePersist('position', JSON.stringify(location), expireMS);
}
diff --git a/src/location/location-web.ts b/src/location/location-web.ts
index 8f925f81..b8c4a84b 100644
--- a/src/location/location-web.ts
+++ b/src/location/location-web.ts
@@ -149,7 +149,7 @@ export class LocationWeb {
}
// 特殊处理下特权sdk定位失败,降级到腾讯地图定位
- const failCallback = (error) => {
+ const failCallback = (error: any) => {
const failHandle = locationHandle.failHandle(options, this.getInstance().locationHandle);
if (failHandle) {
this.getInstance().locationHandle = failHandle;
@@ -188,7 +188,7 @@ export class LocationWeb {
* @param {object} options 定位配置信息
* @private
*/
- private static storeLocationInfo(location, options) {
+ private static storeLocationInfo(location: any, options: any) {
// 缓存位置信息
if (location) {
// 定位成功后,再读取当前时间,并存储
diff --git a/src/location/platform/h5-geolocation-location.ts b/src/location/platform/h5-geolocation-location.ts
index f85321bc..95d415ac 100644
--- a/src/location/platform/h5-geolocation-location.ts
+++ b/src/location/platform/h5-geolocation-location.ts
@@ -3,7 +3,7 @@ import { LocationInterface, LocationFlag, LocationResult } from '../location-int
export default class TencentMapApiLocation implements LocationInterface {
getLocation(): Promise {
return new Promise((resolve, reject) => {
- function geoShowPosition(position) {
+ function geoShowPosition(position: any) {
if (position) {
const location = { lat: position.coords.latitude, lng: position.coords.longitude };
resolve({ location, flag: LocationFlag.LocationSuccess });
@@ -12,7 +12,7 @@ export default class TencentMapApiLocation implements LocationInterface {
}
}
- function geoShowError(error) {
+ function geoShowError(error: any) {
console.log(`getPosError:${error.code},${navigator.geolocation},${error.message}`);
reject();
}
diff --git a/src/location/platform/miniprogram-location.ts b/src/location/platform/miniprogram-location.ts
index c11d4965..b032eeb1 100644
--- a/src/location/platform/miniprogram-location.ts
+++ b/src/location/platform/miniprogram-location.ts
@@ -8,7 +8,7 @@ export default class TencentMapApiLocation implements LocationInterface {
// @ts-ignore
wx.getLocation({
type: 'gcj02',
- success(res) {
+ success(res: any) {
const location = {
lat: parseFloat(`${res.latitude}`),
lng: parseFloat(`${res.longitude}`),
@@ -16,7 +16,7 @@ export default class TencentMapApiLocation implements LocationInterface {
TencentMapApiLocation.lastLocation = location;
resolve({ location, flag: LocationFlag.LocationSuccess });
},
- fail(error) {
+ fail(error: any) {
console.log('MiniProgramLocation', error);
// 频繁调用导致失败,返回最后一次location
if (error.errMsg && error.errMsg.indexOf('频繁调用') > -1) {
diff --git a/src/location/platform/msdk-location.ts b/src/location/platform/msdk-location.ts
index ef07c495..2c5515ae 100644
--- a/src/location/platform/msdk-location.ts
+++ b/src/location/platform/msdk-location.ts
@@ -12,7 +12,7 @@ export default class MsdkLocation implements LocationInterface {
// && (ConfigInfo.instance.getTipGid() === GAME_HLDDZ || ConfigInfo.instance.getTipGid() === GAME_GP)
) {
callJsBrowserAdapter().then(() => {
- addMsdkNativeCallbackListener((data) => {
+ addMsdkNativeCallbackListener((data: any) => {
console.log('addMsdkNativeCallbackListener', data);
const response = JSON.parse(data);
if (response?.cmd === 'reqLocation') {
diff --git a/src/location/platform/slug-sdk-location.ts b/src/location/platform/slug-sdk-location.ts
index 1c044ede..0544b656 100644
--- a/src/location/platform/slug-sdk-location.ts
+++ b/src/location/platform/slug-sdk-location.ts
@@ -6,7 +6,7 @@ export default class SlugSdkLocation implements LocationInterface {
return new Promise((resolve, reject) => {
callJsBrowserAdapter().then(() => {
if (typeof window.customBrowserInterface === 'object') {
- window.customBrowserInterface.getLocationInfo((result) => {
+ window.customBrowserInterface.getLocationInfo((result: any) => {
if (result?.code == 1) {
const location = { lat: result.latitude, lng: result.longitude };
resolve({ location, flag: LocationFlag.LocationSuccess });
diff --git a/src/location/platform/tencent-map-location.ts b/src/location/platform/tencent-map-location.ts
index 5843bc8b..4deb6a40 100644
--- a/src/location/platform/tencent-map-location.ts
+++ b/src/location/platform/tencent-map-location.ts
@@ -13,7 +13,7 @@ import { getAreaCode } from '../../city/city';
export default class TencentMapLocation implements LocationInterface {
public getLocation(options: LocationOptions): Promise {
return new Promise((resolve, reject) => {
- function geoShowPosition(location) {
+ function geoShowPosition(location: any) {
if (!!location.province && !!location.city) {
const retList = getAreaCode(location.province, location.city);
if (retList.length > 1) {
diff --git a/src/location/platform/wechat-sdk-location.ts b/src/location/platform/wechat-sdk-location.ts
index d3d2e8dc..aba669b0 100644
--- a/src/location/platform/wechat-sdk-location.ts
+++ b/src/location/platform/wechat-sdk-location.ts
@@ -14,7 +14,7 @@ export default class WechatSdkLocation implements LocationInterface {
options.configWx?.(['getLocation', 'openLocation'], []).then((wx) => {
const tmp = {
type: 'gcj02',
- success(res) {
+ success(res: any) {
const location = {
lat: parseFloat(res.latitude),
lng: parseFloat(res.longitude),
@@ -22,7 +22,7 @@ export default class WechatSdkLocation implements LocationInterface {
resolve({ location, flag: LocationFlag.LocationSuccess });
locationSuccessFlag = true;
},
- fail(error) {
+ fail(error: any) {
console.log('WechatSdkLocation', error);
reject();
locationSuccessFlag = false;
diff --git a/src/mixin/index.ts b/src/mixin/index.ts
index 9d0a11a0..b080ef43 100644
--- a/src/mixin/index.ts
+++ b/src/mixin/index.ts
@@ -1 +1,2 @@
+export { morsePwdMixin, getMorsePwdMixin } from './morse-password-mixin';
export { getVisibilityChangeMixin } from './visibllity-change-mixin';
diff --git a/src/mixin/morse-password-mixin.ts b/src/mixin/morse-password-mixin.ts
index 59d65f8e..5760fd31 100644
--- a/src/mixin/morse-password-mixin.ts
+++ b/src/mixin/morse-password-mixin.ts
@@ -1,6 +1,19 @@
import { MorsePwd } from '../morse-pwd';
+/**
+ * 摩斯密码的 Vue mixin,方便实用
+ * @param {array} pwd 密钥
+ * @param {Function} cb 回到函数
+ * @returns 换入内容
+ * @example
+ * ```ts
+ * getMorsePwdMixin([1, 1, 1, 1, 1], function () {
+ * if (isInIFrame()) return;
+ * this.onShowLaunchApp();
+ * }),
+ * ```
+ */
export const getMorsePwdMixin = (pwd: number[], cb: Function) => ({
data() {
return {
@@ -32,3 +45,5 @@ export const getMorsePwdMixin = (pwd: number[], cb: Function) => ({
},
},
} as any);
+
+export const morsePwdMixin = getMorsePwdMixin;
diff --git a/src/mp-ci/helper.ts b/src/mp-ci/helper.ts
index 56cf3593..32bb1556 100644
--- a/src/mp-ci/helper.ts
+++ b/src/mp-ci/helper.ts
@@ -11,6 +11,11 @@ export function getInnerBundleBuildDesc({
branch,
author,
message,
+}: {
+ env: string;
+ branch: string;
+ author: string;
+ message: string;
}) {
const buildDesc = genRobotMessage([
[
diff --git a/src/mp-ci/mp-upload-and-report.ts b/src/mp-ci/mp-upload-and-report.ts
index e5f3256c..e018bd9f 100644
--- a/src/mp-ci/mp-upload-and-report.ts
+++ b/src/mp-ci/mp-upload-and-report.ts
@@ -4,11 +4,11 @@ import { MpCI } from './mp-ci';
import { getInnerBundleBuildDesc } from './helper';
-function flattenSubPackages(result) {
+function flattenSubPackages(result: {subPackageInfo: Array<{name: any}>}) {
const {
subPackageInfo = [],
} = result;
- return subPackageInfo.reduce((acc, item) => {
+ return subPackageInfo.reduce((acc: Record, item) => {
acc[item.name] = item;
return acc;
}, {});
@@ -31,7 +31,7 @@ async function reportToRd({
bkStartType,
bkBuildUrl,
bkPipelineId,
-}) {
+}: Record) {
if (!bundleInfo || !bundleInfo.__APP__) return;
const mainBundleSize = parseInt(`${(bundleInfo.__APP__?.size || 0) / 1024}`, 10);
const totalBundleSize = parseInt(`${(bundleInfo.__FULL__?.size || 0) / 1024}`, 10);
@@ -107,7 +107,7 @@ export async function mpUploadAndReport({
commitInfo,
version,
buildDesc,
-}) {
+}: Record) {
const rainbowSecretInfo = {
appId: rainbowAppId,
envName: rainbowEnvName,
@@ -188,7 +188,7 @@ export async function mpUploadAndReport({
}
-export async function mpUploadAndReportByOptions(options) {
+export async function mpUploadAndReportByOptions(options: Record) {
console.log('[options] ', options);
const {
branch,
diff --git a/src/mp-ci/write-env-and-private-key.ts b/src/mp-ci/write-env-and-private-key.ts
index 124d279b..d91d0c81 100644
--- a/src/mp-ci/write-env-and-private-key.ts
+++ b/src/mp-ci/write-env-and-private-key.ts
@@ -1,10 +1,14 @@
import * as fs from 'fs';
import * as path from 'path';
import { fetchRainbowConfig } from '../rainbow/rainbow-user';
+import { writeFileSync } from '../fs/fs';
// 从七彩石获取CI配置
-export async function getCIConfig(rainbowConfigKey, rainbowSecretInfo): Promise {
+export async function getCIConfig(
+ rainbowConfigKey: string,
+ rainbowSecretInfo: Parameters[1],
+): Promise {
let res = {};
const str = await fetchRainbowConfig(rainbowConfigKey, rainbowSecretInfo);
try {
@@ -34,7 +38,7 @@ export function getRobot({
// 写入环境变量
-function writeEnv(robot, localEnv = '') {
+function writeEnv(robot: number, localEnv = '') {
fs.writeFileSync('.env.local', `
${localEnv}
VUE_APP_AUTHOR=CI Robot ${robot}
@@ -46,12 +50,10 @@ VUE_APP_AUTHOR=CI Robot ${robot}
// 写入密钥
-function writePrivateKey(root, privateKey) {
+function writePrivateKey(root: string, privateKey: string) {
const nRoot = root || process.cwd();
- fs.writeFileSync(path.resolve(nRoot, 'private.key'), privateKey, {
- encoding: 'utf-8',
- });
+ writeFileSync(path.resolve(nRoot, 'private.key'), privateKey);
}
@@ -64,7 +66,7 @@ export async function writeEnvAndPrivateKey({
rainbowAppId,
rainbowEnvName,
rainbowGroupName,
-}) {
+}: Record<'branch' | 'env' | 'rainbowConfigKey' | 'rainbowAppId' | 'rainbowEnvName' | 'rainbowGroupName' | 'root', string>) {
const rainbowSecretInfo = {
appId: rainbowAppId,
envName: rainbowEnvName,
@@ -94,7 +96,7 @@ export async function writeEnvAndPrivateKey({
}
-export async function writeEnvAndPrivateKeyByOptions(options) {
+export async function writeEnvAndPrivateKeyByOptions(options: any) {
console.log('[options] ', options);
const {
branch,
diff --git a/src/msdk/index.ts b/src/msdk/index.ts
index 67dc1703..e6b7acbe 100644
--- a/src/msdk/index.ts
+++ b/src/msdk/index.ts
@@ -6,7 +6,11 @@ export {
sendToMsdkNative,
addMsdkNativeCallbackListener,
removeMsdkNativeCallbackListener,
+
closeMsdkWebview,
closeWebView,
+
callJsBrowserAdapter,
+ callJsReSetFullScreen,
+ callJsSetFullScreen,
} from './msdk';
diff --git a/src/msdk/mini-program.ts b/src/msdk/mini-program.ts
index 65963563..6b91c70a 100644
--- a/src/msdk/mini-program.ts
+++ b/src/msdk/mini-program.ts
@@ -1,7 +1,7 @@
import { callJsBrowserAdapter } from './msdk';
import { initEnv } from '../env/env';
-export function launchMiniProgramInSlugSdk(appId, path) {
+export function launchMiniProgramInSlugSdk(appId: string, path: string) {
if (typeof window.customBrowserInterface === 'undefined') {
callJsBrowserAdapter().then(() => {
window.customBrowserInterface?.openMiniProgram(appId, path);
@@ -12,8 +12,8 @@ export function launchMiniProgramInSlugSdk(appId, path) {
}
export function launchMiniProgramInGame({
- appId,
- path,
+ appId = '',
+ path = '',
type = 0,
isWxMp = true,
}) {
diff --git a/src/msdk/msdk.ts b/src/msdk/msdk.ts
index a0debbda..7663e19c 100644
--- a/src/msdk/msdk.ts
+++ b/src/msdk/msdk.ts
@@ -1,7 +1,14 @@
-import { initEnv } from '../env/env';
+import { initEnv, getEnvUAType } from '../env/env';
import { loader } from '../loader/little-loader';
+/**
+ * MSDK 浏览器中,向原生发送数据
+ * @param {string} data 发送的数据
+ * ```ts
+ * sendToMsdkNative('123')
+ * ```
+ */
export function sendToMsdkNative(data = '') {
const env = initEnv();
@@ -38,6 +45,13 @@ export function removeMsdkNativeCallbackListener(callback: Function) {
}
}
+/**
+ * MSDK 浏览器中,关闭 webView
+ * @example
+ * ```ts
+ * closeMsdkWebview()
+ * ```
+ */
export function closeMsdkWebview(env?: any) {
if (!env) {
env = initEnv();
@@ -61,6 +75,14 @@ export function closeMsdkWebview(env?: any) {
}
}
+
+/**
+ * 关闭 webView,包含 msdk 浏览器和其他浏览器
+ * @example
+ * ```ts
+ * closeWebView()
+ * ```
+ */
export function closeWebView() {
console.log('[closeWebView] call close webview');
const env = initEnv();
@@ -78,6 +100,10 @@ export function closeWebView() {
/**
* 添加游戏内浏览器jssdk
+ * @example
+ * ```ts
+ * callJsBrowserAdapter();
+ * ```
*/
export function callJsBrowserAdapter() {
return new Promise((resolve) => {
@@ -103,3 +129,70 @@ export function callJsBrowserAdapter() {
}
});
}
+
+/**
+ * 设置 MSDK 浏览器退出全屏,需提前加载 sdk
+ * @example
+ * ```ts
+ * callJsReSetFullScreen();
+ * ```
+ */
+export const callJsReSetFullScreen = function () {
+ callJsSetFullScreen(false);
+};
+
+/**
+ * 设置 MSDK 浏览器全屏,需提前加载 sdk
+ * @param isFullScreen 是否全屏
+ * @example
+ * ```ts
+ * callJsSetFullScreen();
+ * callJsSetFullScreen(false);
+ * ```
+ */
+export const callJsSetFullScreen = function (isFullScreen = true) {
+ const { isSlugSdk, isMsdkV5, isMsdk, isMsdkX, isAndroid } = getEnvUAType();
+
+ if (isSlugSdk) {
+ if (typeof window.customBrowserInterface === 'object') {
+ const method = isFullScreen ? 'hideUi' : 'showUi';
+ window.customBrowserInterface[method]();
+ }
+ } else if (isMsdkV5) {
+ const setFullScreenStr = JSON.stringify({
+ MsdkMethod: 'setFullScreen',
+ isFullScreen: !!isFullScreen,
+ });
+ // 延时设置全屏
+ setTimeout(() => {
+ if (isAndroid) {
+ window.msdkCall?.(setFullScreenStr);
+ } else {
+ if (window.WebViewJavascriptBridge) {
+ window.msdkCall?.(setFullScreenStr);
+ } else {
+ document.addEventListener('WebViewJavascriptBridgeReady', () => {
+ window.msdkCall?.(setFullScreenStr);
+ }, false);
+ }
+ }
+ }, 100);
+ } else if (isMsdk && !isMsdkX) {
+ const setFullScreenStr = JSON.stringify({
+ MsdkMethod: 'WGSetFullScreen',
+ isFullScreen: !!isFullScreen,
+ });
+
+ if (isAndroid) {
+ window.msdkCall?.('WGSetFullScreen', setFullScreenStr);
+ } else {
+ if (window.WebViewJavascriptBridge) {
+ window.msdkCall?.('WGSetFullScreen', setFullScreenStr);
+ } else {
+ document.addEventListener('WebViewJavascriptBridgeReady', () => {
+ window.msdkCall?.('WGSetFullScreen', setFullScreenStr);
+ }, false);
+ }
+ }
+ }
+};
diff --git a/src/node/comment-json.ts b/src/node/comment-json.ts
index a72850b1..ec3e3d32 100644
--- a/src/node/comment-json.ts
+++ b/src/node/comment-json.ts
@@ -5,7 +5,7 @@ import * as fs from 'fs';
* @param content 原始文件内容
* @returns json数据
*/
-export function parseCommentJson(content) {
+export function parseCommentJson(content: string) {
const newContent = content.replace(/(?:\s+|^)\/\/[^\n]*/g, '');
// console.log('[newContent]', newContent);
@@ -23,7 +23,7 @@ export function parseCommentJson(content) {
* @param file 文件路径
* @returns json数据
*/
-export function readCommentJson(file) {
+export function readCommentJson(file: string) {
const content = fs.readFileSync(file, {
encoding: 'utf-8',
});
diff --git a/src/node/fs-util.ts b/src/node/fs-util.ts
index 14906f22..8b59c0f4 100644
--- a/src/node/fs-util.ts
+++ b/src/node/fs-util.ts
@@ -1,5 +1,6 @@
import * as path from 'path';
import * as fs from 'fs';
+import { writeFileSync, readFileSync } from '../fs/fs';
const LOG_DIR = 'log';
@@ -13,7 +14,7 @@ function innerCopy(src: string, dist: string) {
const tDist = `${dist}/${p}`;
const stat = fs.statSync(tSrc);
if (stat.isFile()) { // 判断是文件还是目录
- fs.writeFileSync(tDist, fs.readFileSync(tSrc));
+ writeFileSync(tDist, readFileSync(tSrc));
} else if (stat.isDirectory()) {
innerCopyDir(tSrc, tDist); // 当是目录是,递归复制
}
@@ -109,7 +110,7 @@ export function rmEmptyDir(tPath: string, level = 0) {
* @param {Object} to 拷贝到那里
*/
export function copyFile(from: string, to: string) {
- return fs.writeFileSync(to, fs.readFileSync(from));
+ return writeFileSync(to, readFileSync(from));
}
@@ -140,9 +141,7 @@ export function readJsonLog(file: string, defaultContent = '{}') {
return defaultContent;
}
- return fs.readFileSync(filePath, {
- encoding: 'utf-8',
- }) || defaultContent;
+ return readFileSync(filePath) || defaultContent;
}
export function getJsonLogDir() {
@@ -152,9 +151,7 @@ export function getJsonLogDir() {
export function saveJsonToLog(content: object, file: string, needLog = true) {
if (!needLog) return;
createLogDir();
- fs.writeFileSync(`./${LOG_DIR}/${file}`, JSON.stringify(content, null, 2), {
- encoding: 'utf-8',
- });
+ writeFileSync(`./${LOG_DIR}/${file}`, content, true);
}
export function getJsonFromLog(file: string) {
diff --git a/src/npm-tip/npm-tip.ts b/src/npm-tip/npm-tip.ts
index a863fe7b..51f07aae 100644
--- a/src/npm-tip/npm-tip.ts
+++ b/src/npm-tip/npm-tip.ts
@@ -12,11 +12,17 @@ function getNpmTipTemplate({
postfix,
feedbackTitle,
feedbackList,
+}: {
+ prefix: string;
+ link: string;
+ postfix: string;
+ feedbackTitle: string;
+ feedbackList: Array;
}) {
return `${colorFactory(96)}${prefix} (${colorFactory(94)} ${link} ${colorFactory(96)}) ${postfix}${colorFactory()}\n\n`
+ `${colorFactory(96)}${feedbackTitle}${colorFactory()}\n`
+ `${feedbackList
- .map(feedback => `${colorFactory(96)}>${colorFactory(94)} ${feedback} ${colorFactory()}`)
+ .map((feedback: string) => `${colorFactory(96)}>${colorFactory(94)} ${feedback} ${colorFactory()}`)
.join('\n')
}\n`;
}
@@ -28,6 +34,12 @@ function getNpmTips({
packagePostfix,
packagePostfixEn,
feedbackList,
+}: {
+ packageName: string;
+ packageLink: string;
+ packagePostfix: string;
+ packagePostfixEn: string;
+ feedbackList: Array;
}) {
const content = isUtf8Encoding()
? getNpmTipTemplate({
@@ -76,7 +88,7 @@ function isUtf8Encoding() {
return false;
}
-function isShowInfo(kContent) {
+function isShowInfo(kContent: string) {
// eslint-disable-next-line @typescript-eslint/naming-convention
const { env: { ADBLOCK, CI, DISABLE_OPENCOLLECTIVE, OPEN_SOURCE_CONTRIBUTOR, npm_config_loglevel } } = process;
const isSilent = typeof npm_config_loglevel === 'string' && ['silent', 'error', 'warn'].includes(npm_config_loglevel);
@@ -113,6 +125,12 @@ export function npmInstallTip({
packagePostfix,
packagePostfixEn,
feedbackList,
+}: {
+ packageName: string;
+ packageLink: string;
+ packagePostfix: string;
+ packagePostfixEn: string;
+ feedbackList: Array;
}) {
const content = getNpmTips({
packageName,
diff --git a/src/path/index.ts b/src/path/index.ts
new file mode 100644
index 00000000..980da2f4
--- /dev/null
+++ b/src/path/index.ts
@@ -0,0 +1 @@
+export { normalizePath } from './path';
diff --git a/src/path/path.ts b/src/path/path.ts
new file mode 100644
index 00000000..09ddf63c
--- /dev/null
+++ b/src/path/path.ts
@@ -0,0 +1,14 @@
+import { isWindows } from '../validate/validate';
+
+/**
+ * 格式化路径
+ * @param path 文件路径,或目录路径
+ * @returns 格式化后的路径
+ * @example
+ * ```ts
+ * normalizePath('xxx/xxx/xxx');
+ *
+ * normalizePath('xxx\\xxx\\xxx');
+ * ```
+ */
+export const normalizePath = (path: string) => (isWindows() ? path.replace(/\\/g, '/') : path);
diff --git a/src/polling/index.ts b/src/polling/index.ts
new file mode 100644
index 00000000..5a66b01b
--- /dev/null
+++ b/src/polling/index.ts
@@ -0,0 +1 @@
+export { PollingRequest } from './polling';
diff --git a/src/polling/polling.ts b/src/polling/polling.ts
new file mode 100644
index 00000000..9472e97b
--- /dev/null
+++ b/src/polling/polling.ts
@@ -0,0 +1,61 @@
+
+
+class PollingRequest {
+ maxRequest: number;
+ maxPollingTime: number;
+ timeInterval: number;
+
+ timer: any;
+
+
+ /**
+ * 轮询
+ * @constructor
+ * @param {number} [maxPollingTime=10] 最大轮询次数
+ * @param {number} [timeInterval=2000] 轮询间隔
+ * @example
+ *
+ * ```ts
+ * const polling = new PollingRequest(10);
+ * const cb = () => {
+ * this.onGetTeamList(true);
+ * };
+ * polling.polling(cb);
+ * ```
+ */
+ constructor(maxPollingTime = 10, timeInterval = 2000) {
+ this.maxRequest = 0;
+ this.maxPollingTime = maxPollingTime;
+ this.timeInterval = timeInterval;
+ this.timer = null;
+ }
+
+ /**
+ * 重置,即取消轮询
+ */
+ reset() {
+ this.maxRequest = 0;
+ clearInterval(this.timer);
+ }
+
+ /**
+ * 开始轮询
+ * @param {function} func 轮询方法
+ */
+ polling(func: Function) {
+ this.timer = setInterval(() => {
+ this.maxRequest += 1;
+
+ if (this.maxRequest > this.maxPollingTime) {
+ clearInterval(this.timer);
+ this.maxRequest = 0;
+ } else {
+ func?.();
+ }
+ }, this.timeInterval);
+ }
+}
+
+// 这种导出可以用 jsdoc 生成文档
+// export class XXX 不可以
+export { PollingRequest };
diff --git a/src/publish/helper.ts b/src/publish/helper.ts
index 9454a6d1..c8e9bd9e 100644
--- a/src/publish/helper.ts
+++ b/src/publish/helper.ts
@@ -8,7 +8,7 @@ export function getPublishRootDir() {
return rootDir;
}
-function findPublishSh(dir) {
+function findPublishSh(dir: string) {
const FILE_NAME = 'publish.sh';
const file = path.resolve(dir, FILE_NAME);
diff --git a/src/publish/post-file.ts b/src/publish/post-file.ts
index 1af7e8df..0a11f23d 100644
--- a/src/publish/post-file.ts
+++ b/src/publish/post-file.ts
@@ -4,7 +4,7 @@ import * as fs from 'fs';
import type { IPostFileOptions } from './types';
-export function postFile(fileDataInfo, fileKeyValue, options?: IPostFileOptions) {
+export function postFile(fileDataInfo: any, fileKeyValue: Array, options?: IPostFileOptions) {
return new Promise(((resolve, reject) => {
if (!options) {
console.log('[publish] failed. 需要 options');
diff --git a/src/publish/publish.ts b/src/publish/publish.ts
index 66cf1044..96e6272c 100644
--- a/src/publish/publish.ts
+++ b/src/publish/publish.ts
@@ -123,7 +123,7 @@ async function realPublish({
let env: string = PUBLISH_HOST_ENV.TEST;
const shell: Record = {};
- shell.runSync = function (cmd, args, options) {
+ shell.runSync = function (cmd: string, args: Array, options: Record) {
const shellResult = spawnSync(cmd, args, options);
if (shellResult.status !== 0) {
console.log('[publish] failed: ', shellResult.stderr);
diff --git a/src/rainbow-to-cos/sync-to-cos.ts b/src/rainbow-to-cos/sync-to-cos.ts
index 5b757ae5..9d50305a 100644
--- a/src/rainbow-to-cos/sync-to-cos.ts
+++ b/src/rainbow-to-cos/sync-to-cos.ts
@@ -1,6 +1,8 @@
/* eslint-disable @typescript-eslint/no-require-imports */
import { uploadCOSFile } from '../tencent-cloud/cos';
import { getSavePath, getSaveFileName } from './helper/helper';
+import { writeFileSync } from '../fs/fs';
+
import type { ICosInfo, ISecretInfo, IRemoteConfig } from './types';
@@ -75,7 +77,6 @@ export async function syncRainbowToCOS({
appName: string;
cosInfo: ICosInfo;
}) {
- const fs = require('fs');
const cosKeyList = getCOSKeyAndSavePath({
configList,
secretInfo,
@@ -84,9 +85,7 @@ export async function syncRainbowToCOS({
});
cosKeyList.forEach((item) => {
- fs.writeFileSync(item.savePath, item.value, {
- encoding: 'utf-8',
- });
+ writeFileSync(item.savePath, item.value);
});
const files = pushCOSFiles(cosKeyList);
diff --git a/src/rem-to-px/rem-to-px.ts b/src/rem-to-px/rem-to-px.ts
index d509558f..0b6c0018 100644
--- a/src/rem-to-px/rem-to-px.ts
+++ b/src/rem-to-px/rem-to-px.ts
@@ -1,6 +1,5 @@
-import * as fs from 'fs';
import { transFormRem } from '../rem/rem';
-
+import { writeFileSync, readFileSync } from '../fs/fs';
/**
* 替换文件的 rem 单位,转为 px
@@ -11,13 +10,9 @@ import { transFormRem } from '../rem/rem';
* ```
*/
export function remToPxInFile(filePath: string) {
- const data = fs.readFileSync(filePath, {
- encoding: 'utf-8',
- });
+ const data = readFileSync(filePath);
const newData = transFormRem(data, 50, 'px');
- fs.writeFileSync(filePath, newData, {
- encoding: 'utf-8',
- });
+ writeFileSync(filePath, newData);
}
diff --git a/src/rem/rem.ts b/src/rem/rem.ts
index 8d1b7c0a..40aafdcc 100644
--- a/src/rem/rem.ts
+++ b/src/rem/rem.ts
@@ -18,7 +18,7 @@
* // 10.50px
* ```
*/
-export function transFormRem(content, factor = 100, unit = 'rpx') {
+export function transFormRem(content: string, factor = 100, unit = 'rpx') {
if (content == null) {
return content;
}
diff --git a/src/router/find-route-name.ts b/src/router/find-route-name.ts
index 2c3cfa41..a6e2a749 100644
--- a/src/router/find-route-name.ts
+++ b/src/router/find-route-name.ts
@@ -1,23 +1,25 @@
import pathToRegexp from './path-to-regexp';
+import type { IRoute, IMeta } from './types';
export function getQueryBaseStr(str = '') {
if (!str) {
return {};
}
- return str.split('&').reduce((acc, item) => {
+ return str.split('&').reduce((acc: Record, item: string) => {
const list = item.split('=');
acc[list[0]] = list[1];
return acc;
}, {});
}
-export function isMatchPath(meta, path) {
+export function isMatchPath(meta: IMeta, path: string) {
const { rawPath = [] } = meta;
if (!rawPath?.length) return;
+
for (const item of rawPath) {
// eslint-disable-next-line prefer-const
- let keys = [];
+ let keys: Array = [];
const regexp = pathToRegexp(item, keys);
const match = path.match(regexp);
@@ -46,7 +48,7 @@ export function isMatchPath(meta, path) {
* console.log('name', name);
* ```
*/
-export function findRouteName(path, routes) {
+export function findRouteName(path: string, routes: Array) {
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0;i < routes.length;i++) {
const item = routes[i];
diff --git a/src/router/types.ts b/src/router/types.ts
new file mode 100644
index 00000000..929a4b76
--- /dev/null
+++ b/src/router/types.ts
@@ -0,0 +1,9 @@
+export type IMeta = {
+ rawPath?: Array
+};
+
+export type IRoute = {
+ name?: string;
+ path?: string;
+ meta?: IMeta;
+};
diff --git a/src/scheduler/scheduler.ts b/src/scheduler/scheduler.ts
index f5c66dc8..a557e4b3 100644
--- a/src/scheduler/scheduler.ts
+++ b/src/scheduler/scheduler.ts
@@ -39,7 +39,7 @@ class Scheduler {
this.maxConcurrency = maxConcurrency;
}
- add = promiseCreator => new Promise((resolve, reject) => {
+ add = (promiseCreator: any) => new Promise((resolve, reject) => {
// 关键是给传过来的函数加个回调属性,当resolved的时候,就能返回对应的结果了。
promiseCreator.resolve = resolve;
promiseCreator.reject = reject;
@@ -54,11 +54,11 @@ class Scheduler {
const job = this.pendingState.shift();
job?.()
- .then((res) => {
+ .then((res: any) => {
// @ts-ignore
job.resolve(res);
})
- .catch((e) => {
+ .catch((e: any) => {
// @ts-ignore
job.reject(e);
})
diff --git a/src/storage/persist-data.ts b/src/storage/persist-data.ts
index a92cafab..e64adcf6 100644
--- a/src/storage/persist-data.ts
+++ b/src/storage/persist-data.ts
@@ -15,7 +15,7 @@ import { checkNodeEnv } from '../env/env';
* clearPersist('name'); // true
* const name2 = getPersist('name'); // undefined
*/
-export function savePersist(key, value, expireMsec = 0) {
+export function savePersist(key: string, value: string, expireMsec = 0) {
if (checkNodeEnv()) {
return false;
}
@@ -43,7 +43,7 @@ export function savePersist(key, value, expireMsec = 0) {
* @param {string} key
* @return {string} key对应的值
*/
-export function getPersist(key) {
+export function getPersist(key: string) {
if (checkNodeEnv()) {
return undefined;
}
diff --git a/src/throttle/throttle.ts b/src/throttle/throttle.ts
index dd9b5bdc..7fef9b83 100644
--- a/src/throttle/throttle.ts
+++ b/src/throttle/throttle.ts
@@ -15,10 +15,10 @@
* window.onscroll = throttle(count, 500)
* ```
*/
-export function throttle(fn, time) {
- let timer;
+export function throttle(fn: Function, time: number) {
+ let timer: ReturnType | null;
- return function (...args) {
+ return function (...args: Array) {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
diff --git a/src/uploader/request.ts b/src/uploader/request.ts
index 6795e34b..6373f3d0 100644
--- a/src/uploader/request.ts
+++ b/src/uploader/request.ts
@@ -36,6 +36,11 @@ export function requestUploadFile({
hashCode,
uploadFileKey = UPLOADER_CONFIG.UPLOAD_FILE_KEY,
url = UPLOADER_CONFIG.UPLOAD_URL_PREFIX,
+}: {
+ file: File;
+ hashCode: string;
+ uploadFileKey?: string;
+ url?: string;
}): Promise<{
url: string;
}> {
diff --git a/src/uploader/uploader.ts b/src/uploader/uploader.ts
index 0403e27f..848a4eb5 100644
--- a/src/uploader/uploader.ts
+++ b/src/uploader/uploader.ts
@@ -4,7 +4,7 @@ import { IUploaderOptions } from './types';
import { UPLOADER_CONFIG } from './config';
export class UploadManager {
- static uploadManager;
+ static uploadManager: UploadManager;
static getInstance() {
if (!this.uploadManager) {
@@ -58,7 +58,7 @@ export class UploadManager {
});
}
- requestUpload(file) {
+ requestUpload(file: File): Promise<{url: string}> {
return new Promise((resolve, reject) => {
if (this.isRequesting) {
reject({ errMsg: '正在上传文件,请稍后再试' });
@@ -129,10 +129,10 @@ export class UploadManager {
* UploadManager.getInstance().updateHashCode();
* ```
*/
-export function uploadFile(file) {
+export function uploadFile(file: File) {
return new Promise((resolve, reject) => {
UploadManager.getInstance().requestUpload(file)
- .then((res) => {
+ .then((res: { url: string }) => {
if (!res.url) {
reject();
} else {
diff --git a/src/url/url-resolve.ts b/src/url/url-resolve.ts
index 86f4adae..69fe319d 100644
--- a/src/url/url-resolve.ts
+++ b/src/url/url-resolve.ts
@@ -28,7 +28,7 @@ export function resolveUrlParams(url = '', key = '') {
}
// 提取多个键值对
- const params = {};
+ const params: Record = {};
const kvList = matchList.map(item => item.replace(/(\?|&)/g, '')); // 移除 ? 或 & 前缀
kvList.forEach((kv) => {
const [key, value] = kv.split('=');
@@ -52,7 +52,7 @@ export function resolveUrlParams(url = '', key = '') {
* const url1 = formatUrlParams('http://www.test.com?a=1&b=2&c=3', { e: 5 }); // http://www.test.com/#/?e=5
* const url2 = formatUrlParams('http://www.test.com?a=1&b=2&c=3#/detail?d=4', { f: 5 }); // http://www.test.com/#/detail?f=5
*/
-export function formatUrlParams(url = '', keepParamsObj = {}, forceHistoryMode?) {
+export function formatUrlParams(url = '', keepParamsObj: Record = {}, forceHistoryMode = false) {
// 参数校验
const keepKeyArr = Object.keys(keepParamsObj);
if (!url || keepKeyArr.length === 0) {
@@ -109,13 +109,13 @@ export function formatUrlParams(url = '', keepParamsObj = {}, forceHistoryMode?)
* @example
* const url1 = extendUrlParams('http://www.test.com?a=1&b=2&c=3#/detail?d=4', { e: 5 }); // 'http://www.test.com/#/detail?a=1&b=2&c=3&d=4&e=5'
*/
-export function extendUrlParams(url, extParamsObj, forceHistoryMode?) {
+export function extendUrlParams(url: string, extParamsObj: Record, forceHistoryMode = false) {
// 获取链接上的所有参数
- const urlParamsObj = resolveUrlParams(url);
+ const urlParamsObj = resolveUrlParams(url) || {};
// 合并传入的参数
const keepParamsObj = {
- ...urlParamsObj,
+ ...(urlParamsObj as Record),
...extParamsObj,
};
@@ -134,12 +134,12 @@ export function extendUrlParams(url, extParamsObj, forceHistoryMode?) {
* const url = removeUrlParams('http://www.test.com/#/detail?a=1&b=2&c=3', ['a', 'b']); // 'http://www.test.com/#/detail?c=3'
* const url2 = removeUrlParams('http://www.test.com?d=4&f=6#/detail?a=1&b=2&c=3', ['a', 'd']); // 'http://www.test.com/#/detail?b=2&c=3&f=6'
*/
-export function removeUrlParams(url, removeKeyArr, forceHistoryMode?) {
+export function removeUrlParams(url: string, removeKeyArr: Array, forceHistoryMode = false) {
// 获取链接上的所有参数
- const urlParamsObj = resolveUrlParams(url);
+ const urlParamsObj = resolveUrlParams(url) as Record;
// 移除指定的key集合
- const keepParamsObj = {};
+ const keepParamsObj: Record = {};
Object.keys(urlParamsObj).forEach((key) => {
if (!removeKeyArr.includes(key)) {
keepParamsObj[key] = urlParamsObj[key];
@@ -161,12 +161,12 @@ export function removeUrlParams(url, removeKeyArr, forceHistoryMode?) {
* @example
* const url = keepUrlParams('http://www.test.com?a=1&b=2&c=3#/detail?d=4', ['a', 'd']); // 'http://www.test.com/#/detail?a=1&d=4'
*/
-export function keepUrlParams(url, keepKeyArr, forceHistoryMode?) {
+export function keepUrlParams(url: string, keepKeyArr: Array, forceHistoryMode = false) {
// 获取链接上的所有参数
- const urlParamsObj = resolveUrlParams(url);
+ const urlParamsObj = resolveUrlParams(url) as Record;
// 只保留指定的key集合
- const keepParamsObj = {};
+ const keepParamsObj: Record = {};
Object.keys(urlParamsObj).forEach((key: string) => {
if (keepKeyArr.includes(key)) {
keepParamsObj[key] = urlParamsObj[key];
diff --git a/src/url/url.ts b/src/url/url.ts
index 1dbbe89e..2a4ea48d 100644
--- a/src/url/url.ts
+++ b/src/url/url.ts
@@ -132,7 +132,7 @@ export function decodeUrlParam(str: string): object {
* // 18
* ```
*/
-export function getUrlPara(paraName, search = '') {
+export function getUrlPara(paraName: string, search = '') {
if (!search && typeof window !== 'undefined') {
search = window.location.search;
}
diff --git a/src/v-lazy/v-lazy.ts b/src/v-lazy/v-lazy.ts
index a728029a..76f9cca5 100644
--- a/src/v-lazy/v-lazy.ts
+++ b/src/v-lazy/v-lazy.ts
@@ -7,7 +7,7 @@ const stoppedImages: any = [];
if (typeof window !== 'undefined') {
window.addEventListener('load', () => {
windowLoaded = true;
- stoppedImages.forEach((img) => {
+ stoppedImages.forEach((img: any) => {
// 因为被置空会导致前一次加载失败,重新加载
if (img.el.getAttribute('lazy') !== 'loading' && img.src) {
img.el.src = img.src;
@@ -33,23 +33,23 @@ export function getVLazyOptions(options: {
attempt: 2,
filter: {
// 设置加载中图片
- loading(listener) {
+ loading(listener: any) {
if (loadingImg) {
listener.loading = loadingImg;
}
},
// 设置加载失败图片
- error(listener) {
+ error(listener: any) {
if (errorImg) {
listener.error = errorImg;
}
},
// 修改成https
- https(listener) {
+ https(listener: any) {
listener.src = getHttpsUrl(listener.src);
},
// 裁剪压缩
- compress(listener) {
+ compress(listener: any) {
// 10.31去除filter中图片压缩,保留loading中即可,否则会导致重复刷新时无法加载
// 11.13反馈微社区图片闪动,src和data-src不一致导致,上面的问题验证暂时没发现问题(重试次数修改为1了),放开解决闪动问题
listener.src = getCompressImgUrl(
@@ -59,11 +59,11 @@ export function getVLazyOptions(options: {
);
},
// 转换为cdn
- cdn(listener) {
+ cdn(listener: any) {
listener.src = getCdnUrl(listener.src);
},
// 拦截window.onload前的图片加载
- stopBeforeLoad(listener) {
+ stopBeforeLoad(listener: any) {
if (!windowLoaded) {
// 保存被拦截的图片
stoppedImages.push({ el: listener.el, src: listener.src });
@@ -73,7 +73,7 @@ export function getVLazyOptions(options: {
},
},
adapter: {
- error(listener) {
+ error(listener: any) {
// 被拦截的图片在onload之后失败,需要重试
if (windowLoaded && listener.stoppedSrc && listener.stoppedSrc.length > 0) {
listener.src = listener.stoppedSrc;
diff --git a/src/vue-start/helper/init-app/v2.ts b/src/vue-start/helper/init-app/v2.ts
index 432a57d4..c766e5dc 100644
--- a/src/vue-start/helper/init-app/v2.ts
+++ b/src/vue-start/helper/init-app/v2.ts
@@ -1,12 +1,12 @@
import type { AppOptionsType } from '../../types';
-export function initApp(options: AppOptionsType, router, store) {
+export function initApp(options: AppOptionsType, router: any, store: any) {
const app = new options.Vue({
el: '#app',
i18n: options.i18n,
router,
store,
- render: h => h(options.App),
+ render: (h: Function) => h(options.App),
mounted() {
if (options.prerender) {
document.dispatchEvent(new Event('render-event'));
diff --git a/src/vue-start/helper/init-app/v3.ts b/src/vue-start/helper/init-app/v3.ts
index 10107401..f67188ec 100644
--- a/src/vue-start/helper/init-app/v3.ts
+++ b/src/vue-start/helper/init-app/v3.ts
@@ -1,6 +1,6 @@
import type { AppOptionsType } from '../../types';
-export function initAppV3(options: AppOptionsType, router, store, createApp) {
+export function initAppV3(options: AppOptionsType, router: Object, store: Object, createApp: Function) {
const app = createApp(options.App);
app.use(router);
diff --git a/src/vue-start/helper/init-config/helper.ts b/src/vue-start/helper/init-config/helper.ts
index 336353a0..7bcbb39b 100644
--- a/src/vue-start/helper/init-config/helper.ts
+++ b/src/vue-start/helper/init-config/helper.ts
@@ -1,4 +1,4 @@
-export function initCommonConfig(app) {
+export function initCommonConfig(app: { config: { devtools: boolean } }) {
if (process.env.NODE_ENV == 'production') {
app.config.devtools = false;
} else {
diff --git a/src/vue-start/helper/init-config/v2.ts b/src/vue-start/helper/init-config/v2.ts
index e2367826..345ae97e 100644
--- a/src/vue-start/helper/init-config/v2.ts
+++ b/src/vue-start/helper/init-config/v2.ts
@@ -1,6 +1,6 @@
import { initCommonConfig } from './helper';
-export function initConfig(app) {
+export function initConfig(app: any) {
app.config.productionTip = false;
initCommonConfig(app);
diff --git a/src/vue-start/helper/init-config/v3.ts b/src/vue-start/helper/init-config/v3.ts
index 81dbedda..b4afa3b3 100644
--- a/src/vue-start/helper/init-config/v3.ts
+++ b/src/vue-start/helper/init-config/v3.ts
@@ -1,7 +1,7 @@
import { initCommonConfig } from './helper';
-export function initConfigV3(app) {
+export function initConfigV3(app: any) {
app.config.compilerOptions.isCustomElement = [
// 忽略自定义元素标签抛出的报错
'wx-open-launch-app',
diff --git a/src/vue-start/helper/init-mixin/index.ts b/src/vue-start/helper/init-mixin/index.ts
index 32c8b83d..5fce9c69 100644
--- a/src/vue-start/helper/init-mixin/index.ts
+++ b/src/vue-start/helper/init-mixin/index.ts
@@ -1,6 +1,6 @@
import type { AppOptionsType } from '../../types';
-export function initMixin(app, options: AppOptionsType) {
+export function initMixin(app: any, options: AppOptionsType) {
// 混入项目自己的mixin
if (options.projectMixins) {
app.mixin(options.projectMixins);
diff --git a/src/vue-start/helper/init-router/v2.ts b/src/vue-start/helper/init-router/v2.ts
index b7415a69..035ca5cc 100644
--- a/src/vue-start/helper/init-router/v2.ts
+++ b/src/vue-start/helper/init-router/v2.ts
@@ -18,7 +18,7 @@ export function initRouter(options: AppOptionsType) {
mode: routerMode,
fallback: false,
routes, // routes
- scrollBehavior(to, from, savedPosition) {
+ scrollBehavior(to: any, from: any, savedPosition: boolean) {
if (savedPosition) {
return savedPosition;
}
@@ -31,7 +31,7 @@ export function initRouter(options: AppOptionsType) {
base: process.env.VUE_APP_ROUTER_BASE || '/',
fallback: false,
routes,
- scrollBehavior(to, from, savedPosition) {
+ scrollBehavior(to: any, from: any, savedPosition: boolean) {
if (savedPosition) {
return savedPosition;
}
diff --git a/src/vue-start/helper/init-store/v2.ts b/src/vue-start/helper/init-store/v2.ts
index 9757ff37..5bd52c4f 100644
--- a/src/vue-start/helper/init-store/v2.ts
+++ b/src/vue-start/helper/init-store/v2.ts
@@ -1,4 +1,4 @@
-export function initStore(options) {
+export function initStore(options: any) {
if (!options.Vuex) return;
options.Vue.use(options.Vuex);
diff --git a/src/vue-start/helper/init-v-lazy/init-v-lazy.ts b/src/vue-start/helper/init-v-lazy/init-v-lazy.ts
index f2135084..f0f22d7d 100644
--- a/src/vue-start/helper/init-v-lazy/init-v-lazy.ts
+++ b/src/vue-start/helper/init-v-lazy/init-v-lazy.ts
@@ -1,7 +1,7 @@
import { getVLazyOptions } from '../../../v-lazy/v-lazy';
-export function initVLazy(options) {
+export function initVLazy(options: any) {
if (!options.VueLazyLoad) return;
options.Vue.use(options.VueLazyLoad, getVLazyOptions());
diff --git a/src/vue-start/vue-start.ts b/src/vue-start/vue-start.ts
index b0318756..f1ce0c92 100644
--- a/src/vue-start/vue-start.ts
+++ b/src/vue-start/vue-start.ts
@@ -8,8 +8,8 @@ import { initVLazy } from './helper/init-v-lazy/init-v-lazy';
import type { AppOptionsType } from './types';
-let router;
-let store;
+let router: any;
+let store: any;
/**
@@ -52,7 +52,7 @@ export function startApp(options: AppOptionsType) {
* 创建路由和Store
* @private
*/
-function createRouterAndStore(options) {
+function createRouterAndStore(options: any) {
if (router || store) {
return;
}
diff --git a/test/base/function.test.ts b/test/base/function.test.ts
index f390cc6e..ac631eef 100644
--- a/test/base/function.test.ts
+++ b/test/base/function.test.ts
@@ -24,7 +24,7 @@ describe('parseFunction', () => {
describe('cached', () => {
it('cached', () => {
- function test(a) {
+ function test(a: number) {
return a + 2;
}
expect(cached(test)(1)).toBe(3);
diff --git a/test/base/number.test.ts b/test/base/number.test.ts
index 20e913db..845dd554 100644
--- a/test/base/number.test.ts
+++ b/test/base/number.test.ts
@@ -2,6 +2,7 @@ import {
getUnitPreviousRatio,
getThousandSeparator,
getThousandSeparator2,
+ padZero,
} from '../../src';
describe('getUnitPreviousRatio', () => {
@@ -38,3 +39,15 @@ describe('getThousandSeparator2', () => {
expect(getThousandSeparator2('12345678 123456789')).toBe('12,345,678 123,456,789');
});
});
+
+describe('padZero', () => {
+ it('padZero', () => {
+ expect(padZero(1, 3)).toBe('001');
+ expect(padZero(1, 4)).toBe('0001');
+
+ expect(padZero(1, 1)).toBe('1');
+
+ expect(padZero(100, 1)).toBe('100');
+ expect(padZero(100, 2)).toBe('100');
+ });
+});
diff --git a/test/base/regexp.test.ts b/test/base/regexp.test.ts
new file mode 100644
index 00000000..7dd92646
--- /dev/null
+++ b/test/base/regexp.test.ts
@@ -0,0 +1,10 @@
+import { getPreReleaseTag } from '../../src';
+
+describe('getPreReleaseTag', () => {
+ it('getPreReleaseTag', () => {
+ expect(getPreReleaseTag('1.1.1')).toBe('');
+ expect(getPreReleaseTag('1.1.1-beta.0')).toBe('beta');
+ expect(getPreReleaseTag('1.1.1-alpha.0')).toBe('alpha');
+ expect(getPreReleaseTag('10.10.10-rc.0')).toBe('rc');
+ });
+});
diff --git a/test/date/date.test.js b/test/date/date.test.js
index 60ee54af..f7fc91eb 100644
--- a/test/date/date.test.js
+++ b/test/date/date.test.js
@@ -1,4 +1,4 @@
-import { getMonthDay, getMonthDay2, isSameWeek } from '../../src';
+import { getMonthDay, getMonthDay2, isSameWeek, isSameDay } from '../../src';
describe('getMonthDay', () => {
it('getMonthDay', () => {
@@ -26,3 +26,12 @@ describe('isSameWeek', () => {
expect(isSameWeek(1601308800000, 1601913600000)).toBe(false);
});
});
+
+
+describe('isSameDay', () => {
+ it('isSameDay', () => {
+ expect(isSameDay(1, 2)).toBe(true);
+ expect(isSameDay(1702613769418, 1702527420000)).toBe(false);
+ expect(isSameDay(1702613769418, 1702613769419)).toBe(true);
+ });
+});
diff --git a/test/loader/loader.test.ts b/test/loader/loader.test.ts
index 59fc50b0..c97535eb 100644
--- a/test/loader/loader.test.ts
+++ b/test/loader/loader.test.ts
@@ -4,7 +4,7 @@ describe('loadCSS', () => {
it('loadCSS', () => {
const mockFunc = jest.fn();
const oriFunc = document.createElement;
- document.createElement = function (...args) {
+ document.createElement = function (...args: Array) {
mockFunc();
// @ts-ignore
return oriFunc.apply(this, args);
diff --git a/test/morse-pwd/morse-pwd.spec.ts b/test/morse-pwd/morse-pwd.spec.ts
index 30a64e36..a95ecc36 100644
--- a/test/morse-pwd/morse-pwd.spec.ts
+++ b/test/morse-pwd/morse-pwd.spec.ts
@@ -2,21 +2,21 @@ import * as sinon from 'sinon';
import { MorsePwd } from '../../src';
-let mockDom;
+let mockDom: any;
beforeEach(() => {
document.querySelector = jest.fn();
mockDom = {
eventQueue: {},
- addEventListener(type, cb) {
+ addEventListener(type: string, cb: Function) {
this.eventQueue[type] = cb;
},
- dispatch(type) {
+ dispatch(type: string) {
if (typeof this.eventQueue[type] === 'function') {
this.eventQueue[type]();
}
},
- removeEventListener(type) {
+ removeEventListener(type: string) {
delete this.eventQueue[type];
},
};
@@ -53,7 +53,7 @@ describe('MorsePwd', () => {
// @ts-ignore
document.querySelector.mockReturnValue(mockDom);
const mockFn = jest.fn();
- const morsePwd = MorsePwd.init({
+ const morsePwd: any = MorsePwd.init({
pwd: [1, 1, 1],
cb: () => {
mockFn();
diff --git a/test/router/path-to-regexp.spec.ts b/test/router/path-to-regexp.spec.ts
index 6aaf13b7..bfd66486 100644
--- a/test/router/path-to-regexp.spec.ts
+++ b/test/router/path-to-regexp.spec.ts
@@ -7,7 +7,7 @@ describe('pathToRegexp', () => {
expect(pathToRegexp('/sche/:id')).toStrictEqual(/^\/sche\/([^\/]+?)(?:\/)?$/i);
// eslint-disable-next-line prefer-const
- let keys = [];
+ let keys: Array = [];
expect(pathToRegexp('/sche/:id', keys)).toStrictEqual(/^\/sche\/([^\/]+?)(?:\/)?$/i);
console.log('keys', keys);
@@ -27,7 +27,7 @@ describe('pathToRegexp', () => {
it('pathToRegexp.b', () => {
const pathHome = '/homepage/:uid?';
// eslint-disable-next-line prefer-const
- let keys = [];
+ let keys: Array = [];
expect(pathToRegexp(pathHome, keys)).toEqual(/^\/homepage(?:\/([^\/]+?))?(?:\/)?$/i);
expect(keys).toEqual([
@@ -46,7 +46,7 @@ describe('pathToRegexp', () => {
it('pathToRegexp.c', () => {
const path = '/match-data/:childid/:grouptype?';
// eslint-disable-next-line prefer-const
- let keys = [];
+ let keys: Array = [];
expect(pathToRegexp(path, keys)).toEqual(/^\/match-data\/([^\/]+?)(?:\/([^\/]+?))?(?:\/)?$/i);
expect(keys).toEqual([
diff --git a/test/url/remove-param.test.ts b/test/url/remove-param.test.ts
index 3289362f..049d2170 100644
--- a/test/url/remove-param.test.ts
+++ b/test/url/remove-param.test.ts
@@ -9,12 +9,12 @@ describe('comm:removeUrlParams', () => {
it('地址 history模式参数并存', () => {
const res = removeUrlParams('http://www.test.com/?a=1&b=2&c=3', ['a', 'b']);
- expect(res).toBe('http://www.test.com/?c=3');
+ expect(res).toBe('http://www.test.com/#/?c=3');
});
it('地址 history模式参数并存 + 强制history模式返回', () => {
const res = removeUrlParams('http://www.test.com/?a=1&b=2&c=3', ['a', 'b']);
- expect(res).toBe('http://www.test.com/?c=3');
+ expect(res).toBe('http://www.test.com/#/?c=3');
});
// it('hash 模式和history模式参数并存', () => {
diff --git a/test/url/url-resolve.test.ts b/test/url/url-resolve.test.ts
index 749364fd..8fb7a386 100644
--- a/test/url/url-resolve.test.ts
+++ b/test/url/url-resolve.test.ts
@@ -81,7 +81,7 @@ describe('formatUrlParams', () => {
it('地址 history模式参数并存', () => {
const res = formatUrlParams('http://www.test.com?a=1&b=2&c=3', { d: 4 });
- expect(res).toBe('http://www.test.com/?d=4');
+ expect(res).toBe('http://www.test.com/#/?d=4');
});
it('hash 模式和history模式参数并存', () => {
@@ -110,7 +110,7 @@ describe('extendUrlParams', () => {
it('地址 history模式参数并存', () => {
const res = extendUrlParams('http://www.test.com?a=1&b=2&c=3', { d: 4 });
- expect(res).toBe('http://www.test.com/?a=1&b=2&c=3&d=4');
+ expect(res).toBe('http://www.test.com/#/?a=1&b=2&c=3&d=4');
});
it('地址 history模式参数并存 + 强制history模式返回', () => {
@@ -139,7 +139,7 @@ describe('keepUrlParams', () => {
it('地址 history模式参数并存', () => {
const res = keepUrlParams('http://www.test.com?a=1&b=2&c=3', ['a', 'b']);
- expect(res).toBe('http://www.test.com/?a=1&b=2');
+ expect(res).toBe('http://www.test.com/#/?a=1&b=2');
});
it('地址 history模式参数并存 + 强制history模式返回', () => {
diff --git a/tsconfig.json b/tsconfig.json
index b7660f78..008ed160 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -8,15 +8,15 @@
"ESNext"
],
"removeComments": false,
- "declaration": true,
"sourceMap": false,
"allowJs": true,
/* 强类型检查配置 */
"strict": true,
- "noImplicitAny": false,
+ "noImplicitAny": true,
/* 模块分析配置 */
"baseUrl": ".",
"outDir": "lib",
+ "declaration": true,
"declarationDir": "lib",
"esModuleInterop": true,
"moduleResolution": "node",