baja-lite 1.6.4 → 1.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/boot-remote.d.ts +2 -0
  2. package/{src/boot-remote.ts → boot-remote.js} +63 -64
  3. package/boot.d.ts +2 -0
  4. package/{src/boot.ts → boot.js} +163 -170
  5. package/code.d.ts +2 -0
  6. package/{src/code.ts → code.js} +405 -414
  7. package/convert-xml.d.ts +10 -0
  8. package/{src/convert-xml.ts → convert-xml.js} +410 -460
  9. package/error.d.ts +5 -0
  10. package/error.js +13 -0
  11. package/event.d.ts +10 -0
  12. package/event.js +38 -0
  13. package/fn.d.ts +128 -0
  14. package/fn.js +172 -0
  15. package/{src/index.ts → index.d.ts} +10 -11
  16. package/index.js +10 -0
  17. package/math.d.ts +83 -0
  18. package/math.js +451 -0
  19. package/object.d.ts +126 -0
  20. package/object.js +321 -0
  21. package/package.json +1 -1
  22. package/snowflake.d.ts +12 -0
  23. package/{src/snowflake.ts → snowflake.js} +108 -127
  24. package/sql.d.ts +2148 -0
  25. package/sql.js +5370 -0
  26. package/sqlite.d.ts +32 -0
  27. package/{src/sqlite.ts → sqlite.js} +156 -157
  28. package/string.d.ts +17 -0
  29. package/string.js +105 -0
  30. package/test-mysql.d.ts +2 -0
  31. package/test-mysql.js +114 -0
  32. package/test-postgresql.d.ts +2 -0
  33. package/{src/test-postgresql.ts → test-postgresql.js} +91 -80
  34. package/test-sqlite.d.ts +1 -0
  35. package/{src/test-sqlite.ts → test-sqlite.js} +90 -80
  36. package/test-xml.d.ts +1 -0
  37. package/{src/test-xml.ts → test-xml.js} +2 -2
  38. package/test.d.ts +1 -0
  39. package/{src/test.ts → test.js} +2 -3
  40. package/wx/base.d.ts +11 -0
  41. package/wx/base.js +78 -0
  42. package/wx/mini.d.ts +52 -0
  43. package/wx/mini.js +112 -0
  44. package/wx/organ.d.ts +65 -0
  45. package/wx/organ.js +171 -0
  46. package/{src/wx/types.ts → wx/types.d.ts} +560 -549
  47. package/wx/types.js +1 -0
  48. package/{src/wx.ts → wx.d.ts} +3 -3
  49. package/wx.js +3 -0
  50. package/.eslintignore +0 -7
  51. package/.eslintrc.cjs +0 -89
  52. package/.prettierrc +0 -7
  53. package/.vscode/settings.json +0 -9
  54. package/ci.js +0 -33
  55. package/package-cjs.json +0 -17
  56. package/pnpm-lock.yaml +0 -2840
  57. package/pnpm-workspace.yaml +0 -2
  58. package/src/error.ts +0 -11
  59. package/src/event.ts +0 -34
  60. package/src/fn.ts +0 -295
  61. package/src/math.ts +0 -405
  62. package/src/object.ts +0 -342
  63. package/src/sql.ts +0 -5529
  64. package/src/string.ts +0 -111
  65. package/src/test-mysql.ts +0 -148
  66. package/src/wx/base.ts +0 -77
  67. package/src/wx/mini.ts +0 -147
  68. package/src/wx/organ.ts +0 -290
  69. package/tsconfig.cjs.json +0 -42
  70. package/tsconfig.json +0 -44
  71. package/xml/event-report.xml +0 -13
  72. package/yarn.lock +0 -1977
  73. /package/{Readme.md → README.md} +0 -0
