karin-plugin-mys-core 1.0.0

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.
@@ -0,0 +1,347 @@
1
+ import {
2
+ dir
3
+ } from "./chunk-JML6VYXN.js";
4
+
5
+ // src/database/dbs/base.ts
6
+ import { json, logger } from "node-karin";
7
+ import lodash from "node-karin/lodash";
8
+ import fs from "fs";
9
+ import path from "path";
10
+ var DbBase = class {
11
+ schemaToJSON(pk) {
12
+ const result = {
13
+ [this.model.primaryKeyAttribute]: pk
14
+ };
15
+ lodash.forEach(this.modelSchema, (value, key) => {
16
+ if (key !== this.model.primaryKeyAttribute) {
17
+ result[key] = typeof value.defaultValue === "function" ? value.defaultValue() : value.defaultValue;
18
+ }
19
+ });
20
+ return result;
21
+ }
22
+ userPath(pk) {
23
+ if (this.databaseType === "dir" /* Dir */) {
24
+ return path.join(this.databasePath, pk);
25
+ }
26
+ return path.join(this.databasePath, `${pk}.json`);
27
+ }
28
+ readSync(path3, pk) {
29
+ const result = json.readSync(path3);
30
+ result._save = this.saveFile(pk);
31
+ return result;
32
+ }
33
+ readDirSync(pk) {
34
+ const path3 = this.userPath(pk);
35
+ const files = fs.readdirSync(path3);
36
+ const result = {
37
+ _save: this.saveDir(pk),
38
+ [this.model.primaryKeyAttribute]: pk
39
+ };
40
+ const filePromises = files.map(async (file) => {
41
+ const data = await json.read(`${path3}/${file}`);
42
+ result[data.key] = data.data;
43
+ });
44
+ Promise.all(filePromises).then().catch((err) => {
45
+ logger.error(err);
46
+ });
47
+ return result;
48
+ }
49
+ writeFileSync(pk, data) {
50
+ const defData = this.schemaToJSON(pk);
51
+ for (const key in data) {
52
+ !(key in defData) && delete data[key];
53
+ }
54
+ json.writeSync(this.userPath(pk), lodash.merge({}, defData, data));
55
+ return true;
56
+ }
57
+ writeDirSync(pk, data) {
58
+ const path3 = this.userPath(pk);
59
+ lodash.forEach(this.modelSchema, (value, key) => {
60
+ if (key !== this.model.primaryKeyAttribute) {
61
+ const result = {
62
+ key,
63
+ [this.model.primaryKeyAttribute]: pk,
64
+ data: data[key] || value.defaultValue
65
+ };
66
+ json.writeSync(`${path3}/${key}.json`, result);
67
+ }
68
+ });
69
+ return true;
70
+ }
71
+ saveFile(pk) {
72
+ return async (data) => {
73
+ delete data[this.model.primaryKeyAttribute];
74
+ this.writeFileSync(pk, data);
75
+ };
76
+ }
77
+ saveDir(pk) {
78
+ return async (data) => {
79
+ delete data[this.model.primaryKeyAttribute];
80
+ this.writeDirSync(pk, data);
81
+ };
82
+ }
83
+ saveSql(model, pk) {
84
+ return async (data) => {
85
+ delete data[this.model.primaryKeyAttribute];
86
+ const Attributes = this.schemaToJSON(pk);
87
+ for (const key in data) {
88
+ !(key in Attributes) && delete data[key];
89
+ }
90
+ await model.update(data);
91
+ };
92
+ }
93
+ };
94
+
95
+ // src/database/database.ts
96
+ import { logger as logger3 } from "node-karin";
97
+ import { DataTypes as DataTypes2 } from "sequelize";
98
+
99
+ // src/database/dbs/sqlite3.ts
100
+ import { json as json2, logger as logger2 } from "node-karin";
101
+ import fs2 from "fs";
102
+ import path2 from "path";
103
+ import { DataTypes, Sequelize } from "sequelize";
104
+ var dialect = "sqlite" /* Sqlite */;
105
+ var sequelize = new Sequelize({
106
+ storage: path2.join(dir.DataDir, "database", "sqlite3.db"),
107
+ dialect,
108
+ logging: false
109
+ });
110
+ var Sqlite3 = class extends DbBase {
111
+ dialect = dialect;
112
+ async check() {
113
+ try {
114
+ await sequelize.authenticate();
115
+ return true;
116
+ } catch (error) {
117
+ logger2.error(error);
118
+ return false;
119
+ }
120
+ }
121
+ async init(DataDir, modelName, modelSchema, type) {
122
+ this.databaseType = type;
123
+ this.databasePath = path2.join(DataDir, modelName);
124
+ if (type !== "db" /* Db */) {
125
+ fs2.mkdirSync(this.databasePath);
126
+ }
127
+ this.modelName = modelName;
128
+ this.modelSchema = modelSchema;
129
+ if (this.databaseType === "db" /* Db */) {
130
+ this.model = sequelize.define(this.modelName, this.modelSchema, {
131
+ timestamps: false
132
+ });
133
+ await this.model.sync();
134
+ const queryInterface = sequelize.getQueryInterface();
135
+ const tableDescription = await queryInterface.describeTable(this.modelName);
136
+ for (const key in this.modelSchema) {
137
+ if (!tableDescription[key]) {
138
+ await queryInterface.addColumn(this.modelName, key, this.modelSchema[key]);
139
+ if (typeof this.modelSchema[key] === "string") continue;
140
+ const defaultValue = this.modelSchema[key].defaultValue;
141
+ if (defaultValue !== void 0) {
142
+ await this.model.update({ [key]: defaultValue }, { where: {} });
143
+ }
144
+ }
145
+ }
146
+ }
147
+ return this;
148
+ }
149
+ async findByPk(pk, create = false) {
150
+ if (this.databaseType !== "db" /* Db */) {
151
+ const path3 = this.userPath(pk);
152
+ if (!fs2.existsSync(path3)) {
153
+ if (create) {
154
+ const data = this.schemaToJSON(pk);
155
+ if (this.databaseType === "dir" /* Dir */) {
156
+ fs2.mkdirSync(path3);
157
+ this.writeDirSync(pk, data);
158
+ } else {
159
+ json2.writeSync(path3, data);
160
+ }
161
+ return {
162
+ ...data,
163
+ _save: this.saveFile(pk)
164
+ };
165
+ }
166
+ return void 0;
167
+ }
168
+ if (this.databaseType === "dir" /* Dir */) {
169
+ return this.readDirSync(pk);
170
+ } else {
171
+ return this.readSync(path3, pk);
172
+ }
173
+ } else {
174
+ let result = await this.model.findByPk(pk);
175
+ if (!result && create) {
176
+ result = await this.model.create(this.schemaToJSON(pk));
177
+ }
178
+ if (!result) return void 0;
179
+ return {
180
+ ...result.toJSON(),
181
+ _save: this.saveSql(result, pk)
182
+ };
183
+ }
184
+ }
185
+ async findAllByPks(pks) {
186
+ if (this.databaseType !== "db" /* Db */) {
187
+ const result = [];
188
+ pks.forEach((pk) => {
189
+ const path3 = this.userPath(pk);
190
+ if (fs2.existsSync(path3)) {
191
+ if (this.databaseType === "dir" /* Dir */) {
192
+ result.push(this.readDirSync(pk));
193
+ } else {
194
+ result.push(this.readSync(path3, pk));
195
+ }
196
+ }
197
+ });
198
+ return result;
199
+ } else {
200
+ const result = await this.model.findAll({
201
+ where: {
202
+ [this.model.primaryKeyAttribute]: pks
203
+ }
204
+ });
205
+ return result.map((item) => ({
206
+ ...item.toJSON(),
207
+ _save: this.saveSql(item, item[this.model.primaryKeyAttribute])
208
+ }));
209
+ }
210
+ }
211
+ async destroy(pk) {
212
+ if (this.databaseType !== "db" /* Db */) {
213
+ const path3 = this.userPath(pk);
214
+ if (this.databaseType === "dir" /* Dir */) {
215
+ fs2.rmdirSync(path3, { recursive: true });
216
+ } else {
217
+ fs2.unlinkSync(path3);
218
+ }
219
+ return true;
220
+ } else {
221
+ const destroyed = await this.model.destroy({
222
+ where: { [this.model.primaryKeyAttribute]: pk }
223
+ });
224
+ return destroyed > 0;
225
+ }
226
+ }
227
+ };
228
+ var Sqlite3Static = new class Sqlite3Static2 {
229
+ Column(type, def, option) {
230
+ return {
231
+ type: DataTypes[type],
232
+ defaultValue: def,
233
+ ...option
234
+ };
235
+ }
236
+ ArrayColumn(key, fn) {
237
+ return {
238
+ type: DataTypes.STRING,
239
+ defaultValue: [].join(","),
240
+ get() {
241
+ return this.getDataValue(key).split(",").filter(Boolean);
242
+ },
243
+ set(data) {
244
+ const setData = (fn ? fn(data) : data) || [];
245
+ this.setDataValue(key, setData.join(","));
246
+ }
247
+ };
248
+ }
249
+ JsonColumn(key, def = {}) {
250
+ return {
251
+ type: DataTypes.STRING,
252
+ defaultValue: JSON.stringify(def),
253
+ get() {
254
+ let data = this.getDataValue(key);
255
+ try {
256
+ data = JSON.parse(data) || def;
257
+ } catch (e) {
258
+ data = def;
259
+ }
260
+ return data;
261
+ },
262
+ set(data) {
263
+ this.setDataValue(key, JSON.stringify(data));
264
+ }
265
+ };
266
+ }
267
+ }();
268
+
269
+ // src/database/database.ts
270
+ var DatabaseClass = class {
271
+ #defaultDatabase;
272
+ #defaultDatabaseStatic;
273
+ constructor() {
274
+ this.#defaultDatabase = () => new Sqlite3();
275
+ this.#defaultDatabaseStatic = Sqlite3Static;
276
+ }
277
+ /** 设置默认数据库 */
278
+ async default(Database2, Static) {
279
+ const db = Database2();
280
+ if (await db.check()) {
281
+ this.#defaultDatabase = Database2;
282
+ this.#defaultDatabaseStatic = Static;
283
+ } else {
284
+ logger3.error();
285
+ }
286
+ }
287
+ /** 获取当前使用的数据库 */
288
+ get() {
289
+ return this.#defaultDatabase();
290
+ }
291
+ get PkColumn() {
292
+ return (type, option) => ({
293
+ type: DataTypes2[type],
294
+ primaryKey: true,
295
+ allowNull: false,
296
+ ...option
297
+ });
298
+ }
299
+ get Column() {
300
+ return this.#defaultDatabaseStatic.Column;
301
+ }
302
+ get ArrayColumn() {
303
+ return this.#defaultDatabaseStatic.ArrayColumn;
304
+ }
305
+ get JsonColumn() {
306
+ return this.#defaultDatabaseStatic.JsonColumn;
307
+ }
308
+ };
309
+ var Database = new DatabaseClass();
310
+
311
+ // src/database/tables/mysAccountInfo.ts
312
+ var DB = Database.get();
313
+ var MysAccountInfoDB = await DB.init(
314
+ dir.DataDir,
315
+ "mysAccountInfoData",
316
+ {
317
+ ltuid: Database.PkColumn("STRING"),
318
+ type: Database.Column("STRING", "mihoyo" /* cn */),
319
+ cookie: Database.Column("TEXT", ""),
320
+ stoken: Database.Column("STRING", ""),
321
+ deviceMd5: Database.Column("STRING", "")
322
+ },
323
+ "db" /* Db */
324
+ );
325
+
326
+ // src/database/tables/mysUserInfo.ts
327
+ var DB2 = Database.get();
328
+ var BaseMysUserInfoSchema = {
329
+ userId: Database.PkColumn("STRING"),
330
+ ltuids: Database.ArrayColumn("ltuids"),
331
+ stuids: Database.ArrayColumn("stuids"),
332
+ deviceList: Database.ArrayColumn("deviceList")
333
+ };
334
+ var MysUserInfoDB = await DB2.init(
335
+ dir.DataDir,
336
+ "mysUserInfoData",
337
+ BaseMysUserInfoSchema,
338
+ "db" /* Db */
339
+ );
340
+
341
+ export {
342
+ DbBase,
343
+ Database,
344
+ MysAccountInfoDB,
345
+ BaseMysUserInfoSchema,
346
+ MysUserInfoDB
347
+ };
@@ -0,0 +1,31 @@
1
+ // src/types/database/dbs/base.ts
2
+ var Dialect = /* @__PURE__ */ ((Dialect2) => {
3
+ Dialect2["Sqlite"] = "sqlite";
4
+ Dialect2["MySQL"] = "mysql";
5
+ Dialect2["MariaDB"] = "mariadb";
6
+ Dialect2["PostgreSQL"] = "postgres";
7
+ Dialect2["MSSQL"] = "mssql";
8
+ Dialect2["Oracle"] = "oracle";
9
+ Dialect2["DB2"] = "db2";
10
+ Dialect2["Snowflake"] = "snowflake";
11
+ return Dialect2;
12
+ })(Dialect || {});
13
+ var DatabaseType = /* @__PURE__ */ ((DatabaseType2) => {
14
+ DatabaseType2["File"] = "file";
15
+ DatabaseType2["Dir"] = "dir";
16
+ DatabaseType2["Db"] = "db";
17
+ return DatabaseType2;
18
+ })(DatabaseType || {});
19
+
20
+ // src/types/database/tables/mysAccountInfo.ts
21
+ var MysAccountType = /* @__PURE__ */ ((MysAccountType2) => {
22
+ MysAccountType2["cn"] = "mihoyo";
23
+ MysAccountType2["os"] = "hoyolab";
24
+ return MysAccountType2;
25
+ })(MysAccountType || {});
26
+
27
+ export {
28
+ Dialect,
29
+ DatabaseType,
30
+ MysAccountType
31
+ };
@@ -0,0 +1,47 @@
1
+ // src/dir.ts
2
+ import { karinPathBase, requireFileSync } from "node-karin";
3
+ import path from "path";
4
+ import { URL, fileURLToPath } from "url";
5
+ var pluginDir = fileURLToPath(new URL("../", import.meta.url));
6
+ var pluginName = path.basename(pluginDir);
7
+ var pkg = requireFileSync(path.join(pluginDir, "package.json"));
8
+ var dir = {
9
+ /** 根目录绝对路径 */
10
+ pluginDir,
11
+ /** 插件目录名称 */
12
+ pluginName,
13
+ /** package.json */
14
+ pkg,
15
+ /** 插件版本 package.json 的 version */
16
+ get version() {
17
+ return pkg.version;
18
+ },
19
+ /** 插件名称 package.json 的 name */
20
+ get name() {
21
+ return pkg.name;
22
+ },
23
+ /** 插件默认配置目录 */
24
+ get defConfigDir() {
25
+ return path.join(pluginDir, "config");
26
+ },
27
+ /** 在`@karinjs`中的绝对路径 */
28
+ get karinPath() {
29
+ return path.join(karinPathBase, pluginName);
30
+ },
31
+ /** 插件配置目录 `@karinjs/karin-plugin-xxx/config` */
32
+ get ConfigDir() {
33
+ return path.join(this.karinPath, "config");
34
+ },
35
+ /** 插件数据目录 `@karinjs/karin-plugin-xxx/data` */
36
+ get DataDir() {
37
+ return path.join(this.karinPath, "data");
38
+ },
39
+ /** 插件资源目录 `@karinjs/karin-plugin-xxx/resources` */
40
+ get defResourcesDir() {
41
+ return path.join(this.karinPath, "resources");
42
+ }
43
+ };
44
+
45
+ export {
46
+ dir
47
+ };
@@ -0,0 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ export {
8
+ __export
9
+ };
@@ -0,0 +1,5 @@
1
+ import { c as DatabaseClassInstance } from './base-B1BvQ4ol.js';
2
+
3
+ type DatabaseFn = <T extends Record<string, any>>() => DatabaseClassInstance<T>;
4
+
5
+ export type { DatabaseFn as D };
@@ -0,0 +1,163 @@
1
+ import { AxiosHeaders } from 'node-karin/axios';
2
+ import { f as MysAccountType } from './base-B1BvQ4ol.js';
3
+
4
+ interface BaseltuidInfo {
5
+ ltuid: string;
6
+ type: MysAccountType;
7
+ }
8
+ interface UidInfo extends BaseltuidInfo {
9
+ uid?: string;
10
+ cookie?: string;
11
+ stoken?: string;
12
+ owner?: boolean;
13
+ }
14
+ interface DeviceInfo {
15
+ id: string;
16
+ name: string;
17
+ }
18
+ interface BaseMysRes {
19
+ retcode: number;
20
+ message: string;
21
+ error?: string[];
22
+ isCache?: boolean;
23
+ }
24
+ type MysApiInfoFn<R extends BaseMysRes & Record<string, any> | undefined = undefined, D extends Record<string, any> = {}> = (self: DefineMysApi<R, D>, data: D) => {
25
+ Method: 'GET' | 'POST';
26
+ Url: URL;
27
+ Body?: any;
28
+ HeaderFn: (options: {
29
+ query: string;
30
+ body: any;
31
+ }, data?: D) => Record<string, string> | Promise<Record<string, string>>;
32
+ };
33
+
34
+ interface UserGameRoleItem {
35
+ game_biz: string;
36
+ region: string;
37
+ game_uid: string;
38
+ nickname: string;
39
+ is_chosen: boolean;
40
+ }
41
+
42
+ interface RefreshUidData {
43
+ data: {
44
+ [key: string]: string[];
45
+ };
46
+ names: {
47
+ [key: string]: string;
48
+ };
49
+ }
50
+ interface StokenParms {
51
+ stuid: string;
52
+ stoken: string;
53
+ mid: string;
54
+ }
55
+
56
+ interface Config {
57
+ }
58
+
59
+ declare const MysApp: Readonly<{
60
+ version: {
61
+ cn: string;
62
+ os: string;
63
+ };
64
+ appId: 2;
65
+ salt: {
66
+ os: string;
67
+ '4X': string;
68
+ '6X': string;
69
+ K2: string;
70
+ LK2: string;
71
+ PROD: string;
72
+ };
73
+ }>;
74
+
75
+ declare class DefineMysApi<R extends BaseMysRes & Record<string, any> | undefined = undefined, D extends Record<string, any> = {}> {
76
+ #private;
77
+ uidInfo: UidInfo;
78
+ Device: DeviceInfo;
79
+ constructor(apiInfo: MysApiInfoFn<R, D>, uidInfo?: UidInfo, opt?: {
80
+ deviceFp?: boolean;
81
+ checkCode?: boolean;
82
+ });
83
+ get isHoyolab(): boolean;
84
+ getApi(data: D): Promise<{
85
+ Method: "POST" | "GET";
86
+ Url: URL;
87
+ Body: any;
88
+ Headers: AxiosHeaders;
89
+ }>;
90
+ getDevice(): Promise<DeviceInfo>;
91
+ request(data: D, checkCode?: boolean): Promise<R>;
92
+ checkRetCode(res: R, data?: D, validate?: boolean): Promise<R>;
93
+ getDS1(saltKey: keyof typeof MysApp.salt, query?: string, body?: string): string;
94
+ getDS2(saltKey: keyof typeof MysApp.salt, query?: string, body?: string): string;
95
+ NoHeaders: (options?: {
96
+ query?: string;
97
+ body?: any;
98
+ }) => {};
99
+ BaseCnHeaders: () => Promise<{
100
+ 'x-rpc-app_version': string;
101
+ 'x-rpc-client_type': string;
102
+ 'x-rpc-device_id': string;
103
+ 'User-Agent': string;
104
+ Referer: string;
105
+ }>;
106
+ BaseOsHeaders: () => {
107
+ 'x-rpc-app_version': string;
108
+ 'x-rpc-client_type': string;
109
+ 'x-rpc-language': string;
110
+ };
111
+ PassportHeaders: (options?: {
112
+ query?: string;
113
+ body?: any;
114
+ }) => {
115
+ 'x-rpc-app_version': string;
116
+ 'x-rpc-game_biz': string;
117
+ 'x-rpc-client_type': string;
118
+ 'User-Agent': string;
119
+ 'x-rpc-app_id': string;
120
+ DS: string;
121
+ };
122
+ CookieHeaders: (options?: {
123
+ query?: string;
124
+ body?: any;
125
+ }) => {
126
+ 'x-rpc-app_version': string;
127
+ 'x-rpc-client_type': string;
128
+ 'x-rpc-language': string;
129
+ Cookie: string;
130
+ } | {
131
+ then<TResult1 = {
132
+ 'x-rpc-app_version': string;
133
+ 'x-rpc-client_type': string;
134
+ 'x-rpc-device_id': string;
135
+ 'User-Agent': string;
136
+ Referer: string;
137
+ }, TResult2 = never>(onfulfilled?: ((value: {
138
+ 'x-rpc-app_version': string;
139
+ 'x-rpc-client_type': string;
140
+ 'x-rpc-device_id': string;
141
+ 'User-Agent': string;
142
+ Referer: string;
143
+ }) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): Promise<TResult1 | TResult2>;
144
+ catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined): Promise<{
145
+ 'x-rpc-app_version': string;
146
+ 'x-rpc-client_type': string;
147
+ 'x-rpc-device_id': string;
148
+ 'User-Agent': string;
149
+ Referer: string;
150
+ } | TResult>;
151
+ finally(onfinally?: (() => void) | null | undefined): Promise<{
152
+ 'x-rpc-app_version': string;
153
+ 'x-rpc-client_type': string;
154
+ 'x-rpc-device_id': string;
155
+ 'User-Agent': string;
156
+ Referer: string;
157
+ }>;
158
+ [Symbol.toStringTag]: string;
159
+ Cookie: string;
160
+ };
161
+ }
162
+
163
+ export { type BaseltuidInfo as B, type Config as C, type DeviceInfo as D, type MysApiInfoFn as M, type RefreshUidData as R, type StokenParms as S, type UidInfo as U, type BaseMysRes as a, type UserGameRoleItem as b, DefineMysApi as c, MysApp as d };
package/lib/dir.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * 插件目录信息
3
+ */
4
+ declare const dir: {
5
+ /** 根目录绝对路径 */
6
+ pluginDir: string;
7
+ /** 插件目录名称 */
8
+ pluginName: string;
9
+ /** package.json */
10
+ pkg: any;
11
+ /** 插件版本 package.json 的 version */
12
+ readonly version: any;
13
+ /** 插件名称 package.json 的 name */
14
+ readonly name: any;
15
+ /** 插件默认配置目录 */
16
+ readonly defConfigDir: string;
17
+ /** 在`@karinjs`中的绝对路径 */
18
+ readonly karinPath: string;
19
+ /** 插件配置目录 `@karinjs/karin-plugin-xxx/config` */
20
+ readonly ConfigDir: string;
21
+ /** 插件数据目录 `@karinjs/karin-plugin-xxx/data` */
22
+ readonly DataDir: string;
23
+ /** 插件资源目录 `@karinjs/karin-plugin-xxx/resources` */
24
+ readonly defResourcesDir: string;
25
+ };
26
+
27
+ export { dir };
package/lib/dir.js ADDED
@@ -0,0 +1,7 @@
1
+ import {
2
+ dir
3
+ } from "./chunk-JML6VYXN.js";
4
+ import "./chunk-MLKGABMK.js";
5
+ export {
6
+ dir
7
+ };