package/src/string.ts DELETED
@@ -1,111 +0,0 @@
1
- /**
2
- * 通过uri获取key
3
- * @param uri
4
- */
5
- export const getPicKey = (uri: string): string => {
6
- const arr = /key=([0-9a-zA-Z.]+)/.exec(uri);
7
- if (arr && arr.length === 2) {
8
- return arr[1]!;
9
- }
10
- return uri;
11
- };
12
-
13
- export const emptyString = (source: any, skipEmptyString = true): boolean => {
14
- return (
15
- source === null ||
16
- source === undefined ||
17
- (skipEmptyString === true && (source === '' || `${ source }`.replace(/\s/g, '') === ''))
18
- );
19
- };
20
-
21
- export const notEmptyString = (source: any, skipEmptyString = true): boolean => {
22
- return emptyString(source, skipEmptyString) === false;
23
- };
24
-
25
- export const safeString = (source?: string): string => {
26
- if (source) {
27
- return `${ source }`.replace(/'/g, '');
28
- }
29
- return '';
30
- };
31
- export const trimObject = <T>(data: any): T => {
32
- if (data) {
33
- for (const k in data) {
34
- if (typeof data[k] === 'string') {
35
- data[k] = data[k].trim();
36
- }
37
- }
38
- }
39
- return data;
40
- };
41
-
42
- export const randomNumber = (len: number): string => {
43
- return `${ parseInt(`${ (Math.random() * 9 + 1) * Math.pow(10, (len - 1)) }`, 10) }`;
44
- };
45
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
46
- const charLen = chars.length;
47
- export const randomString = (len: number): string => {
48
- return Array.from(new Array(len)).map(() => chars.charAt(Math.floor(Math.random() * charLen))).join('');
49
- };
50
- const chars2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
51
- const charLen2 = chars2.length;
52
- export const randomString2 = (len: number): string => {
53
- return Array.from(new Array(len)).map(() => chars2.charAt(Math.floor(Math.random() * charLen2))).join('');
54
- };
55
- const chars3 = 'abcdefghijklmnopqrstuvwxyz0123456789';
56
- const charLen3 = chars3.length;
57
- export const randomString3 = (len: number): string => {
58
- return Array.from(new Array(len)).map(() => chars3.charAt(Math.floor(Math.random() * charLen3))).join('');
59
- };
60
- export const buildWxStr = (data: {[key: string]: string}, maxLabelLength: number, ...titles: string[]) => {
61
- let str = titles.join('\r\n');
62
- str += '\r\n\r\n';
63
- const items = new Array<string>();
64
- // const maxLength = maxLabelLength * 2;
65
- for (const [key, value] of Object.entries(data)) {
66
- if (notEmptyString(value)) {
67
- const len = maxLabelLength - key.length;
68
- items.push(`${ key }:${ ''.padEnd(len * 3 + (len > 0 ? 1 : 0), ' ') }${ value }`);
69
- }
70
- }
71
- str += items.join('\r\n');
72
- return str;
73
- };
74
- const chinese = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/g;
75
- const table = {
76
- '!': '!',
77
- '¥': '$',
78
- '…': '.',
79
- '(': '(',
80
- ')': ')',
81
- '《': '<',
82
- '》': '>',
83
- '?': '?',
84
- ':': ':',
85
- '“': `'`,
86
- '”': `'`,
87
- '’': `'`,
88
- '‘': `'`,
89
- ',': ',',
90
- '。': '.',
91
- '、': '/',
92
- ';': ';',
93
- '〈': '<',
94
- '〉': '>',
95
- '【': '[',
96
- '】': ']',
97
- '『': '[',
98
- '』': ']',
99
- '「': '[',
100
- '」': ']',
101
- '﹃': '[',
102
- '﹄': ']',
103
- '〔': '(',
104
- '〕': ')',
105
- '—': '-',
106
- '~': '~',
107
- '﹏': '~'
108
- };
109
- export const replaceChineseCode = (str: string) => {
110
- return str.replace(chinese, (a: string) => table[a] || '');
111
- };
package/src/test-mysql.ts DELETED
@@ -1,148 +0,0 @@
1
- import { Field, SqlType } from 'baja-lite-field';
2
- import 'reflect-metadata';
3
- import { Boot } from './boot.js';
4
- import { ColumnMode, DB, SelectResult, SqlService } from './sql.js';
5
- class BaseAuditUser {
6
- /**
7
- *
8
- * @type { varchar }
9
- * @memberof BaseAuditUser
10
- */
11
- @Field({ type: SqlType.varchar, length: 32, id: true, notNull: true, uuidShort: true })
12
- auditId?: string;
13
- /**
14
- * 密码
15
- * @type { varchar }
16
- * @memberof BaseAuditUser
17
- */
18
- @Field({ type: SqlType.varchar, length: 32, comment: '密码' })
19
- password?: string;
20
- /**
21
- * 省
22
- * @type { varchar }
23
- * @memberof BaseAuditUser
24
- */
25
- @Field({ type: SqlType.varchar, length: 255, comment: '省' })
26
- userProvinceCode?: string;
27
- /**
28
- * 省
29
- * @type { varchar }
30
- * @memberof BaseAuditUser
31
- */
32
- @Field({ type: SqlType.varchar, length: 255, comment: '省' })
33
- userProvince?: string;
34
- /**
35
- * 显示名称
36
- * @type { varchar }
37
- * @memberof BaseAuditUser
38
- */
39
- @Field({ type: SqlType.varchar, length: 32, comment: '显示名称' })
40
- labelName?: string;
41
- /**
42
- * 备注名称
43
- * @type { varchar }
44
- * @memberof BaseAuditUser
45
- */
46
- @Field({ type: SqlType.varchar, length: 32, comment: '备注名称' })
47
- remarkName?: string;
48
- /**
49
- * 初始密码
50
- * @type { varchar }
51
- * @memberof BaseAuditUser
52
- */
53
- @Field({ type: SqlType.varchar, length: 32, comment: '初始密码' })
54
- upassword?: string;
55
- /**
56
- * 是否中心
57
- * @type { char }
58
- * @memberof BaseAuditUser
59
- */
60
- @Field({ type: SqlType.char, length: 1, def: 0, comment: '是否中心' })
61
- baseType?: string;
62
- /**
63
- *
64
- * @type { varchar }
65
- * @memberof BaseAuditUser
66
- */
67
- @Field({ type: SqlType.varchar, length: 32 })
68
- userId?: string;
69
- /**
70
- *
71
- * @type { varchar }
72
- * @memberof BaseAuditUser
73
- */
74
- @Field({ type: SqlType.varchar, length: 32 })
75
- companyId?: string;
76
- /**
77
- *
78
- * @type { varchar }
79
- * @memberof BaseAuditUser
80
- */
81
- @Field({ type: SqlType.varchar, length: 32 })
82
- username?: string;
83
- /**
84
- * 状态
85
- * @type { char }
86
- * @memberof BaseAuditUser
87
- */
88
- @Field({ type: SqlType.char, length: 1, def: 0, comment: '状态' })
89
- userStatus?: string;
90
- /**
91
- * 账户分组
92
- * @type { char }
93
- * @memberof BaseAuditUser
94
- */
95
- @Field({ type: SqlType.char, length: 1, def: 0, comment: '账户分组' })
96
- groupId?: string;
97
- /**
98
- *
99
- * @type { varchar }
100
- * @memberof BaseAuditUser
101
- */
102
- @Field({ type: SqlType.varchar, length: 10 })
103
- startDate?: string;
104
- /**
105
- *
106
- * @type { varchar }
107
- * @memberof BaseAuditUser
108
- */
109
- @Field({ type: SqlType.varchar, length: 10 })
110
- endDate?: string;
111
- }
112
- @DB({ tableName: 'base_audit_user', clz: BaseAuditUser })
113
- class BaseAuditUserService extends SqlService<BaseAuditUser> {
114
- }
115
- export async function go2() {
116
- await Boot({
117
- Mysql: {
118
- host: '127.0.0.1',
119
- port: 3306,
120
- user: 'root',
121
- password: 'abcd1234',
122
- // 数据库名
123
- database: 'sportevent',
124
- debug: false
125
- },
126
- log: 'trace',
127
- columnMode: ColumnMode.HUMP,
128
- sqlDir: 'E:/pro/my-sdk/baja-lite/xml',
129
- sqlMap: {
130
- ['test.test']: `
131
- SELECT * FROM base_user {{#realname}} WHERE realname LIKE CONCAT(:realname, '%') {{/realname}};
132
- SELECT * FROM base_user {{#realname}} WHERE realname LIKE CONCAT(:realname, '%') {{/realname}};
133
- `
134
- }
135
- });
136
- const service = new BaseAuditUserService();
137
- const rt = await service.stream().eq('auditId', '100987125344341382').select('labelName').where('audit_id > 0').excuteSelect({selectResult:SelectResult.R_C_Assert});
138
- console.log(rt);
139
- // const list = await service.transaction<number>({
140
- // fn: async conn => {
141
- // await service.stream().eq('baseType', '0').in('auditId', ['162400829591265280', '162201628882247680']).excuteSelect();
142
- // const data = await service.stream().in('auditId', ['162400829591265280', '162201628882247680']).update('labelName', '333').excuteUpdate({ conn });
143
- // return data;
144
- // }
145
- // });
146
- // console.log(11, list);
147
- }
148
- go2();
package/src/wx/base.ts DELETED
@@ -1,77 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-unsafe-argument */
2
- import pino from 'pino';
3
- import * as rp from 'request-promise';
4
- import { Throw } from '../error.js';
5
- const logger =
6
- process.env['NODE_ENV'] !== 'production' ? pino({
7
- name: 'wx',
8
- transport: {
9
- target: 'pino-pretty'
10
- }
11
- }) : pino({ name: 'wx' });
12
- export abstract class BaseWx {
13
- protected authErrorCodes = [40001, 40014, 41001, 42001];
14
- protected name: string = '';
15
- protected tokenUrl: string = '';
16
- private tokenData = '';
17
- protected mock = false;
18
- protected async getToken(force?: boolean): Promise<string> {
19
- let token = '';
20
- const now = +new Date();
21
- let need = force === true;
22
- if (this.tokenData) {
23
- const datas = this.tokenData.split('^_^');
24
- token = datas[0]!;
25
- const lastTime = datas[1]!;
26
- const spliceTime = datas[2]!;
27
- if (now - parseInt(lastTime, 10) - parseInt(spliceTime, 10) > 0) {
28
- need = true;
29
- }
30
- } else {
31
- need = true;
32
- }
33
- if (need === true) {
34
- const data = await this.fetch(() => this.tokenUrl, 'get', {}, false);
35
- token = data.access_token;
36
- this.tokenData = `${token}^_^${now}^_^${data.expires_in * 1000}`;
37
- }
38
- return token;
39
- }
40
- protected async fetch(uri: (token: string) => string, method: 'get' | 'post', data: { [key: string]: any }, needToken = true, buffer = false) {
41
- if (this.mock === true) {
42
- return {};
43
- }
44
- let token = needToken ? await this.getToken() : '';
45
- if (!needToken || token) {
46
- const start = +new Date();
47
- let url = uri(token);
48
- const param = method === 'get' ? {
49
- method,
50
- json: buffer ? false : true,
51
- qs: data,
52
- encoding: buffer ? null : undefined
53
- } : {
54
- json: data,
55
- method,
56
- encoding: buffer ? null : undefined
57
- };
58
-
59
- let response = await rp.default({
60
- uri: url,
61
- ...param
62
- });
63
- if (this.authErrorCodes.includes(response.errcode)) {
64
- token = await this.getToken(true);
65
- url = uri(token);
66
- response = await rp.default({
67
- uri: url,
68
- ...param
69
- });
70
- Throw.if(response.errcode && response.errcode - 0 !== 0, `${url}-${response.errcode}-${response.errmsg}`);
71
- }
72
- Throw.if(response.errcode && response.errcode - 0 !== 0, `${url}-${response.errcode}-${response.errmsg}`);
73
- logger.info(`fetch data ${+new Date() - start} ms`);
74
- return response;
75
- }
76
- }
77
- }
package/src/wx/mini.ts DELETED
@@ -1,147 +0,0 @@
1
- import crypto from 'crypto';
2
- import { Throw } from '../error.js';
3
- import { BaseWx } from './base.js';
4
- import { WxLiveInfo, WxLiveReplay, WxMiniConfig } from './types.js';
5
- export class WxMini extends BaseWx {
6
- protected name = 'wxMini';
7
- private config: WxMiniConfig;
8
- private templNameCache: { [name: string]: { page: string; tmplId: string }[] }; // 订阅消息缓存
9
- private templKeyCache: { [key: string]: string[] }; // 订阅消息场景分组id
10
- constructor(config: WxMiniConfig) {
11
- super();
12
- this.config = config;
13
- this.tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.config.appId}&secret=${this.config.appSecret}`;
14
- this.templNameCache = {};
15
- this.templKeyCache = {};
16
- if (this.config.messages) {
17
- for (const item of this.config.messages) {
18
- if (!this.templNameCache[item.name]) {
19
- this.templNameCache[item.name] = [];
20
- }
21
- this.templNameCache[item.name]!.push({
22
- tmplId: item.tmplId,
23
- page: `pages/${item.model}/${item.page}/${item.page}`
24
- });
25
- for (const key of item.keys) {
26
- if (!this.templKeyCache[key]) {
27
- this.templKeyCache[key] = [];
28
- }
29
- this.templKeyCache[key]!.push(item.tmplId);
30
- }
31
- }
32
- }
33
- }
34
- async getUnlimited({ scene, model, page, fullpath, png, width, lineColor }: { scene: string; model?: string; page?: string; fullpath?: string; png?: '0' | '1' | 0 | 1 | true | false | 'true' | 'false'; width?: number; lineColor?: { r: number; g: number; b: number } }) {
35
- Throw.if(!fullpath && (!model || !page), '路径不完整,fullpath或者model+page必须传一个');
36
- const pageto = fullpath ?? `pages/${model}/${page}/${page}`;
37
- return await this.fetch(
38
- (token: string) => `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${token}`,
39
- 'post',
40
- {
41
- scene,
42
- page: pageto,
43
- line_color: lineColor ?? this.config.qrcode?.lineColor,
44
- is_hyaline: png === 'true' || png === '1' || png === true || png === 1,
45
- width: width ?? this.config.qrcode?.width ?? 500
46
- },
47
- true,
48
- true
49
- );
50
- }
51
- async sendMs(
52
- { openids, name, data, scene }: {
53
- openids: string[];
54
- name: string;
55
- data: { [key: string]: string | number };
56
- scene: string;
57
- }) {
58
- const temps = this.templNameCache[name]!;
59
- const dataSend: { [key: string]: { value: string | number } } = {};
60
- for (const [key, value] of Object.entries(data)) {
61
- dataSend[key] = { value: value ?? '' };
62
- }
63
- if (scene) {
64
- scene = `?${scene}`;
65
- } else {
66
- scene = '';
67
- }
68
- for (const temp of temps) {
69
- for (const touser of openids) {
70
- await this.fetch(
71
- (token: string) => `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${token}`,
72
- 'post',
73
- {
74
- touser,
75
- data: dataSend,
76
- template_id: temp.tmplId,
77
- page: `${temp.page}${scene}`
78
- }
79
- );
80
- }
81
- }
82
- }
83
- async code2session(code: string): Promise<{ openid: string; session_key: string; unionid?: string }> {
84
- const data = await this.fetch(
85
- () => `https://api.weixin.qq.com/sns/jscode2session?appid=${this.config.appId}&secret=${this.config.appSecret}&js_code=${code}&grant_type=authorization_code`,
86
- 'get',
87
- {},
88
- false
89
- );
90
- return {
91
- openid: data.openid,
92
- session_key: data.session_key,
93
- unionid: data.unionid
94
- };
95
- }
96
- getTemplIds() {
97
- return this.templKeyCache;
98
- }
99
- decrypt<T>({ sessionKey, encryptedData, iv }: { iv: string; sessionKey: string; encryptedData: string }): T | undefined {
100
- Throw.if(!sessionKey, '会话过期,请重新登陆!');
101
- const sessionKeyBuf = Buffer.from(sessionKey, 'base64');
102
- const encryptedDataBuf = Buffer.from(encryptedData, 'base64');
103
- const ivBuf = Buffer.from(iv, 'base64');
104
- try {
105
- // 解密
106
- const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKeyBuf, ivBuf);
107
- // 设置自动 padding 为 true,删除填充补位
108
- decipher.setAutoPadding(true);
109
- const decoded = decipher.update(encryptedDataBuf, undefined, 'utf8') + decipher.final('utf8');
110
- const decodedData = JSON.parse(decoded);
111
- Throw.if(decodedData.watermark.appid !== this.config.appId, '加密验证失败');
112
- return decodedData as T;
113
- } catch (err) {
114
- throw new Error('加密验证失败');
115
- }
116
- }
117
- async getLiveInfo(start: number, limit: number): Promise<WxLiveInfo[]> {
118
- const data = await this.fetch(
119
- (token: string) => `https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=${token}`,
120
- 'post',
121
- { start, limit }
122
- );
123
- return data.room_info;
124
- }
125
- async getLiveReplay(room_id: number, start: number, limit: number): Promise<WxLiveReplay[]> {
126
- const data = await this.fetch(
127
- (token: string) => `https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=${token}`,
128
- 'post',
129
- { room_id, start, limit, action: 'get_replay' }
130
- );
131
- return data.live_replay;
132
- }
133
- async getPhone(code: string, openid: string) {
134
- const data = await this.fetch(
135
- (token: string) => `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${token}`,
136
- 'post',
137
- { code, openid }
138
- );
139
- return {
140
- phoneNumber: data.phone_info.phoneNumber,
141
- purePhoneNumber: data.phone_info.purePhoneNumber,
142
- countryCode: data.phone_info.countryCode,
143
- timestamp: data.phone_info.watermark.timestamp,
144
- appid: data.phone_info.watermark.appid
145
- };
146
- }
147
- }