@seayoo-io/combo-sdk-node 1.7.0 → 1.9.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.
package/dist/index.cjs CHANGED
@@ -1,1812 +1,1700 @@
1
- var os = require('os');
2
- var http = require('http');
3
- var https = require('https');
4
- var crypto = require('crypto');
5
- var jsonwebtoken = require('jsonwebtoken');
6
-
7
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
-
9
- var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
10
- var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
11
-
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let os = require("os");
25
+ let http = require("http");
26
+ http = __toESM(http);
27
+ let https = require("https");
28
+ https = __toESM(https);
29
+ let crypto = require("crypto");
30
+ let jsonwebtoken = require("jsonwebtoken");
31
+ jsonwebtoken = __toESM(jsonwebtoken);
32
+ //#region src/const.ts
12
33
  /** SDK 名称 */
13
34
  const SDKName = "combo-sdk-node";
14
35
  /** SDK 版本,在编译前会被动态替换 */
15
- const SDKVersion = "1.7.0";
36
+ const SDKVersion = "1.9.0";
16
37
  /**
17
- * 世游支持的服务端点列表
18
- */
19
- exports.Endpoint = void 0;
20
- (function (Endpoint) {
21
- /** 中国大陆 API 端点,用于国内发行 */
22
- Endpoint["China"] = "https://api.seayoo.com";
23
- /** 全球的 API 端点,用于海外发行 */
24
- Endpoint["Global"] = "https://api.seayoo.io";
25
- })(exports.Endpoint || (exports.Endpoint = {}));
38
+ * 世游支持的服务端点列表
39
+ */
40
+ let Endpoint = /* @__PURE__ */ function(Endpoint) {
41
+ /** 中国大陆 API 端点,用于国内发行 */
42
+ Endpoint["China"] = "https://api.seayoo.com";
43
+ /** 全球的 API 端点,用于海外发行 */
44
+ Endpoint["Global"] = "https://api.seayoo.io";
45
+ return Endpoint;
46
+ }({});
26
47
  /** 支持的系统平台 */
27
- exports.Platform = void 0;
28
- (function (Platform) {
29
- /** 安卓平台,包括华为鸿蒙系统、小米澎湃 OS 等基于 Android 的操作系统 */
30
- Platform["Android"] = "android";
31
- /** 苹果的 iOS 和 iPadOS */
32
- Platform["iOS"] = "ios";
33
- /** Windows (PC) 桌面平台 */
34
- Platform["Windows"] = "windows";
35
- /** macOS 桌面平台 */
36
- Platform["macOS"] = "macos";
37
- /** WebGL 平台,包括微信、抖音等小游戏,以及 HTML5 网页游戏 */
38
- Platform["WebGL"] = "webgl";
39
- /** 华为的 HarmonyOS NEXT 鸿蒙应用开发平台 */
40
- Platform["HarmonyOS"] = "harmonyos";
41
- })(exports.Platform || (exports.Platform = {}));
48
+ let Platform = /* @__PURE__ */ function(Platform) {
49
+ /** 安卓平台,包括华为鸿蒙系统、小米澎湃 OS 等基于 Android 的操作系统 */
50
+ Platform["Android"] = "android";
51
+ /** 苹果的 iOS 和 iPadOS */
52
+ Platform["iOS"] = "ios";
53
+ /** Windows (PC) 桌面平台 */
54
+ Platform["Windows"] = "windows";
55
+ /** macOS 桌面平台 */
56
+ Platform["macOS"] = "macos";
57
+ /** WebGL 平台,包括微信、抖音等小游戏,以及 HTML5 网页游戏 */
58
+ Platform["WebGL"] = "webgl";
59
+ /** 华为的 HarmonyOS NEXT 鸿蒙应用开发平台 */
60
+ Platform["HarmonyOS"] = "harmonyos";
61
+ return Platform;
62
+ }({});
42
63
  /** 支持的登录提供方 */
43
- exports.IdP = void 0;
44
- (function (IdP) {
45
- /** 游客登录 */
46
- IdP["Guest"] = "guest";
47
- /** 世游通行证 */
48
- IdP["Seayoo"] = "seayoo";
49
- /** Sign-in with Apple */
50
- IdP["Apple"] = "apple";
51
- /** Google Account */
52
- IdP["Google"] = "google";
53
- /** Facebook Login */
54
- IdP["Facebook"] = "facebook";
55
- /** 小米账号 */
56
- IdP["Xiaomi"] = "xiaomi";
57
- /** 微信登录 */
58
- IdP["Weixin"] = "weixin";
59
- /** OPPO 账号 */
60
- IdP["Oppo"] = "oppo";
61
- /** VIVO 账号 */
62
- IdP["Vivo"] = "vivo";
63
- /** 华为账号 */
64
- IdP["Huawei"] = "huawei";
65
- /** 荣耀账号 */
66
- IdP["Honor"] = "honor";
67
- /** UC(九游)登录 */
68
- IdP["UC"] = "uc";
69
- /** TapTap 登录 */
70
- IdP["TapTap"] = "taptap";
71
- /** 哔哩哔哩(B站)账号 */
72
- IdP["Bilibili"] = "bilibili";
73
- /** 应用宝 YSDK 登录 */
74
- IdP["Yingyongbao"] = "yingyongbao";
75
- /** 4399 账号登录 */
76
- IdP["F4399"] = "4399";
77
- /** 抖音账号 */
78
- IdP["Douyin"] = "douyin";
79
- /** 雷电模拟器账号 */
80
- IdP["Leidian"] = "leidian";
81
- /** 猫窝游戏 */
82
- IdP["Maowo"] = "maowo";
83
- /** 联想 */
84
- IdP["Lenovo"] = "lenovo";
85
- /** 魅族 */
86
- IdP["Meizu"] = "meizu";
87
- /** 酷派 */
88
- IdP["Coolpad"] = "coolpad";
89
- /** 努比亚 */
90
- IdP["Nubia"] = "nubia";
91
- /** 绝峰游戏 */
92
- IdP["Juefeng"] = "juefeng";
93
- /** 魅拓游戏 */
94
- IdP["Meituo"] = "meituo";
95
- /** 微信小游戏 */
96
- IdP["MinigameWeixin"] = "minigame_weixin";
97
- /** 抖音小游戏 */
98
- IdP["MinigameDouyin"] = "minigame_douyin";
99
- /** MuMu 模拟器 */
100
- IdP["Mumu"] = "mumu";
101
- /** 虎牙游戏 */
102
- IdP["Huya"] = "huya";
103
- /** 好游快爆 */
104
- IdP["Hykb"] = "hykb";
105
- /** 233 乐园 */
106
- IdP["L233"] = "233";
107
- })(exports.IdP || (exports.IdP = {}));
64
+ let IdP = /* @__PURE__ */ function(IdP) {
65
+ /** 游客登录 */
66
+ IdP["Guest"] = "guest";
67
+ /** 世游通行证 */
68
+ IdP["Seayoo"] = "seayoo";
69
+ /** Sign-in with Apple */
70
+ IdP["Apple"] = "apple";
71
+ /** Google Account */
72
+ IdP["Google"] = "google";
73
+ /** Facebook Login */
74
+ IdP["Facebook"] = "facebook";
75
+ /** 小米账号 */
76
+ IdP["Xiaomi"] = "xiaomi";
77
+ /** 微信登录 */
78
+ IdP["Weixin"] = "weixin";
79
+ /** OPPO 账号 */
80
+ IdP["Oppo"] = "oppo";
81
+ /** VIVO 账号 */
82
+ IdP["Vivo"] = "vivo";
83
+ /** 华为账号 */
84
+ IdP["Huawei"] = "huawei";
85
+ /** 荣耀账号 */
86
+ IdP["Honor"] = "honor";
87
+ /** UC(九游)登录 */
88
+ IdP["UC"] = "uc";
89
+ /** TapTap 登录 */
90
+ IdP["TapTap"] = "taptap";
91
+ /** 哔哩哔哩(B站)账号 */
92
+ IdP["Bilibili"] = "bilibili";
93
+ /** 应用宝 YSDK 登录 */
94
+ IdP["Yingyongbao"] = "yingyongbao";
95
+ /** 4399 账号登录 */
96
+ IdP["F4399"] = "4399";
97
+ /** 抖音账号 */
98
+ IdP["Douyin"] = "douyin";
99
+ /** 雷电模拟器账号 */
100
+ IdP["Leidian"] = "leidian";
101
+ /** 猫窝游戏 */
102
+ IdP["Maowo"] = "maowo";
103
+ /** 联想 */
104
+ IdP["Lenovo"] = "lenovo";
105
+ /** 魅族 */
106
+ IdP["Meizu"] = "meizu";
107
+ /** 酷派 */
108
+ IdP["Coolpad"] = "coolpad";
109
+ /** 努比亚 */
110
+ IdP["Nubia"] = "nubia";
111
+ /** 绝峰游戏 */
112
+ IdP["Juefeng"] = "juefeng";
113
+ /** 魅拓游戏 */
114
+ IdP["Meituo"] = "meituo";
115
+ /** 微信小游戏 */
116
+ IdP["MinigameWeixin"] = "minigame_weixin";
117
+ /** 抖音小游戏 */
118
+ IdP["MinigameDouyin"] = "minigame_douyin";
119
+ /** MuMu 模拟器 */
120
+ IdP["Mumu"] = "mumu";
121
+ /** 虎牙游戏 */
122
+ IdP["Huya"] = "huya";
123
+ /** 好游快爆 */
124
+ IdP["Hykb"] = "hykb";
125
+ /** 233 乐园 */
126
+ IdP["L233"] = "233";
127
+ return IdP;
128
+ }({});
108
129
  /** GM 错误类型枚举 */
109
- exports.GMError = void 0;
110
- (function (GMError) {
111
- /** 请求中的 HTTP method 不正确,没有按照预期使用 POST。*/
112
- GMError["InvalidHttpMethod"] = "invalid_http_method";
113
- /** 请求中的 Content-Type 不是 application/json。*/
114
- GMError["InvalidContentType"] = "invalid_content_type";
115
- /** 对 HTTP 请求的签名验证不通过。这意味着 HTTP 请求不可信。 */
116
- GMError["InvalidSignature"] = "invalid_signature";
117
- /** 请求的结构不正确。例如,缺少必要的字段,或字段类型不正确。 */
118
- GMError["InvalidRequest"] = "invalid_request";
119
- /** 游戏侧不认识请求中的 GM 命令。 */
120
- GMError["InvalidCommand"] = "invalid_command";
121
- /** GM 命令发送频率过高,被游戏侧限流,命令未被处理。 */
122
- GMError["ThrottlingError"] = "throttling_error";
123
- /** 幂等处理重试请求时,idempotency_key 所对应的原始请求尚未处理完毕。*/
124
- GMError["IdempotencyConflict"] = "idempotency_conflict";
125
- /** 幂等处理重试请求时,请求内容和 idempotency_key 所对应的原始请求内容不一致。*/
126
- GMError["IdempotencyMismatch"] = "idempotency_mismatch";
127
- /** GM 命令的参数不正确。例如,参数缺少必要的字段,或参数的字段类型不正确。 */
128
- GMError["InvalidArgs"] = "invalid_args";
129
- /** 游戏当前处于停服维护状态,无法处理收到的 GM 命令。*/
130
- GMError["MaintenanceError"] = "maintenance_error";
131
- /** 网络通信错误。 */
132
- GMError["NetworkError"] = "network_error";
133
- /** 数据库操作异常导致 GM 命令执行失败。 */
134
- GMError["DatabaseError"] = "database_error";
135
- /** GM 命令处理超时。 */
136
- GMError["TimeoutError"] = "timeout_error";
137
- /** 处理 GM 命令时内部出错。可作为兜底的通用错误类型。*/
138
- GMError["InternalError"] = "internal_error";
139
- })(exports.GMError || (exports.GMError = {}));
140
-
130
+ let GMError = /* @__PURE__ */ function(GMError) {
131
+ /** 请求中的 HTTP method 不正确,没有按照预期使用 POST。*/
132
+ GMError["InvalidHttpMethod"] = "invalid_http_method";
133
+ /** 请求中的 Content-Type 不是 application/json。*/
134
+ GMError["InvalidContentType"] = "invalid_content_type";
135
+ /** 对 HTTP 请求的签名验证不通过。这意味着 HTTP 请求不可信。 */
136
+ GMError["InvalidSignature"] = "invalid_signature";
137
+ /** 请求的结构不正确。例如,缺少必要的字段,或字段类型不正确。 */
138
+ GMError["InvalidRequest"] = "invalid_request";
139
+ /** 游戏侧不认识请求中的 GM 命令。 */
140
+ GMError["InvalidCommand"] = "invalid_command";
141
+ /** GM 命令发送频率过高,被游戏侧限流,命令未被处理。 */
142
+ GMError["ThrottlingError"] = "throttling_error";
143
+ /** 幂等处理重试请求时,idempotency_key 所对应的原始请求尚未处理完毕。*/
144
+ GMError["IdempotencyConflict"] = "idempotency_conflict";
145
+ /** 幂等处理重试请求时,请求内容和 idempotency_key 所对应的原始请求内容不一致。*/
146
+ GMError["IdempotencyMismatch"] = "idempotency_mismatch";
147
+ /** GM 命令的参数不正确。例如,参数缺少必要的字段,或参数的字段类型不正确。 */
148
+ GMError["InvalidArgs"] = "invalid_args";
149
+ /** 游戏当前处于停服维护状态,无法处理收到的 GM 命令。*/
150
+ GMError["MaintenanceError"] = "maintenance_error";
151
+ /** 网络通信错误。 */
152
+ GMError["NetworkError"] = "network_error";
153
+ /** 数据库操作异常导致 GM 命令执行失败。 */
154
+ GMError["DatabaseError"] = "database_error";
155
+ /** GM 命令处理超时。 */
156
+ GMError["TimeoutError"] = "timeout_error";
157
+ /** 处理 GM 命令时内部出错。可作为兜底的通用错误类型。*/
158
+ GMError["InternalError"] = "internal_error";
159
+ return GMError;
160
+ }({});
161
+ let HttpStatus = /* @__PURE__ */ function(HttpStatus) {
162
+ HttpStatus[HttpStatus["OK"] = 200] = "OK";
163
+ HttpStatus[HttpStatus["Accepted"] = 202] = "Accepted";
164
+ HttpStatus[HttpStatus["NoContent"] = 204] = "NoContent";
165
+ HttpStatus[HttpStatus["BadRequest"] = 400] = "BadRequest";
166
+ HttpStatus[HttpStatus["Unauthorized"] = 401] = "Unauthorized";
167
+ HttpStatus[HttpStatus["Forbidden"] = 403] = "Forbidden";
168
+ HttpStatus[HttpStatus["NotFound"] = 404] = "NotFound";
169
+ HttpStatus[HttpStatus["MethodNotAllowed"] = 405] = "MethodNotAllowed";
170
+ HttpStatus[HttpStatus["NotAcceptable"] = 406] = "NotAcceptable";
171
+ HttpStatus[HttpStatus["RequestTimeout"] = 408] = "RequestTimeout";
172
+ HttpStatus[HttpStatus["Conflict"] = 409] = "Conflict";
173
+ HttpStatus[HttpStatus["UnsupportedMediaType"] = 415] = "UnsupportedMediaType";
174
+ HttpStatus[HttpStatus["UnprocessableEntity"] = 422] = "UnprocessableEntity";
175
+ HttpStatus[HttpStatus["TooManyRequests"] = 429] = "TooManyRequests";
176
+ HttpStatus[HttpStatus["InternalServerError"] = 500] = "InternalServerError";
177
+ HttpStatus[HttpStatus["BadGateway"] = 502] = "BadGateway";
178
+ HttpStatus[HttpStatus["ServiceUnavailable"] = 503] = "ServiceUnavailable";
179
+ return HttpStatus;
180
+ }({});
181
+ //#endregion
182
+ //#region src/api/ua.ts
141
183
  function getUserAgent(game) {
142
- return `${SDKName}/${SDKVersion} game/${game} node/${process.version} os/${os.platform()} arch/${os.arch()}`;
184
+ return `${SDKName}/${SDKVersion} game/${game} node/${process.version} os/${(0, os.platform)()} arch/${(0, os.arch)()}`;
143
185
  }
144
-
186
+ //#endregion
187
+ //#region src/utils/base.ts
145
188
  const urlReg = /^(?:https?:)?\/\/.+/i;
146
189
  const urlReg2 = /^https?:\/\//i;
147
190
  const objReg = /^\{[\d\D]*\}$/;
148
191
  const arrReg = /^\[[\d\D]*\]$/;
149
192
  /**
150
- * 暂停一段时间
151
- * @param {number} ms 暂停的毫秒数
152
- */
193
+ * 暂停一段时间
194
+ * @param {number} ms 暂停的毫秒数
195
+ */
153
196
  function sleep(ms) {
154
- return new Promise(resolve => setTimeout(resolve, ms));
197
+ return new Promise((resolve) => setTimeout(resolve, ms));
155
198
  }
156
199
  /**
157
- * 空函数,异步空函数为 asyncNoop
158
- */
200
+ * 空函数,异步空函数为 asyncNoop
201
+ */
159
202
  function noop() {}
160
203
  /**
161
- * 检查是否为空值 null / undefined
162
- */
204
+ * 检查是否为空值 null / undefined
205
+ */
163
206
  function isEmpty(data) {
164
- return data === null || data === undefined;
207
+ return data === null || data === void 0;
165
208
  }
166
209
  /**
167
- * 检查是否为 object(非 null / array)
168
- */
210
+ * 检查是否为 object(非 null / array)
211
+ */
169
212
  function isObject(data) {
170
- return data !== null && typeof data === "object" && !Array.isArray(data);
213
+ return data !== null && typeof data === "object" && !Array.isArray(data);
171
214
  }
172
215
  /**
173
- * 检测是否为 String Record
174
- */
216
+ * 检测是否为 String Record
217
+ */
175
218
  function isStringRecord(data) {
176
- return isObject(data) && Object.keys(data).every(key => typeof key === "string");
219
+ return isObject(data) && Object.keys(data).every((key) => typeof key === "string");
177
220
  }
178
221
  /**
179
- * 检查一个url地址是否以 http/https 开头,如果第二个参数传递 true,则自适应协议(//....)也被认为是完整 url
180
- */
222
+ * 检查一个url地址是否以 http/https 开头,如果第二个参数传递 true,则自适应协议(//....)也被认为是完整 url
223
+ */
181
224
  function isFullURL(url, ignoreProtocol = false) {
182
- return ignoreProtocol ? urlReg.test(url) : urlReg2.test(url);
225
+ return ignoreProtocol ? urlReg.test(url) : urlReg2.test(url);
183
226
  }
184
227
  /**
185
- * 检测文本是否有可能转化为 object 或 array,注意,检测通过也未必能被正确格式化为 json
186
- */
228
+ * 检测文本是否有可能转化为 object 或 array,注意,检测通过也未必能被正确格式化为 json
229
+ */
187
230
  function isJsonLike(text) {
188
- return objReg.test(text) || arrReg.test(text);
231
+ return objReg.test(text) || arrReg.test(text);
189
232
  }
190
233
  /**
191
- * 基于 baseURL 计算完整的 url 信息,仅可在浏览器环境使用
192
- * @param url 要转化的 url,如果以 https: 或 http: 开头则直接返回
193
- * @param baseURL 可选 baseURL
194
- */
234
+ * 基于 baseURL 计算完整的 url 信息,仅可在浏览器环境使用
235
+ * @param url 要转化的 url,如果以 https: 或 http: 开头则直接返回
236
+ * @param baseURL 可选 baseURL
237
+ */
195
238
  function getFullURL(url, baseURL = "") {
196
- if (!baseURL || isFullURL(url, true)) {
197
- return fillUrl(url);
198
- }
199
- return (fillUrl(baseURL) + "/" + url).replace(/\/{2,}/g, "/").replace(/:\//, "://");
239
+ if (!baseURL || isFullURL(url, true)) return fillUrl(url);
240
+ return (fillUrl(baseURL) + "/" + url).replace(/\/{2,}/g, "/").replace(/:\//, "://");
200
241
  }
201
242
  /**
202
- * 给 url 添加完整域名和协议,仅可在浏览器环境使用
203
- * @param url 要检查的 url,如果是自适应协议 //... 则会添加当前页面的协议信息,否则添加域名和协议信息
204
- */
243
+ * 给 url 添加完整域名和协议,仅可在浏览器环境使用
244
+ * @param url 要检查的 url,如果是自适应协议 //... 则会添加当前页面的协议信息,否则添加域名和协议信息
245
+ */
205
246
  function fillUrl(url) {
206
- if (isFullURL(url, true)) {
207
- if (url.startsWith("http")) {
208
- return url;
209
- }
210
- return ("location" in globalThis ? location.protocol : "https:") + url;
211
- }
212
- return ("location" in globalThis ? location.origin + "/" : "http://127.0.0.1/") + url.replace(/^\/+/, "");
247
+ if (isFullURL(url, true)) {
248
+ if (url.startsWith("http")) return url;
249
+ return ("location" in globalThis ? location.protocol : "https:") + url;
250
+ }
251
+ return ("location" in globalThis ? location.origin + "/" : "http://127.0.0.1/") + url.replace(/^\/+/, "");
213
252
  }
214
253
  /**
215
- * 简版 Object.fromEntries
216
- */
254
+ * 简版 Object.fromEntries
255
+ */
217
256
  function fromEntries(kv) {
218
- return kv.reduce((result, [key, value]) => {
219
- if (key) {
220
- result[key] = value || "";
221
- }
222
- return result;
223
- }, {});
257
+ return kv.reduce((result, [key, value]) => {
258
+ if (key) result[key] = value || "";
259
+ return result;
260
+ }, {});
224
261
  }
225
262
  function parseJSON(str, typeGuard) {
226
- try {
227
- const data = JSON.parse(str);
228
- if (typeGuard) {
229
- return typeGuard(data) ? data : null;
230
- }
231
- return data;
232
- } catch (e) {
233
- return null;
234
- }
235
- }
236
-
263
+ try {
264
+ const data = JSON.parse(str);
265
+ if (typeGuard) return typeGuard(data) ? data : null;
266
+ return data;
267
+ } catch (e) {
268
+ return null;
269
+ }
270
+ }
271
+ //#endregion
272
+ //#region src/utils/types.ts
237
273
  function getTypeGuard(typeGuard, defaultMessage = "数据未能正确识别") {
238
- if (typeof typeGuard === "function") {
239
- return {
240
- guard: typeGuard,
241
- message: defaultMessage
242
- };
243
- }
244
- return {
245
- guard: typeGuard.guard,
246
- message: typeGuard.message || defaultMessage
247
- };
248
- }
249
-
274
+ if (typeof typeGuard === "function") return {
275
+ guard: typeGuard,
276
+ message: defaultMessage
277
+ };
278
+ return {
279
+ guard: typeGuard.guard,
280
+ message: typeGuard.message || defaultMessage
281
+ };
282
+ }
283
+ //#endregion
284
+ //#region src/utils/config.ts
250
285
  /**
251
- * 校验通用配置,如果有错误,则直接 throw Error
252
- */
286
+ * 校验通用配置,如果有错误,则直接 throw Error
287
+ */
253
288
  function verifyConfig(config) {
254
- verifyConfigWithoutEndpoint(config);
255
- if (!isFullURL(config.endpoint)) {
256
- throw Error(`Config.endpoint Error, Should be url, Preset Values: ${exports.Endpoint.China}, ${exports.Endpoint.Global}}`);
257
- }
289
+ verifyConfigWithoutEndpoint(config);
290
+ if (!isFullURL(config.endpoint)) throw Error(`Config.endpoint Error, Should be url, Preset Values: ${Endpoint.China}, ${Endpoint.Global}}`);
258
291
  }
259
292
  /**
260
- * 校验通用配置,如果有错误,则直接 throw Error
261
- */
293
+ * 校验通用配置,如果有错误,则直接 throw Error
294
+ */
262
295
  function verifyConfigWithoutEndpoint(config) {
263
- if (!isObject(config)) {
264
- throw Error("Config Missing");
265
- }
266
- if (!config.game) {
267
- throw Error(`Config.game Error, Missing Required GameId`);
268
- }
269
- if (!config.secret) {
270
- throw Error(`Config.secret Error, Missing Required Secret`);
271
- }
272
- if (!config.secret.startsWith("sk_")) {
273
- throw Error(`Config.secret Error, Should be Start With sk_`);
274
- }
275
- }
276
-
296
+ if (!isObject(config)) throw Error("Config Missing");
297
+ if (!config.game) throw Error(`Config.game Error, Missing Required GameId`);
298
+ if (!config.secret) throw Error(`Config.secret Error, Missing Required Secret`);
299
+ if (!config.secret.startsWith("sk_")) throw Error(`Config.secret Error, Should be Start With sk_`);
300
+ }
301
+ //#endregion
302
+ //#region src/utils/signer.ts
277
303
  const AuthorizationField = "Authorization";
278
- const MaxTimeDiff = 5 * 60 * 1000;
304
+ const MaxTimeDiff = 300 * 1e3;
279
305
  const timestampReg = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;
280
- // 签名方法定义,给未来扩展新签名方法留出空间
281
- const SigningDefinitions = {
282
- HS256: {
283
- prefix: "SEAYOO-HMAC-SHA256",
284
- sign({
285
- game,
286
- secret,
287
- method,
288
- url,
289
- data,
290
- timestamp
291
- }, onlySignature = false) {
292
- if (timestamp && !timestampReg.test(timestamp)) {
293
- return "ErrorTimestamp";
294
- }
295
- const payloadHash = sha256(convertBodyData(data || ""));
296
- const ts = timestamp || getTimestamp();
297
- const fullURL = isFullURL(url) ? new URL(url) : new URL(url, "http://x.com");
298
- const uri = fullURL.pathname + fullURL.search;
299
- const signature = hS256(secret, [this.prefix, method.toUpperCase(), uri, ts, payloadHash].join("\n"));
300
- return onlySignature ? signature : `${this.prefix} Game=${game},Timestamp=${ts},Signature=${signature}`;
301
- },
302
- verify(authString, option) {
303
- const info = parseRawAuthHeader(authString, this.prefix);
304
- if (!info) {
305
- return false;
306
- }
307
- const game = "Game" in info ? info.Game : null;
308
- const timestamp = "Timestamp" in info ? info.Timestamp : null;
309
- const signature = "Signature" in info ? info.Signature : null;
310
- if (!game || !signature || !timestamp || option.game && option.game !== game) {
311
- return false;
312
- }
313
- const ts = parseTimestamp(timestamp);
314
- // 时间戳精度只到秒,需要忽略毫秒值
315
- const now = Math.floor(Date.now() / 1000) * 1000;
316
- if (!ts || ts < now - MaxTimeDiff || ts > now + MaxTimeDiff) {
317
- return false;
318
- }
319
- return signature === this.sign({
320
- ...option,
321
- game,
322
- timestamp
323
- }, true);
324
- }
325
- }
326
- };
306
+ const SigningDefinitions = { HS256: {
307
+ prefix: "SEAYOO-HMAC-SHA256",
308
+ sign({ game, secret, method, url, data, timestamp }, onlySignature = false) {
309
+ if (timestamp && !timestampReg.test(timestamp)) return "ErrorTimestamp";
310
+ const payloadHash = sha256(convertBodyData(data || ""));
311
+ const ts = timestamp || getTimestamp();
312
+ const fullURL = isFullURL(url) ? new URL(url) : new URL(url, "http://x.com");
313
+ const uri = fullURL.pathname + fullURL.search;
314
+ const signature = hS256(secret, [
315
+ this.prefix,
316
+ method.toUpperCase(),
317
+ uri,
318
+ ts,
319
+ payloadHash
320
+ ].join("\n"));
321
+ return onlySignature ? signature : `${this.prefix} Game=${game},Timestamp=${ts},Signature=${signature}`;
322
+ },
323
+ verify(authString, option) {
324
+ const info = parseRawAuthHeader(authString, this.prefix);
325
+ if (!info) return false;
326
+ const game = "Game" in info ? info.Game : null;
327
+ const timestamp = "Timestamp" in info ? info.Timestamp : null;
328
+ const signature = "Signature" in info ? info.Signature : null;
329
+ if (!game || !signature || !timestamp || option.game && option.game !== game) return false;
330
+ const ts = parseTimestamp(timestamp);
331
+ const now = Math.floor(Date.now() / 1e3) * 1e3;
332
+ if (!ts || ts < now - MaxTimeDiff || ts > now + MaxTimeDiff) return false;
333
+ return signature === this.sign({
334
+ ...option,
335
+ game,
336
+ timestamp
337
+ }, true);
338
+ }
339
+ } };
327
340
  /**
328
- * 格式化 AuthorizationHeader
329
- */
341
+ * 格式化 AuthorizationHeader
342
+ */
330
343
  function parseAuthorizationHeader(authString, version = "HS256") {
331
- if (!version || !SigningDefinitions[version]) {
332
- console.error({
333
- type: "parseAuthorizationHeader Error",
334
- message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
335
- });
336
- return null;
337
- }
338
- return parseRawAuthHeader(authString, SigningDefinitions[version].prefix);
344
+ if (!version || !SigningDefinitions[version]) {
345
+ console.error({
346
+ type: "parseAuthorizationHeader Error",
347
+ message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
348
+ });
349
+ return null;
350
+ }
351
+ return parseRawAuthHeader(authString, SigningDefinitions[version].prefix);
339
352
  }
340
353
  /**
341
- * 获取请求签名值,默认签名方法是 HS256
342
- */
354
+ * 获取请求签名值,默认签名方法是 HS256
355
+ */
343
356
  function calcAuthorizationHeader(option, onlySignature = false, version = "HS256") {
344
- if (!version || !SigningDefinitions[version]) {
345
- console.error({
346
- type: "calcAuthorizationHeader Error",
347
- message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
348
- });
349
- return "ErrorSigningVersion";
350
- }
351
- return SigningDefinitions[version].sign(option, onlySignature);
357
+ if (!version || !SigningDefinitions[version]) {
358
+ console.error({
359
+ type: "calcAuthorizationHeader Error",
360
+ message: `invalid version ${version}, support ${Object.keys(SigningDefinitions).join(", ")}`
361
+ });
362
+ return "ErrorSigningVersion";
363
+ }
364
+ return SigningDefinitions[version].sign(option, onlySignature);
352
365
  }
353
366
  /**
354
- * 检查 http auth 信息是否正确
355
- */
367
+ * 检查 http auth 信息是否正确
368
+ */
356
369
  function checkHttpAuthInfo(authString, option) {
357
- if (!authString) {
358
- return false;
359
- }
360
- const configs = Object.values(SigningDefinitions);
361
- for (const cfg of configs) {
362
- if (authString.startsWith(cfg.prefix + " ")) {
363
- return cfg.verify(authString, option);
364
- }
365
- }
366
- return false;
370
+ if (!authString) return false;
371
+ const configs = Object.values(SigningDefinitions);
372
+ for (const cfg of configs) if (authString.startsWith(cfg.prefix + " ")) return cfg.verify(authString, option);
373
+ return false;
367
374
  }
368
375
  function getTimestamp() {
369
- const d = new Date();
370
- return d.toISOString().replace(/\.\d+Z$/, "Z").replace(/[-:]/g, "");
376
+ return (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d+Z$/, "Z").replace(/[-:]/g, "");
371
377
  }
372
378
  function parseTimestamp(ts) {
373
- const info = ts.match(timestampReg);
374
- if (!info) {
375
- return null;
376
- }
377
- return Date.UTC(+info[1], +info[2] - 1, +info[3], +info[4], +info[5], +info[6]);
379
+ const info = ts.match(timestampReg);
380
+ if (!info) return null;
381
+ return Date.UTC(+info[1], +info[2] - 1, +info[3], +info[4], +info[5], +info[6]);
378
382
  }
379
383
  function sha256(data) {
380
- return crypto.createHash("sha256").update(data).digest("hex").toLowerCase();
384
+ return (0, crypto.createHash)("sha256").update(data).digest("hex").toLowerCase();
381
385
  }
382
386
  function hS256(secret, data) {
383
- return crypto.createHmac("sha256", secret).update(data).digest("hex").toLowerCase();
387
+ return (0, crypto.createHmac)("sha256", secret).update(data).digest("hex").toLowerCase();
384
388
  }
385
389
  function convertBodyData(body) {
386
- if (typeof body === "string") {
387
- return body;
388
- }
389
- return JSON.stringify(body);
390
+ if (typeof body === "string") return body;
391
+ return JSON.stringify(body);
390
392
  }
391
393
  function parseRawAuthHeader(authString, prefix) {
392
- if (!authString || !authString.startsWith(prefix + " ")) {
393
- return null;
394
- }
395
- return fromEntries(authString.substring(prefix.length + 1).split(",").map(kvs => {
396
- const kv = kvs.split("=");
397
- if (kv.length !== 2) {
398
- return null;
399
- }
400
- const key = kv[0].trim();
401
- const value = getValue(kv[1]);
402
- if (!key || !value) {
403
- return null;
404
- }
405
- return [key, value];
406
- }).filter(v => v !== null));
394
+ if (!authString || !authString.startsWith(prefix + " ")) return null;
395
+ return fromEntries(authString.substring(prefix.length + 1).split(",").map((kvs) => {
396
+ const kv = kvs.split("=");
397
+ if (kv.length !== 2) return null;
398
+ const key = kv[0].trim();
399
+ const value = getValue(kv[1]);
400
+ if (!key || !value) return null;
401
+ return [key, value];
402
+ }).filter((v) => v !== null));
407
403
  }
408
404
  function getValue(value) {
409
- const v = value.trim();
410
- return /^".+"$/.test(v) ? v.replace(/^"|"$/g, "") : v;
405
+ const v = value.trim();
406
+ return /^".+"$/.test(v) ? v.replace(/^"|"$/g, "") : v;
411
407
  }
412
-
408
+ //#endregion
409
+ //#region src/utils/http.ts
413
410
  async function readBody(req, backup) {
414
- const body = [];
415
- if (!req.readable) {
416
- backup || console.error({
417
- type: "RequestUnReadable",
418
- url: req.url,
419
- methe: req.method,
420
- message: "Cannot read body, stream not readable"
421
- });
422
- return backup || "";
423
- }
424
- return new Promise((resolve, reject) => {
425
- req.on("error", reject);
426
- req.on("data", chunk => body.push(chunk));
427
- req.on("end", () => {
428
- resolve(Buffer.concat(body).toString("utf-8"));
429
- });
430
- });
411
+ const body = [];
412
+ if (!req.readable) {
413
+ backup || console.error({
414
+ type: "RequestUnReadable",
415
+ url: req.url,
416
+ methe: req.method,
417
+ message: "Cannot read body, stream not readable"
418
+ });
419
+ return backup || "";
420
+ }
421
+ return new Promise((resolve, reject) => {
422
+ req.on("error", reject);
423
+ req.on("data", (chunk) => body.push(chunk));
424
+ req.on("end", () => {
425
+ resolve(Buffer.concat(body).toString("utf-8"));
426
+ });
427
+ });
431
428
  }
432
429
  async function done(res, statusCode, message) {
433
- res.statusCode = statusCode;
434
- if (statusCode !== 204) {
435
- res.write(message || "");
436
- }
437
- res.end();
430
+ res.statusCode = statusCode;
431
+ if (statusCode !== 204) res.write(message || "");
432
+ res.end();
438
433
  }
439
434
  async function responseError(res, statusCode, error, message) {
440
- res.statusCode = statusCode;
441
- if (statusCode !== 204) {
442
- res.setHeader("Content-Type", "application/json");
443
- res.write(JSON.stringify({
444
- error,
445
- message
446
- }));
447
- }
448
- res.end();
435
+ res.statusCode = statusCode;
436
+ if (statusCode !== 204) {
437
+ res.setHeader("Content-Type", "application/json");
438
+ res.write(JSON.stringify({
439
+ error,
440
+ message
441
+ }));
442
+ }
443
+ res.end();
449
444
  }
450
445
  async function responseJson(res, data, statusCode = 200) {
451
- res.statusCode = statusCode;
452
- if (statusCode !== 204) {
453
- res.setHeader("Content-Type", "application/json");
454
- res.write(JSON.stringify(data));
455
- }
456
- res.end();
457
- }
458
-
446
+ res.statusCode = statusCode;
447
+ if (statusCode !== 204) {
448
+ res.setHeader("Content-Type", "application/json");
449
+ res.write(JSON.stringify(data));
450
+ }
451
+ res.end();
452
+ }
453
+ //#endregion
454
+ //#region src/utils/index.ts
459
455
  /** 生成一个 SessionID 以用作用户上下线的上报标记 */
460
456
  function genSessionID(comboId) {
461
- const ts = process.hrtime.bigint();
462
- const r = Math.random() + Math.random();
463
- return crypto.createHash("md5").update(`${comboId}${ts}${r}`).digest("hex").toLowerCase();
457
+ const ts = process.hrtime.bigint();
458
+ const r = Math.random() + Math.random();
459
+ return (0, crypto.createHash)("md5").update(`${comboId}${ts}${r}`).digest("hex").toLowerCase();
464
460
  }
465
461
  /** 生成一个随机id */
466
462
  function genNonceString() {
467
- const ts = process.hrtime.bigint();
468
- const r = Math.random() + Math.random();
469
- return crypto.createHash("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
463
+ const ts = process.hrtime.bigint();
464
+ const r = Math.random() + Math.random();
465
+ return (0, crypto.createHash)("md5").update(`${ts}${r}`).digest("hex").toLowerCase();
470
466
  }
471
-
467
+ //#endregion
468
+ //#region src/request/inc/rule.ts
472
469
  const defaultDataField = "data";
473
470
  const defaultMessageField = "message";
474
471
  /**
475
- * 分析响应内容中的错误信息和数据
476
- */
472
+ * 分析响应内容中的错误信息和数据
473
+ */
477
474
  function analyseResponse(status, statusText, responseText, globalRule, rule) {
478
- const responseRule = rule || globalRule;
479
- return statusOK(status) ? getResponseOKInfo(responseRule.ok || globalRule.ok, status, statusText, responseText) : getReponseFailedInfo(responseRule.failed || globalRule.failed, statusText, responseText);
475
+ const responseRule = rule || globalRule;
476
+ return statusOK(status) ? getResponseOKInfo(responseRule.ok || globalRule.ok, status, statusText, responseText) : getReponseFailedInfo(responseRule.failed || globalRule.failed, statusText, responseText);
480
477
  }
481
478
  function getReponseFailedInfo(rule, statusText, responseText) {
482
- const r = rule || {
483
- resolve: "json",
484
- messageField: defaultMessageField
485
- };
486
- const result = {
487
- ok: false,
488
- code: statusText,
489
- message: responseText,
490
- data: null
491
- };
492
- switch (r.resolve) {
493
- case "body":
494
- result.message = formatPresetBody(responseText) || responseText;
495
- break;
496
- case "json":
497
- const {
498
- code,
499
- message
500
- } = formatJsonBody(responseText, r.statusField, r.messageField);
501
- result.code = code || statusText;
502
- result.message = formatPresetBody(responseText) || message;
503
- break;
504
- }
505
- return result;
479
+ const r = rule || {
480
+ resolve: "json",
481
+ messageField: defaultMessageField
482
+ };
483
+ const result = {
484
+ ok: false,
485
+ code: statusText,
486
+ message: responseText,
487
+ data: null
488
+ };
489
+ switch (r.resolve) {
490
+ case "body":
491
+ result.message = formatPresetBody(responseText) || responseText;
492
+ break;
493
+ case "json":
494
+ const { code, message } = formatJsonBody(responseText, r.statusField, r.messageField);
495
+ result.code = code || statusText;
496
+ result.message = formatPresetBody(responseText) || message;
497
+ break;
498
+ }
499
+ return result;
506
500
  }
507
501
  function formatJsonBody(body, statusField, msgField = defaultMessageField) {
508
- if (!isJsonLike(body)) {
509
- return {
510
- message: ""
511
- };
512
- }
513
- const json = parseJSON(body);
514
- if (!json || !isStringRecord(json)) {
515
- return {
516
- message: body
517
- };
518
- }
519
- return {
520
- code: statusField ? readMessageFrom(json, statusField) : "",
521
- message: readMessageFrom(json, msgField) || body
522
- };
502
+ if (!isJsonLike(body)) return { message: "" };
503
+ const json = parseJSON(body);
504
+ if (!json || !isStringRecord(json)) return { message: body };
505
+ return {
506
+ code: statusField ? readMessageFrom(json, statusField) : "",
507
+ message: readMessageFrom(json, msgField) || body
508
+ };
523
509
  }
524
510
  function readMessageFrom(json, field) {
525
- const fields = Array.isArray(field) ? field : [field];
526
- for (const field of fields) {
527
- if (field in json) {
528
- return convert2str(json[field]);
529
- }
530
- }
531
- return "";
511
+ const fields = Array.isArray(field) ? field : [field];
512
+ for (const field of fields) if (field in json) return convert2str(json[field]);
513
+ return "";
532
514
  }
533
515
  function convert2str(data) {
534
- if (!data) {
535
- return "";
536
- }
537
- if (typeof data === "string") {
538
- return data;
539
- }
540
- return JSON.stringify(data);
516
+ if (!data) return "";
517
+ if (typeof data === "string") return data;
518
+ return JSON.stringify(data);
541
519
  }
542
520
  const htmlReg = /<title>([^<]+)<\/title>/i;
543
521
  const xmlReg = /<message>([^<]+)<\/message>/i;
544
522
  function formatPresetBody(str) {
545
- const htmlMatch = str.match(htmlReg);
546
- if (htmlMatch) {
547
- return htmlMatch[1];
548
- }
549
- const xmlMatch = str.match(xmlReg);
550
- if (xmlMatch) {
551
- return xmlMatch[1];
552
- }
553
- return "";
523
+ const htmlMatch = str.match(htmlReg);
524
+ if (htmlMatch) return htmlMatch[1];
525
+ const xmlMatch = str.match(xmlReg);
526
+ if (xmlMatch) return xmlMatch[1];
527
+ return "";
554
528
  }
555
529
  function getResponseOKInfo(rule, status, statusText, responseText) {
556
- const r = rule || {
557
- resolve: "body"
558
- };
559
- const result = {
560
- ok: true,
561
- code: statusText,
562
- message: "",
563
- data: null
564
- };
565
- // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status#%E6%88%90%E5%8A%9F%E5%93%8D%E5%BA%94
566
- if (status === 202 || status === 204 || !responseText) {
567
- return result;
568
- }
569
- // 解析策略为 body 则直接将 body 当作响应数据
570
- if (r.resolve === "body") {
571
- result.data = isJsonLike(responseText) ? parseJSON(responseText) : responseText;
572
- return result;
573
- }
574
- // 否则解析策略为 json,从 object json 中查找数据和消息
575
- const response = parseJSON(responseText);
576
- if (!response || !isStringRecord(response)) {
577
- result.ok = false;
578
- result.code = "ResponseFormatError";
579
- result.message = "响应内容无法格式化为 Object";
580
- return result;
581
- }
582
- const statusField = r.statusField;
583
- const statusOKValue = r.statusOKValue || "";
584
- const dataField = r.dataField || defaultDataField;
585
- const messageField = r.messageField || defaultMessageField;
586
- const ignoreMessage = r.ignoreMessage || "";
587
- if (statusField && !(statusField in response)) {
588
- result.ok = false;
589
- result.code = "ResponseFieldMissing";
590
- result.message = "响应内容找不到状态字段 " + statusField;
591
- return result;
592
- }
593
- const code = statusField ? response[statusField] + "" : "";
594
- result.ok = statusField ? code === statusOKValue : true;
595
- result.code = code || statusText;
596
- result.data = dataField in response ? response[dataField] : null;
597
- result.message = readMessageFrom(response, messageField);
598
- if (ignoreMessage && result.message) {
599
- if (Array.isArray(ignoreMessage) && ignoreMessage.includes(result.message) || typeof ignoreMessage === "string" && result.message === ignoreMessage) {
600
- result.message = "";
601
- }
602
- }
603
- return result;
530
+ const r = rule || { resolve: "body" };
531
+ const result = {
532
+ ok: true,
533
+ code: statusText,
534
+ message: "",
535
+ data: null
536
+ };
537
+ if (status === 202 || status === 204 || !responseText) return result;
538
+ if (r.resolve === "body") {
539
+ result.data = isJsonLike(responseText) ? parseJSON(responseText) : responseText;
540
+ return result;
541
+ }
542
+ const response = parseJSON(responseText);
543
+ if (!response || !isStringRecord(response)) {
544
+ result.ok = false;
545
+ result.code = "ResponseFormatError";
546
+ result.message = "响应内容无法格式化为 Object";
547
+ return result;
548
+ }
549
+ const statusField = r.statusField;
550
+ const statusOKValue = r.statusOKValue || "";
551
+ const dataField = r.dataField || defaultDataField;
552
+ const messageField = r.messageField || defaultMessageField;
553
+ const ignoreMessage = r.ignoreMessage || "";
554
+ if (statusField && !(statusField in response)) {
555
+ result.ok = false;
556
+ result.code = "ResponseFieldMissing";
557
+ result.message = "响应内容找不到状态字段 " + statusField;
558
+ return result;
559
+ }
560
+ const code = statusField ? response[statusField] + "" : "";
561
+ result.ok = statusField ? code === statusOKValue : true;
562
+ result.code = code || statusText;
563
+ result.data = dataField in response ? response[dataField] : null;
564
+ result.message = readMessageFrom(response, messageField);
565
+ if (ignoreMessage && result.message) {
566
+ if (Array.isArray(ignoreMessage) && ignoreMessage.includes(result.message) || typeof ignoreMessage === "string" && result.message === ignoreMessage) result.message = "";
567
+ }
568
+ return result;
604
569
  }
605
570
  function statusOK(status) {
606
- return status >= 200 && status < 400;
571
+ return status >= 200 && status < 400;
607
572
  }
608
-
573
+ //#endregion
574
+ //#region src/request/inc/retry.ts
609
575
  async function retryRequest(agent, url, config, options, _try) {
610
- var _ref, _options$maxRetry, _options$retryResolve, _options$retryInterva;
611
- const currentTryCount = _try || 0;
612
- const maxRetry = Math.min(10, (_ref = (_options$maxRetry = options == null ? void 0 : options.maxRetry) != null ? _options$maxRetry : config.get("maxRetry")) != null ? _ref : 0);
613
- const retryResolve = (_options$retryResolve = options == null ? void 0 : options.retryResolve) != null ? _options$retryResolve : config.get("retryResolve");
614
- const logger = config.get("logHandler") || noop;
615
- logger({
616
- type: "prepear",
617
- url,
618
- method: (options == null ? void 0 : options.method) || "GET",
619
- retry: currentTryCount,
620
- maxRetry,
621
- message: currentTryCount === 0 ? "start" : `retry ${currentTryCount}/${maxRetry} start`,
622
- headers: options == null ? void 0 : options.headers,
623
- options
624
- });
625
- const start = Date.now();
626
- const result = await agent(url, config, options);
627
- const status = result.status;
628
- const cost = Date.now() - start;
629
- const payload = `[cost ${cost}][${status}] ${status < 0 ? result.body : ""}`;
630
- logger({
631
- type: "finished",
632
- url,
633
- method: result.method,
634
- retry: currentTryCount,
635
- maxRetry,
636
- message: currentTryCount === 0 ? `finish ${payload}` : `retry ${currentTryCount}/${maxRetry} finish ${payload}`,
637
- response: result,
638
- headers: result.headers,
639
- cost
640
- });
641
- // status 大于 0 表示服务器已经有响应
642
- const ok = statusOK(status);
643
- if (!maxRetry || retryResolve === "network" && status > 0 || retryResolve === "status" && ok || currentTryCount >= maxRetry) {
644
- return result;
645
- }
646
- const retryInterval = (_options$retryInterva = options == null ? void 0 : options.retryInterval) != null ? _options$retryInterva : config.get("retryInterval");
647
- // 最短间隔 100ms 才能重试
648
- await sleep(Math.max(100, typeof retryInterval === "function" ? retryInterval(currentTryCount + 1) : retryInterval));
649
- return await retryRequest(agent, url, config, options, currentTryCount + 1);
650
- }
651
-
576
+ var _ref, _options$maxRetry, _options$retryResolve, _options$retryInterva;
577
+ const currentTryCount = _try || 0;
578
+ const maxRetry = Math.min(10, (_ref = (_options$maxRetry = options === null || options === void 0 ? void 0 : options.maxRetry) !== null && _options$maxRetry !== void 0 ? _options$maxRetry : config.get("maxRetry")) !== null && _ref !== void 0 ? _ref : 0);
579
+ const retryResolve = (_options$retryResolve = options === null || options === void 0 ? void 0 : options.retryResolve) !== null && _options$retryResolve !== void 0 ? _options$retryResolve : config.get("retryResolve");
580
+ const logger = config.get("logHandler") || noop;
581
+ logger({
582
+ type: "prepear",
583
+ url,
584
+ method: (options === null || options === void 0 ? void 0 : options.method) || "GET",
585
+ retry: currentTryCount,
586
+ maxRetry,
587
+ message: currentTryCount === 0 ? "start" : `retry ${currentTryCount}/${maxRetry} start`,
588
+ headers: options === null || options === void 0 ? void 0 : options.headers,
589
+ options
590
+ });
591
+ const start = Date.now();
592
+ const result = await agent(url, config, options);
593
+ const status = result.status;
594
+ const cost = Date.now() - start;
595
+ const payload = `[cost ${cost}][${status}] ${status < 0 ? result.body : ""}`;
596
+ logger({
597
+ type: "finished",
598
+ url,
599
+ method: result.method,
600
+ retry: currentTryCount,
601
+ maxRetry,
602
+ message: currentTryCount === 0 ? `finish ${payload}` : `retry ${currentTryCount}/${maxRetry} finish ${payload}`,
603
+ response: result,
604
+ headers: result.headers,
605
+ cost
606
+ });
607
+ const ok = statusOK(status);
608
+ if (!maxRetry || retryResolve === "network" && status > 0 || retryResolve === "status" && ok || currentTryCount >= maxRetry) return result;
609
+ const retryInterval = (_options$retryInterva = options === null || options === void 0 ? void 0 : options.retryInterval) !== null && _options$retryInterva !== void 0 ? _options$retryInterva : config.get("retryInterval");
610
+ await sleep(Math.max(100, typeof retryInterval === "function" ? retryInterval(currentTryCount + 1) : retryInterval));
611
+ return await retryRequest(agent, url, config, options, currentTryCount + 1);
612
+ }
613
+ //#endregion
614
+ //#region src/request/inc/response.ts
652
615
  function handleResponse(res, url, config, options) {
653
- var _config$get2;
654
- // status为负数的表示网络错误或请求取消等异常情况
655
- if (res.status < 0) {
656
- return checkGlobalMessage({
657
- ok: false,
658
- status: res.status,
659
- code: res.statusText,
660
- headers: {},
661
- message: "",
662
- data: null
663
- }, `${res.method} ${url} ${res.statusText}`, res.method, url, config, options);
664
- }
665
- // 处理全局 http 错误
666
- if (!statusOK(res.status)) {
667
- var _config$get;
668
- (_config$get = config.get("errorHandler")) == null || _config$get(res.status, res.method, url);
669
- }
670
- // 分析响应内容
671
- const result = {
672
- ...analyseResponse(res.status, res.statusText, res.body, config.get("responseRule"), options == null ? void 0 : options.responseRule),
673
- status: res.status,
674
- headers: fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
675
- };
676
- // 全局处理响应结果 (浅复制,防止被修改,同时保留修改 result.data 的可能性)
677
- (_config$get2 = config.get("responseHandler")) == null || _config$get2({
678
- ...result
679
- }, res.method, url);
680
- // 检查并全局提示
681
- const defaultMessage = result.ok ? result.message : `${res.method} ${url} [${result.code || res.statusText}] ${result.message || res.statusText}`;
682
- return checkGlobalMessage(result, defaultMessage, res.method, url, config, options);
616
+ var _config$get2;
617
+ if (res.status < 0) return checkGlobalMessage({
618
+ ok: false,
619
+ status: res.status,
620
+ code: res.statusText,
621
+ headers: {},
622
+ message: "",
623
+ data: null
624
+ }, `${res.method} ${url} ${res.statusText}`, res.method, url, config, options);
625
+ if (!statusOK(res.status)) {
626
+ var _config$get;
627
+ (_config$get = config.get("errorHandler")) === null || _config$get === void 0 || _config$get(res.status, res.method, url);
628
+ }
629
+ const result = {
630
+ ...analyseResponse(res.status, res.statusText, res.body, config.get("responseRule"), options === null || options === void 0 ? void 0 : options.responseRule),
631
+ status: res.status,
632
+ headers: fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
633
+ };
634
+ (_config$get2 = config.get("responseHandler")) === null || _config$get2 === void 0 || _config$get2({ ...result }, res.method, url);
635
+ return checkGlobalMessage(result, result.ok ? result.message : `${res.method} ${url} [${result.code || res.statusText}] ${result.message || res.statusText}`, res.method, url, config, options);
683
636
  }
684
637
  function checkGlobalMessage(result, defaultMessage, method, url, config, options) {
685
- const gmessageConvert = config.get("message");
686
- const messageConvert = gmessageConvert === false || (options == null ? void 0 : options.message) === false ? false : (options == null ? void 0 : options.message) || gmessageConvert;
687
- if (messageConvert !== false) {
688
- config.showMessage(!result.ok, typeof messageConvert === "function" ? messageConvert(result, method, url, defaultMessage) : defaultMessage);
689
- }
690
- return result;
691
- }
692
-
638
+ const gmessageConvert = config.get("message");
639
+ const messageConvert = gmessageConvert === false || (options === null || options === void 0 ? void 0 : options.message) === false ? false : (options === null || options === void 0 ? void 0 : options.message) || gmessageConvert;
640
+ if (messageConvert !== false) config.showMessage(!result.ok, typeof messageConvert === "function" ? messageConvert(result, method, url, defaultMessage) : defaultMessage);
641
+ return result;
642
+ }
643
+ //#endregion
644
+ //#region src/request/inc/option.ts
693
645
  async function convertOptions(url, config, options) {
694
- var _config$get, _config$get2;
695
- const opt = Object.assign({
696
- method: "GET"
697
- }, options);
698
- const method = opt.method;
699
- if (method === "GET" || method === "HEAD" || method === "DELETE") {
700
- if (opt.body !== undefined) {
701
- console.warn("request body is invalid with method get, head, delete");
702
- delete opt.body;
703
- }
704
- }
705
- const headers = Object.assign({
706
- "Content-Type": "application/json;charset=utf-8"
707
- }, opt.headers);
708
- const p = opt.params || {};
709
- const params = {};
710
- Object.keys(p).forEach(key => {
711
- if (p[key] !== undefined) {
712
- params[key] = convertParam(p[key]);
713
- }
714
- });
715
- const fullUrl = config.getFullUrl(url);
716
- const body = convertBody(opt.body);
717
- const timeout = opt.timeout || config.get("timeout");
718
- // 全局请求干预函数,可以修改 headers 和 params 并返回新的 url 地址
719
- const newURL = await ((_config$get = config.get("requestTransformer")) == null ? void 0 : _config$get({
720
- headers,
721
- params,
722
- method,
723
- url: fullUrl,
724
- body
725
- }));
726
- const finalUrl = typeof newURL === "string" && newURL ? newURL : fullUrl;
727
- // 打印日志
728
- (_config$get2 = config.get("logHandler")) == null || _config$get2({
729
- type: "ready",
730
- url: finalUrl,
731
- method,
732
- headers,
733
- timeout,
734
- body
735
- });
736
- // 返回
737
- return {
738
- url: finalUrl,
739
- method,
740
- body,
741
- params,
742
- headers,
743
- timeout
744
- };
646
+ var _config$get, _config$get2;
647
+ const opt = Object.assign({ method: "GET" }, options);
648
+ const method = opt.method;
649
+ if (method === "GET" || method === "HEAD" || method === "DELETE") {
650
+ if (opt.body !== void 0) {
651
+ console.warn("request body is invalid with method get, head, delete");
652
+ delete opt.body;
653
+ }
654
+ }
655
+ const headers = Object.assign({ "Content-Type": "application/json;charset=utf-8" }, opt.headers);
656
+ const p = opt.params || {};
657
+ const params = {};
658
+ Object.keys(p).forEach((key) => {
659
+ if (p[key] !== void 0) params[key] = convertParam(p[key]);
660
+ });
661
+ const fullUrl = config.getFullUrl(url);
662
+ const body = convertBody(opt.body);
663
+ const timeout = opt.timeout || config.get("timeout");
664
+ const newURL = await ((_config$get = config.get("requestTransformer")) === null || _config$get === void 0 ? void 0 : _config$get({
665
+ headers,
666
+ params,
667
+ method,
668
+ url: fullUrl,
669
+ body
670
+ }));
671
+ const finalUrl = typeof newURL === "string" && newURL ? newURL : fullUrl;
672
+ (_config$get2 = config.get("logHandler")) === null || _config$get2 === void 0 || _config$get2({
673
+ type: "ready",
674
+ url: finalUrl,
675
+ method,
676
+ headers,
677
+ timeout,
678
+ body
679
+ });
680
+ return {
681
+ url: finalUrl,
682
+ method,
683
+ body,
684
+ params,
685
+ headers,
686
+ timeout
687
+ };
745
688
  }
746
689
  /** 将数据转成 string 格式表示,仅仅特殊处理 array 为 item,item... */
747
690
  function convertParam(val) {
748
- if (typeof val === "string") {
749
- return val;
750
- }
751
- if (Array.isArray(val)) {
752
- return val.join(",");
753
- }
754
- return val + "";
691
+ if (typeof val === "string") return val;
692
+ if (Array.isArray(val)) return val.join(",");
693
+ return val + "";
755
694
  }
756
695
  function convertBody(body) {
757
- if (!body) {
758
- return;
759
- }
760
- if (typeof body === "string" || body instanceof URLSearchParams) {
761
- return body;
762
- }
763
- return JSON.stringify(body);
764
- }
765
-
696
+ if (!body) return;
697
+ if (typeof body === "string" || body instanceof URLSearchParams) return body;
698
+ return JSON.stringify(body);
699
+ }
700
+ //#endregion
701
+ //#region src/request/inc/request.ts
766
702
  /**
767
- * 基于 nodejs 的 http/https 包的网络请求包装函数,url 必须是一个完整 url
768
- *
769
- * 该方法必定 resolve,限制在 nodejs 环境中使用
770
- */
771
- const nodeRequest = async function (url, config, options) {
772
- return handleResponse(await retryRequest(coreNodeRequest, url, config, options), url, config, options);
703
+ * 基于 nodejs 的 http/https 包的网络请求包装函数,url 必须是一个完整 url
704
+ *
705
+ * 该方法必定 resolve,限制在 nodejs 环境中使用
706
+ */
707
+ const nodeRequest = async function(url, config, options) {
708
+ return handleResponse(await retryRequest(coreNodeRequest, url, config, options), url, config, options);
773
709
  };
774
- const coreNodeRequest = async function (url, config, options) {
775
- const opt = await convertOptions(url, config, options);
776
- if (!isFullURL(opt.url)) {
777
- return {
778
- url: opt.url,
779
- method: opt.method,
780
- status: -2,
781
- statusText: "URLFormatError",
782
- headers: {},
783
- body: ""
784
- };
785
- }
786
- const client = /^https:\/\//i.test(opt.url) ? https__default["default"] : http__default["default"];
787
- const iURL = new URL(opt.url);
788
- const params = opt.params;
789
- if (params instanceof Object) {
790
- Object.keys(params).forEach(key => iURL.searchParams.set(key, params[key]));
791
- }
792
- const isHeadRequest = opt.method === "HEAD";
793
- return new Promise(resolve => {
794
- const req = client.request(iURL.toString(), {
795
- headers: opt.headers,
796
- method: opt.method,
797
- timeout: opt.timeout > 0 ? opt.timeout : undefined
798
- }, function (res) {
799
- const resbody = [];
800
- res.on("data", chunk => resbody.push(chunk));
801
- res.on("end", () => {
802
- const headers = fromEntries(Object.entries(res.headers).map(([key, value]) => {
803
- return [key.toLowerCase(), Array.isArray(value) ? value.join(",") : value];
804
- }));
805
- resolve({
806
- url: iURL.toString(),
807
- method: opt.method,
808
- status: res.statusCode || -3,
809
- statusText: res.statusMessage || "Unknown",
810
- headers,
811
- body: isHeadRequest ? "" : Buffer.concat(resbody).toString("utf-8")
812
- });
813
- });
814
- });
815
- req.on("error", e => {
816
- resolve({
817
- url: iURL.toString(),
818
- method: opt.method,
819
- status: -1,
820
- statusText: e.name || "Unknown",
821
- body: e.message
822
- });
823
- });
824
- req.on("timeout", () => {
825
- resolve({
826
- url: iURL.toString(),
827
- method: opt.method,
828
- status: -1,
829
- statusText: "Timeout",
830
- body: ""
831
- });
832
- });
833
- if (opt.body) {
834
- req.write(opt.body);
835
- }
836
- req.end();
837
- });
710
+ const coreNodeRequest = async function(url, config, options) {
711
+ const opt = await convertOptions(url, config, options);
712
+ if (!isFullURL(opt.url)) return {
713
+ url: opt.url,
714
+ method: opt.method,
715
+ status: -2,
716
+ statusText: "URLFormatError",
717
+ headers: {},
718
+ body: ""
719
+ };
720
+ const client = /^https:\/\//i.test(opt.url) ? https.default : http.default;
721
+ const iURL = new URL(opt.url);
722
+ const params = opt.params;
723
+ if (params instanceof Object) Object.keys(params).forEach((key) => iURL.searchParams.set(key, params[key]));
724
+ const isHeadRequest = opt.method === "HEAD";
725
+ return new Promise((resolve) => {
726
+ const req = client.request(iURL.toString(), {
727
+ headers: opt.headers,
728
+ method: opt.method,
729
+ timeout: opt.timeout > 0 ? opt.timeout : void 0
730
+ }, function(res) {
731
+ const resbody = [];
732
+ res.on("data", (chunk) => resbody.push(chunk));
733
+ res.on("end", () => {
734
+ const headers = fromEntries(Object.entries(res.headers).map(([key, value]) => {
735
+ return [key.toLowerCase(), Array.isArray(value) ? value.join(",") : value];
736
+ }));
737
+ resolve({
738
+ url: iURL.toString(),
739
+ method: opt.method,
740
+ status: res.statusCode || -3,
741
+ statusText: res.statusMessage || "Unknown",
742
+ headers,
743
+ body: isHeadRequest ? "" : Buffer.concat(resbody).toString("utf-8")
744
+ });
745
+ });
746
+ });
747
+ req.on("error", (e) => {
748
+ resolve({
749
+ url: iURL.toString(),
750
+ method: opt.method,
751
+ status: -1,
752
+ statusText: e.name || "Unknown",
753
+ body: e.message
754
+ });
755
+ });
756
+ req.on("timeout", () => {
757
+ resolve({
758
+ url: iURL.toString(),
759
+ method: opt.method,
760
+ status: -1,
761
+ statusText: "Timeout",
762
+ body: ""
763
+ });
764
+ });
765
+ if (opt.body) req.write(opt.body);
766
+ req.end();
767
+ });
838
768
  };
839
-
769
+ //#endregion
770
+ //#region src/request/inc/cache.ts
840
771
  /** 为 get 请求并发而设计的缓冲工具 */
841
- class Cache {
842
- constructor(ttl = 500) {
843
- this.ttl = void 0;
844
- this.cache = void 0;
845
- this.cache = {};
846
- this.ttl = Math.max(ttl, 0);
847
- }
848
- getKey(url, param) {
849
- const p = Object.keys(param || {}).sort().map(key => `${key}#${param == null ? void 0 : param[key]}`);
850
- return url + p.join(",");
851
- }
852
- updateTTL(ttl) {
853
- this.ttl = Math.max(ttl, 0);
854
- }
855
- get(key) {
856
- if (this.ttl === 0) {
857
- return null;
858
- }
859
- const c = this.cache[key];
860
- if (!c) {
861
- return null;
862
- }
863
- if (c.ttl < Date.now()) {
864
- delete this.cache[key];
865
- return null;
866
- }
867
- return c.res;
868
- }
869
- set(key, action) {
870
- if (this.ttl === 0) {
871
- return;
872
- }
873
- this.cache[key] = {
874
- ttl: Date.now() + this.ttl,
875
- res: action
876
- };
877
- }
878
- }
879
-
772
+ var Cache = class {
773
+ constructor(ttl = 500) {
774
+ this.cache = {};
775
+ this.ttl = Math.max(ttl, 0);
776
+ }
777
+ getKey(url, param) {
778
+ return url + Object.keys(param || {}).sort().map((key) => `${key}#${param === null || param === void 0 ? void 0 : param[key]}`).join(",");
779
+ }
780
+ updateTTL(ttl) {
781
+ this.ttl = Math.max(ttl, 0);
782
+ }
783
+ get(key) {
784
+ if (this.ttl === 0) return null;
785
+ const c = this.cache[key];
786
+ if (!c) return null;
787
+ if (c.ttl < Date.now()) {
788
+ delete this.cache[key];
789
+ return null;
790
+ }
791
+ return c.res;
792
+ }
793
+ set(key, action) {
794
+ if (this.ttl === 0) return;
795
+ this.cache[key] = {
796
+ ttl: Date.now() + this.ttl,
797
+ res: action
798
+ };
799
+ }
800
+ };
801
+ //#endregion
802
+ //#region src/request/inc/guard.ts
880
803
  function checkTypedDataResult(url, result, config, typeGard) {
881
- if (result.ok && !isEmpty(result.data) && typeGard) {
882
- const guard = getTypeGuard(typeGard, "响应数据未能正确识别");
883
- if (guard.guard(result.data)) {
884
- return result;
885
- }
886
- config.showMessage(true, `${url} ${guard.message}`);
887
- result.data = null;
888
- return result;
889
- }
890
- return result;
891
- }
892
-
893
- class RequestGlobalConfig {
894
- constructor(config) {
895
- // 保存的配置需要部分字段强制设置默认值
896
- this.config = {
897
- baseURL: "",
898
- maxRetry: 0,
899
- retryInterval: 1000,
900
- retryResolve: "network",
901
- timeout: 5000,
902
- cacheTTL: 500,
903
- responseRule: {
904
- ok: {
905
- resolve: "body"
906
- },
907
- failed: {
908
- resolve: "json",
909
- messageField: "message"
910
- }
911
- }
912
- };
913
- config && this.set(config);
914
- }
915
- set(config) {
916
- if (config.baseURL && !/^\/.+/.test(config.baseURL) && !isFullURL(config.baseURL)) {
917
- console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址");
918
- throw new Error("BaseURLError");
919
- }
920
- Object.assign(this.config, config);
921
- }
922
- get(key) {
923
- return this.config[key];
924
- }
925
- /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
926
- getFullUrl(url) {
927
- return url.startsWith("/") ? getFullURL(url) : getFullURL(url, this.config.baseURL);
928
- }
929
- /** 提示消息 */
930
- showMessage(isError, message) {
931
- if (this.config.messageHandler && message) {
932
- this.config.messageHandler(isError, message);
933
- }
934
- }
935
- }
936
-
804
+ if (result.ok && !isEmpty(result.data) && typeGard) {
805
+ const guard = getTypeGuard(typeGard, "响应数据未能正确识别");
806
+ if (guard.guard(result.data)) return result;
807
+ config.showMessage(true, `${url} ${guard.message}`);
808
+ result.data = null;
809
+ return result;
810
+ }
811
+ return result;
812
+ }
813
+ //#endregion
814
+ //#region src/request/inc/config.ts
815
+ var RequestGlobalConfig = class {
816
+ constructor(config) {
817
+ this.config = {
818
+ baseURL: "",
819
+ maxRetry: 0,
820
+ retryInterval: 1e3,
821
+ retryResolve: "network",
822
+ timeout: 5e3,
823
+ cacheTTL: 500,
824
+ responseRule: {
825
+ ok: { resolve: "body" },
826
+ failed: {
827
+ resolve: "json",
828
+ messageField: "message"
829
+ }
830
+ }
831
+ };
832
+ config && this.set(config);
833
+ }
834
+ set(config) {
835
+ if (config.baseURL && !/^\/.+/.test(config.baseURL) && !isFullURL(config.baseURL)) {
836
+ console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址");
837
+ throw new Error("BaseURLError");
838
+ }
839
+ Object.assign(this.config, config);
840
+ }
841
+ get(key) {
842
+ return this.config[key];
843
+ }
844
+ /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
845
+ getFullUrl(url) {
846
+ return url.startsWith("/") ? getFullURL(url) : getFullURL(url, this.config.baseURL);
847
+ }
848
+ /** 提示消息 */
849
+ showMessage(isError, message) {
850
+ if (this.config.messageHandler && message) this.config.messageHandler(isError, message);
851
+ }
852
+ };
853
+ //#endregion
854
+ //#region src/request/inc/main.ts
937
855
  /** 工具函数主类 */
938
- class NetRequestHandler {
939
- constructor(agent, config) {
940
- this.agent = void 0;
941
- this.config = void 0;
942
- this.cache = void 0;
943
- this.config = new RequestGlobalConfig(config);
944
- this.agent = agent;
945
- this.cache = new Cache(this.config.get("cacheTTL"));
946
- // bind this
947
- this.setConfig = this.setConfig.bind(this);
948
- this.getConfig = this.getConfig.bind(this);
949
- this.get = this.get.bind(this);
950
- this.post = this.post.bind(this);
951
- this.del = this.del.bind(this);
952
- this.patch = this.patch.bind(this);
953
- this.put = this.put.bind(this);
954
- this.head = this.head.bind(this);
955
- }
956
- /**
957
- * 执行网络请求
958
- */
959
- async exec(url, options) {
960
- return await this.agent(url, this.config, options);
961
- }
962
- /**
963
- * 检查响应的数据类型
964
- */
965
- async guard(url, result, typeGard) {
966
- return checkTypedDataResult(url, result, this.config, typeGard);
967
- }
968
- /**
969
- * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
970
- */
971
- setConfig(config) {
972
- this.config.set(config);
973
- this.cache.updateTTL(this.config.get("cacheTTL"));
974
- }
975
- /**
976
- * 读取默认的请求配置
977
- */
978
- getConfig(key) {
979
- return this.config.get(key);
980
- }
981
- /**
982
- * 发送一个 HEAD 请求,并且不处理响应 body
983
- */
984
- async head(url, options) {
985
- const ops = Object.assign({}, options || null);
986
- ops.method = "HEAD";
987
- return this.guard(url, await this.exec(url, ops), null);
988
- }
989
- async get(url, typeGard, options) {
990
- const ops = Object.assign({}, options || null);
991
- ops.method = "GET";
992
- const cacheKey = this.cache.getKey(url, ops.params);
993
- const cache = this.cache.get(cacheKey);
994
- if (cache) {
995
- return this.guard(url, await cache, typeGard || null);
996
- }
997
- const res = this.exec(url, ops);
998
- this.cache.set(cacheKey, res);
999
- return this.guard(url, await res, typeGard || null);
1000
- }
1001
- async post(url, data, typeGard, options) {
1002
- const ops = Object.assign({}, options || null);
1003
- ops.method = "POST";
1004
- ops.body = data;
1005
- return this.guard(url, await this.exec(url, ops), typeGard || null);
1006
- }
1007
- async del(url, typeGard, options) {
1008
- const ops = Object.assign({}, options || null);
1009
- ops.method = "DELETE";
1010
- return this.guard(url, await this.exec(url, ops), typeGard || null);
1011
- }
1012
- async put(url, data, typeGard, options) {
1013
- const ops = Object.assign({}, options || null);
1014
- ops.method = "PUT";
1015
- ops.body = data;
1016
- return this.guard(url, await this.exec(url, ops), typeGard || null);
1017
- }
1018
- async patch(url, data, typeGard, options) {
1019
- const ops = Object.assign({}, options || null);
1020
- ops.method = "PATCH";
1021
- ops.body = data;
1022
- return this.guard(url, await this.exec(url, ops), typeGard || null);
1023
- }
1024
- }
1025
-
856
+ var NetRequestHandler = class {
857
+ constructor(agent, config) {
858
+ this.config = new RequestGlobalConfig(config);
859
+ this.agent = agent;
860
+ this.cache = new Cache(this.config.get("cacheTTL"));
861
+ this.setConfig = this.setConfig.bind(this);
862
+ this.getConfig = this.getConfig.bind(this);
863
+ this.get = this.get.bind(this);
864
+ this.post = this.post.bind(this);
865
+ this.del = this.del.bind(this);
866
+ this.patch = this.patch.bind(this);
867
+ this.put = this.put.bind(this);
868
+ this.head = this.head.bind(this);
869
+ }
870
+ /**
871
+ * 执行网络请求
872
+ */
873
+ async exec(url, options) {
874
+ return await this.agent(url, this.config, options);
875
+ }
876
+ /**
877
+ * 检查响应的数据类型
878
+ */
879
+ async guard(url, result, typeGard) {
880
+ return checkTypedDataResult(url, result, this.config, typeGard);
881
+ }
882
+ /**
883
+ * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
884
+ */
885
+ setConfig(config) {
886
+ this.config.set(config);
887
+ this.cache.updateTTL(this.config.get("cacheTTL"));
888
+ }
889
+ /**
890
+ * 读取默认的请求配置
891
+ */
892
+ getConfig(key) {
893
+ return this.config.get(key);
894
+ }
895
+ /**
896
+ * 发送一个 HEAD 请求,并且不处理响应 body
897
+ */
898
+ async head(url, options) {
899
+ const ops = Object.assign({}, options || null);
900
+ ops.method = "HEAD";
901
+ return this.guard(url, await this.exec(url, ops), null);
902
+ }
903
+ async get(url, typeGard, options) {
904
+ const ops = Object.assign({}, options || null);
905
+ ops.method = "GET";
906
+ const cacheKey = this.cache.getKey(url, ops.params);
907
+ const cache = this.cache.get(cacheKey);
908
+ if (cache) return this.guard(url, await cache, typeGard || null);
909
+ const res = this.exec(url, ops);
910
+ this.cache.set(cacheKey, res);
911
+ return this.guard(url, await res, typeGard || null);
912
+ }
913
+ async post(url, data, typeGard, options) {
914
+ const ops = Object.assign({}, options || null);
915
+ ops.method = "POST";
916
+ ops.body = data;
917
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
918
+ }
919
+ async del(url, typeGard, options) {
920
+ const ops = Object.assign({}, options || null);
921
+ ops.method = "DELETE";
922
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
923
+ }
924
+ async put(url, data, typeGard, options) {
925
+ const ops = Object.assign({}, options || null);
926
+ ops.method = "PUT";
927
+ ops.body = data;
928
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
929
+ }
930
+ async patch(url, data, typeGard, options) {
931
+ const ops = Object.assign({}, options || null);
932
+ ops.method = "PATCH";
933
+ ops.body = data;
934
+ return this.guard(url, await this.exec(url, ops), typeGard || null);
935
+ }
936
+ };
937
+ //#endregion
938
+ //#region src/request/index.ts
1026
939
  function NetRequest(config) {
1027
- return new NetRequestHandler(nodeRequest, config);
940
+ return new NetRequestHandler(nodeRequest, config);
1028
941
  }
1029
-
942
+ //#endregion
943
+ //#region src/api/index.ts
1030
944
  const ApiPrefix = "/v1/server";
1031
945
  const TraceIdField = "x-trace-id";
1032
946
  /**
1033
- * Combo SDK For Server REST Api
1034
- */
1035
- class ApiClient {
1036
- constructor(config) {
1037
- var _config$maxRetry;
1038
- this.req = void 0;
1039
- verifyConfig(config);
1040
- const ua = getUserAgent(config.game);
1041
- this.req = NetRequest({
1042
- baseURL: `${config.endpoint.replace(/\/$/, "")}${ApiPrefix}`,
1043
- maxRetry: (_config$maxRetry = config.maxRetry) != null ? _config$maxRetry : 1,
1044
- retryInterval: config.retryInterval,
1045
- responseRule: {
1046
- ok: {
1047
- resolve: "body"
1048
- },
1049
- failed: {
1050
- resolve: "json",
1051
- statusField: "error",
1052
- messageField: "message"
1053
- }
1054
- },
1055
- requestTransformer({
1056
- headers,
1057
- method,
1058
- url,
1059
- params,
1060
- body
1061
- }) {
1062
- const iURL = new URL(url);
1063
- if (params) {
1064
- if (params instanceof Object) {
1065
- Object.keys(params).forEach(key => iURL.searchParams.set(key, params[key]));
1066
- }
1067
- }
1068
- headers["User-Agent"] = ua;
1069
- headers[AuthorizationField] = calcAuthorizationHeader({
1070
- game: config.game,
1071
- secret: config.secret,
1072
- endpoint: config.endpoint,
1073
- method,
1074
- url: iURL.toString(),
1075
- data: body || ""
1076
- });
1077
- },
1078
- logHandler: config.logger,
1079
- timeout: config.timeout || 5000
1080
- });
1081
- }
1082
- /**
1083
- * 创建订单
1084
- */
1085
- async createOrder(option) {
1086
- const {
1087
- ok,
1088
- data,
1089
- code,
1090
- status,
1091
- message,
1092
- headers
1093
- } = await this.req.post("create-order", option, isCreateOrderResponse);
1094
- if (!ok || !data) {
1095
- console.error({
1096
- type: "createOrder Error",
1097
- status,
1098
- code,
1099
- message,
1100
- traceId: headers[TraceIdField]
1101
- });
1102
- throw new Error(`createOrder: ${message || code || status}`);
1103
- }
1104
- return data;
1105
- }
1106
- /**
1107
- * 通知世游服务端玩家进入游戏世界(上线)
1108
- *
1109
- * 此接口仅用于中宣部防沉迷系统的上下线数据上报
1110
- *
1111
- * @param comboId 聚合用户标识
1112
- * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
1113
- */
1114
- async enterGame(comboId, sessionId) {
1115
- const {
1116
- ok,
1117
- status,
1118
- code,
1119
- message,
1120
- headers
1121
- } = await this.req.post("enter-game", {
1122
- combo_id: comboId,
1123
- session_id: sessionId
1124
- });
1125
- if (!ok) {
1126
- console.error({
1127
- type: "enterGame Error",
1128
- status,
1129
- code,
1130
- message,
1131
- traceId: headers[TraceIdField]
1132
- });
1133
- }
1134
- return ok;
1135
- }
1136
- /**
1137
- * 通知世游服务端玩家离开游戏世界(下线)
1138
- *
1139
- * 此接口仅用于中宣部防沉迷系统的上下线数据上报
1140
- *
1141
- * @param comboId 聚合用户标识
1142
- * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
1143
- */
1144
- async leaveGame(comboId, sessionId) {
1145
- const {
1146
- ok,
1147
- status,
1148
- code,
1149
- message,
1150
- headers
1151
- } = await this.req.post("leave-game", {
1152
- combo_id: comboId,
1153
- session_id: sessionId
1154
- });
1155
- if (!ok) {
1156
- console.error({
1157
- type: "leaveGame Error",
1158
- status,
1159
- code,
1160
- message,
1161
- traceId: headers[TraceIdField]
1162
- });
1163
- }
1164
- return ok;
1165
- }
1166
- /**
1167
- * 发送验证码
1168
- *
1169
- * @param option 发送验证码参数
1170
- */
1171
- async sendOtp(option) {
1172
- const {
1173
- ok,
1174
- data,
1175
- code,
1176
- status,
1177
- message,
1178
- headers
1179
- } = await this.req.post("send-otp", option, isSendOtpResponse);
1180
- if (!ok || !data) {
1181
- console.error({
1182
- type: "sendOtp Error",
1183
- status,
1184
- code,
1185
- message,
1186
- traceId: headers[TraceIdField]
1187
- });
1188
- throw new Error(`sendOtp: ${message || code || status}`);
1189
- }
1190
- return data;
1191
- }
1192
- /**
1193
- * 验证验证码
1194
- *
1195
- * @param option 验证码验证参数
1196
- */
1197
- async verifyOtp(option) {
1198
- const {
1199
- ok,
1200
- data,
1201
- code,
1202
- status,
1203
- message,
1204
- headers
1205
- } = await this.req.post("verify-otp", option, isVerifyOtpResponse);
1206
- if (!ok || !data) {
1207
- console.error({
1208
- type: "verifyOtp Error",
1209
- status,
1210
- code,
1211
- message,
1212
- traceId: headers[TraceIdField]
1213
- });
1214
- throw new Error(`verifyOtp: ${message || code || status}`);
1215
- }
1216
- return data;
1217
- }
1218
- /**
1219
- * 申请语音审核。
1220
- *
1221
- * 玩家认为语音房间内某些玩家存在语音违规行为时,可提交语音审核申请。调用前提是:游戏已经在世游开启语音审核服务。
1222
- */
1223
- async voiceModerationRequest(option) {
1224
- const {
1225
- ok,
1226
- status,
1227
- code,
1228
- message,
1229
- headers
1230
- } = await this.req.post("voice-moderation-request", option);
1231
- if (!ok) {
1232
- console.error({
1233
- type: "voiceModerationRequest Error",
1234
- status,
1235
- code,
1236
- message,
1237
- traceId: headers[TraceIdField]
1238
- });
1239
- }
1240
- return ok;
1241
- }
1242
- }
947
+ * Combo SDK For Server REST Api
948
+ */
949
+ var ApiClient = class {
950
+ constructor(config) {
951
+ var _config$maxRetry;
952
+ verifyConfig(config);
953
+ const ua = getUserAgent(config.game);
954
+ this.req = NetRequest({
955
+ baseURL: `${config.endpoint.replace(/\/$/, "")}${ApiPrefix}`,
956
+ maxRetry: (_config$maxRetry = config.maxRetry) !== null && _config$maxRetry !== void 0 ? _config$maxRetry : 1,
957
+ retryInterval: config.retryInterval,
958
+ responseRule: {
959
+ ok: { resolve: "body" },
960
+ failed: {
961
+ resolve: "json",
962
+ statusField: "error",
963
+ messageField: "message"
964
+ }
965
+ },
966
+ requestTransformer({ headers, method, url, params, body }) {
967
+ const iURL = new URL(url);
968
+ if (params) {
969
+ if (params instanceof Object) Object.keys(params).forEach((key) => iURL.searchParams.set(key, params[key]));
970
+ }
971
+ headers["User-Agent"] = ua;
972
+ headers[AuthorizationField] = calcAuthorizationHeader({
973
+ game: config.game,
974
+ secret: config.secret,
975
+ endpoint: config.endpoint,
976
+ method,
977
+ url: iURL.toString(),
978
+ data: body || ""
979
+ });
980
+ },
981
+ logHandler: config.logger,
982
+ timeout: config.timeout || 5e3
983
+ });
984
+ }
985
+ /**
986
+ * 创建订单
987
+ */
988
+ async createOrder(option) {
989
+ const { ok, data, code, status, message, headers } = await this.req.post("create-order", option, isCreateOrderResponse);
990
+ if (!ok || !data) {
991
+ console.error({
992
+ type: "createOrder Error",
993
+ status,
994
+ code,
995
+ message,
996
+ traceId: headers[TraceIdField]
997
+ });
998
+ throw new Error(`createOrder: ${message || code || status}`);
999
+ }
1000
+ return data;
1001
+ }
1002
+ /**
1003
+ * 通知世游服务端玩家进入游戏世界(上线)
1004
+ *
1005
+ * 此接口仅用于中宣部防沉迷系统的上下线数据上报
1006
+ *
1007
+ * @param comboId 聚合用户标识
1008
+ * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
1009
+ */
1010
+ async enterGame(comboId, sessionId) {
1011
+ const { ok, status, code, message, headers } = await this.req.post("enter-game", {
1012
+ combo_id: comboId,
1013
+ session_id: sessionId
1014
+ });
1015
+ if (!ok) console.error({
1016
+ type: "enterGame Error",
1017
+ status,
1018
+ code,
1019
+ message,
1020
+ traceId: headers[TraceIdField]
1021
+ });
1022
+ return ok;
1023
+ }
1024
+ /**
1025
+ * 通知世游服务端玩家离开游戏世界(下线)
1026
+ *
1027
+ * 此接口仅用于中宣部防沉迷系统的上下线数据上报
1028
+ *
1029
+ * @param comboId 聚合用户标识
1030
+ * @param sessionId 游戏会话标识,单次游戏会话的上下线动作必须使用同一会话标识上报
1031
+ */
1032
+ async leaveGame(comboId, sessionId) {
1033
+ const { ok, status, code, message, headers } = await this.req.post("leave-game", {
1034
+ combo_id: comboId,
1035
+ session_id: sessionId
1036
+ });
1037
+ if (!ok) console.error({
1038
+ type: "leaveGame Error",
1039
+ status,
1040
+ code,
1041
+ message,
1042
+ traceId: headers[TraceIdField]
1043
+ });
1044
+ return ok;
1045
+ }
1046
+ /**
1047
+ * 发送验证码
1048
+ *
1049
+ * @param option 发送验证码参数
1050
+ */
1051
+ async sendOtp(option) {
1052
+ const { ok, data, code, status, message, headers } = await this.req.post("send-otp", option, isSendOtpResponse);
1053
+ if (!ok || !data) {
1054
+ console.error({
1055
+ type: "sendOtp Error",
1056
+ status,
1057
+ code,
1058
+ message,
1059
+ traceId: headers[TraceIdField]
1060
+ });
1061
+ throw new Error(`sendOtp: ${message || code || status}`);
1062
+ }
1063
+ return data;
1064
+ }
1065
+ /**
1066
+ * 验证验证码
1067
+ *
1068
+ * @param option 验证码验证参数
1069
+ */
1070
+ async verifyOtp(option) {
1071
+ const { ok, data, code, status, message, headers } = await this.req.post("verify-otp", option, isVerifyOtpResponse);
1072
+ if (!ok || !data) {
1073
+ console.error({
1074
+ type: "verifyOtp Error",
1075
+ status,
1076
+ code,
1077
+ message,
1078
+ traceId: headers[TraceIdField]
1079
+ });
1080
+ throw new Error(`verifyOtp: ${message || code || status}`);
1081
+ }
1082
+ return data;
1083
+ }
1084
+ /**
1085
+ * 获取微信小游戏的接口调用凭证(Access Token),供游戏服务端调用微信服务端 API 使用。
1086
+ *
1087
+ * 接口调用凭证由世游服务端统一维护和刷新,游戏侧无需自行调用微信接口获取。
1088
+ *
1089
+ * 此接口仅适用于微信小游戏。
1090
+ *
1091
+ * 游戏服务端应当缓存接口调用凭证,缓存时间 1 分钟,按照 1 次/分钟 的频率请求该 API 获取并刷新缓存。
1092
+ *
1093
+ * @param option 获取接口调用凭证的参数
1094
+ */
1095
+ async getMiniGameWeixinAccessToken(option) {
1096
+ const { ok, data, code, status, message, headers } = await this.req.post("minigame-weixin-access-token", option, isGetMiniGameWeixinAccessTokenResponse);
1097
+ if (!ok || !data) {
1098
+ console.error({
1099
+ type: "getMiniGameWeixinAccessToken Error",
1100
+ status,
1101
+ code,
1102
+ message,
1103
+ traceId: headers[TraceIdField]
1104
+ });
1105
+ throw new Error(`getMiniGameWeixinAccessToken: ${message || code || status}`);
1106
+ }
1107
+ return data;
1108
+ }
1109
+ /**
1110
+ * 申请语音审核。
1111
+ *
1112
+ * 玩家认为语音房间内某些玩家存在语音违规行为时,可提交语音审核申请。调用前提是:游戏已经在世游开启语音审核服务。
1113
+ */
1114
+ async voiceModerationRequest(option) {
1115
+ const { ok, status, code, message, headers } = await this.req.post("voice-moderation-request", option);
1116
+ if (!ok) console.error({
1117
+ type: "voiceModerationRequest Error",
1118
+ status,
1119
+ code,
1120
+ message,
1121
+ traceId: headers[TraceIdField]
1122
+ });
1123
+ return ok;
1124
+ }
1125
+ };
1243
1126
  function isCreateOrderResponse(data) {
1244
- return isObject(data) && ["order_id", "order_token"].every(field => field in data) && "expires_at" in data && typeof data.expires_at === "number";
1127
+ return isObject(data) && ["order_id", "order_token"].every((field) => field in data) && "expires_at" in data && typeof data.expires_at === "number";
1245
1128
  }
1246
- // 目前 OTP 仅支持 sms 通道,mobile 恒为掩码后的手机号字符串,故此处统一按 string 校验。
1247
- // 后续新增 channel 时,需要在此根据 channel 补充 mobile 的关联校验
1248
- // (例如非 sms 通道下 mobile 可能为空),届时可考虑将 channel 传入本守卫。
1249
1129
  function isSendOtpResponse(data) {
1250
- return isObject(data) && "mobile" in data && "otp_ttl" in data && "otp_cooldown" in data && typeof data.mobile === "string" && typeof data.otp_ttl === "number" && typeof data.otp_cooldown === "number";
1130
+ return isObject(data) && "mobile" in data && "otp_ttl" in data && "otp_cooldown" in data && typeof data.mobile === "string" && typeof data.otp_ttl === "number" && typeof data.otp_cooldown === "number";
1251
1131
  }
1252
1132
  function isVerifyOtpResponse(data) {
1253
- return isObject(data) && "valid" in data && typeof data.valid === "boolean";
1133
+ return isObject(data) && "valid" in data && typeof data.valid === "boolean";
1134
+ }
1135
+ function isGetMiniGameWeixinAccessTokenResponse(data) {
1136
+ return isObject(data) && "app_id" in data && "access_token" in data && typeof data.app_id === "string" && typeof data.access_token === "string" && data.access_token !== "";
1254
1137
  }
1255
-
1138
+ //#endregion
1139
+ //#region src/verify/id.ts
1256
1140
  function isIdentityJwtPayload(payload) {
1257
- return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "device_id" in payload && "external_id" in payload && "external_name" in payload && "reg_time" in payload;
1141
+ return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "idp" in payload && "device_id" in payload && "external_id" in payload && "external_name" in payload && "reg_time" in payload;
1258
1142
  }
1259
-
1143
+ //#endregion
1144
+ //#region src/verify/ads.ts
1260
1145
  function isAdJwtPayload(payload) {
1261
- return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "placement_id" in payload && "impression_id" in payload;
1146
+ return isObject(payload) && "sub" in payload && "iss" in payload && "scope" in payload && "placement_id" in payload && "impression_id" in payload;
1262
1147
  }
1263
-
1148
+ //#endregion
1149
+ //#region src/utils/gcm.ts
1264
1150
  /**
1265
- * decryptAESGCM 使用 AES-256-GCM 解密 base64 编码的密文。
1266
- * 密文格式为 base64(nonce || ciphertext || authTag),其中 nonce 为 12 字节,authTag 为 16 字节。
1267
- */
1151
+ * decryptAESGCM 使用 AES-256-GCM 解密 base64 编码的密文。
1152
+ * 密文格式为 base64(nonce || ciphertext || authTag),其中 nonce 为 12 字节,authTag 为 16 字节。
1153
+ */
1268
1154
  function decryptAESGCM(sk, encoded) {
1269
- let data;
1270
- try {
1271
- data = Buffer.from(encoded, "base64");
1272
- } catch (err) {
1273
- throw new Error(`base64 decode error: ${err}`);
1274
- }
1275
- const key = deriveAESKey(sk);
1276
- const nonceSize = 12;
1277
- const authTagSize = 16;
1278
- if (data.length < nonceSize + authTagSize) {
1279
- throw new Error("ciphertext too short");
1280
- }
1281
- const nonce = data.slice(0, nonceSize);
1282
- // 密文格式: nonce (12) || ciphertext (variable) || authTag (16)
1283
- const authTag = data.slice(data.length - authTagSize);
1284
- const ciphertext = data.slice(nonceSize, data.length - authTagSize);
1285
- const decipher = crypto.createDecipheriv("aes-256-gcm", key, nonce);
1286
- decipher.setAuthTag(authTag);
1287
- // Node.js 12 兼容:使用 update 处理所有数据,避免 final() 的问题
1288
- let plaintext;
1289
- try {
1290
- plaintext = decipher.update(ciphertext);
1291
- // Node.js 12 中 GCM 模式下 final() 通常返回空 Buffer,但会验证 authTag
1292
- const finalBuffer = decipher.final();
1293
- if (finalBuffer.length > 0) {
1294
- plaintext = Buffer.concat([plaintext, finalBuffer]);
1295
- }
1296
- } catch (err) {
1297
- throw new Error(`gcm decrypt error: ${err}`);
1298
- }
1299
- return plaintext.toString("utf8");
1155
+ let data;
1156
+ try {
1157
+ data = Buffer.from(encoded, "base64");
1158
+ } catch (err) {
1159
+ throw new Error(`base64 decode error: ${err}`);
1160
+ }
1161
+ const key = deriveAESKey(sk);
1162
+ const nonceSize = 12;
1163
+ const authTagSize = 16;
1164
+ if (data.length < nonceSize + authTagSize) throw new Error("ciphertext too short");
1165
+ const nonce = data.slice(0, nonceSize);
1166
+ const authTag = data.slice(data.length - authTagSize);
1167
+ const ciphertext = data.slice(nonceSize, data.length - authTagSize);
1168
+ const decipher = (0, crypto.createDecipheriv)("aes-256-gcm", key, nonce);
1169
+ decipher.setAuthTag(authTag);
1170
+ let plaintext;
1171
+ try {
1172
+ plaintext = decipher.update(ciphertext);
1173
+ const finalBuffer = decipher.final();
1174
+ if (finalBuffer.length > 0) plaintext = Buffer.concat([plaintext, finalBuffer]);
1175
+ } catch (err) {
1176
+ throw new Error(`gcm decrypt error: ${err}`);
1177
+ }
1178
+ return plaintext.toString("utf8");
1300
1179
  }
1301
1180
  function deriveAESKey(sk) {
1302
- return crypto.createHash("sha256").update(sk).digest();
1181
+ return (0, crypto.createHash)("sha256").update(sk).digest();
1303
1182
  }
1304
-
1183
+ //#endregion
1184
+ //#region src/verify/index.ts
1305
1185
  const IdentityTokenScope = "auth";
1306
1186
  const AdTokenScope = "ads";
1307
1187
  /**
1308
- * token 验证器
1309
- */
1310
- class TokenVerifier {
1311
- constructor(config) {
1312
- this.privateKey = void 0;
1313
- this.baseOption = void 0;
1314
- verifyConfig(config);
1315
- this.privateKey = config.secret;
1316
- this.baseOption = {
1317
- // https://github.com/auth0/node-jsonwebtoken#algorithms-supported
1318
- algorithms: ["HS256"],
1319
- audience: config.game,
1320
- issuer: config.endpoint,
1321
- ignoreExpiration: false
1322
- };
1323
- }
1324
- /**
1325
- * verifyIdentityToken 对 IdentityToken 进行验证
1326
- *
1327
- * 验证失败会返回 Error 对象
1328
- */
1329
- verifyIdentityToken(token) {
1330
- try {
1331
- const payload = jsonwebtoken.verify(token, this.privateKey, {
1332
- ...this.baseOption,
1333
- complete: false
1334
- });
1335
- if (!payload || !isIdentityJwtPayload(payload) || !payload.sub) {
1336
- return new Error("verifyIdentityToken: token 格式化失败 " + JSON.stringify(payload));
1337
- }
1338
- if (payload.scope !== IdentityTokenScope) {
1339
- return new Error("verifyIdentityToken: 无效的 Scope");
1340
- }
1341
- // spell-checker:ignore AESGCM
1342
- return {
1343
- combo_id: payload.sub,
1344
- idp: payload.idp,
1345
- external_id: payload.external_id,
1346
- external_name: payload.external_name,
1347
- weixin_session_key: payload.weixin_session_key ? decryptAESGCM(this.privateKey, payload.weixin_session_key) : "",
1348
- distro: payload.distro || "",
1349
- variant: payload.variant || "",
1350
- device_id: payload.device_id || "",
1351
- age: payload.age || 0,
1352
- reg_time: payload.reg_time || 0
1353
- };
1354
- } catch (error) {
1355
- return new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1356
- }
1357
- }
1358
- /**
1359
- * verifyAdToken 对 AdToken 进行验证
1360
- *
1361
- * 验证失败会返回 Error 对象
1362
- */
1363
- verifyAdToken(token) {
1364
- try {
1365
- const payload = jsonwebtoken.verify(token, this.privateKey, {
1366
- ...this.baseOption,
1367
- complete: false
1368
- });
1369
- if (!payload || !isAdJwtPayload(payload) || !payload.sub) {
1370
- return new Error("verifyAdToken: token 格式化失败 " + JSON.stringify(payload));
1371
- }
1372
- if (payload.scope !== AdTokenScope) {
1373
- return new Error("verifyAdToken: 无效的 Scope");
1374
- }
1375
- return {
1376
- combo_id: payload.sub,
1377
- placement_id: payload.placement_id,
1378
- impression_id: payload.impression_id
1379
- };
1380
- } catch (error) {
1381
- return new Error(`AdToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1382
- }
1383
- }
1384
- }
1385
-
1188
+ * token 验证器
1189
+ */
1190
+ var TokenVerifier = class {
1191
+ constructor(config) {
1192
+ verifyConfig(config);
1193
+ this.privateKey = config.secret;
1194
+ this.baseOption = {
1195
+ algorithms: ["HS256"],
1196
+ audience: config.game,
1197
+ issuer: config.endpoint,
1198
+ ignoreExpiration: false
1199
+ };
1200
+ }
1201
+ /**
1202
+ * verifyIdentityToken 对 IdentityToken 进行验证
1203
+ *
1204
+ * 验证失败会返回 Error 对象
1205
+ */
1206
+ verifyIdentityToken(token) {
1207
+ try {
1208
+ const payload = jsonwebtoken.default.verify(token, this.privateKey, {
1209
+ ...this.baseOption,
1210
+ complete: false
1211
+ });
1212
+ if (!payload || !isIdentityJwtPayload(payload) || !payload.sub) return /* @__PURE__ */ new Error("verifyIdentityToken: token 格式化失败 " + JSON.stringify(payload));
1213
+ if (payload.scope !== IdentityTokenScope) return /* @__PURE__ */ new Error("verifyIdentityToken: 无效的 Scope");
1214
+ return {
1215
+ combo_id: payload.sub,
1216
+ idp: payload.idp,
1217
+ external_id: payload.external_id,
1218
+ external_name: payload.external_name,
1219
+ weixin_session_key: payload.weixin_session_key ? decryptAESGCM(this.privateKey, payload.weixin_session_key) : "",
1220
+ distro: payload.distro || "",
1221
+ variant: payload.variant || "",
1222
+ device_id: payload.device_id || "",
1223
+ age: payload.age || 0,
1224
+ reg_time: payload.reg_time || 0
1225
+ };
1226
+ } catch (error) {
1227
+ return /* @__PURE__ */ new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1228
+ }
1229
+ }
1230
+ /**
1231
+ * verifyAdToken 对 AdToken 进行验证
1232
+ *
1233
+ * 验证失败会返回 Error 对象
1234
+ */
1235
+ verifyAdToken(token) {
1236
+ try {
1237
+ const payload = jsonwebtoken.default.verify(token, this.privateKey, {
1238
+ ...this.baseOption,
1239
+ complete: false
1240
+ });
1241
+ if (!payload || !isAdJwtPayload(payload) || !payload.sub) return /* @__PURE__ */ new Error("verifyAdToken: token 格式化失败 " + JSON.stringify(payload));
1242
+ if (payload.scope !== AdTokenScope) return /* @__PURE__ */ new Error("verifyAdToken: 无效的 Scope");
1243
+ return {
1244
+ combo_id: payload.sub,
1245
+ placement_id: payload.placement_id,
1246
+ impression_id: payload.impression_id
1247
+ };
1248
+ } catch (error) {
1249
+ return /* @__PURE__ */ new Error(`AdToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
1250
+ }
1251
+ }
1252
+ };
1253
+ //#endregion
1254
+ //#region src/notify/msgShipOrder.ts
1386
1255
  function isShipOrderPayload(data) {
1387
- return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && ("is_sandbox" in data ? typeof data.is_sandbox === "boolean" : true) && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1256
+ return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && ("is_sandbox" in data ? typeof data.is_sandbox === "boolean" : true) && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1388
1257
  }
1389
-
1258
+ //#endregion
1259
+ //#region src/notify/msgRefund.ts
1390
1260
  function isRefundPayload(data) {
1391
- return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1261
+ return isObject(data) && "order_id" in data && "reference_id" in data && "combo_id" in data && "product_id" in data && "quantity" in data && "currency" in data && "amount" in data && typeof data.order_id === "string" && typeof data.combo_id === "string" && typeof data.quantity === "number" && typeof data.amount === "number" && Number.isSafeInteger(data.quantity) && Number.isSafeInteger(data.amount) && !!data.order_id && !!data.combo_id;
1262
+ }
1263
+ //#endregion
1264
+ //#region src/notify/msgDataTags.ts
1265
+ function isDataTag(data) {
1266
+ return isObject(data) && "entity_type" in data && "entity_id" in data && "tag_name" in data && "tag_value" in data && typeof data.entity_type === "string" && typeof data.entity_id === "string" && typeof data.tag_name === "string" && typeof data.tag_value === "string" && !!data.entity_type && !!data.entity_id && !!data.tag_name;
1267
+ }
1268
+ function isDataTagsPayload(data) {
1269
+ return isObject(data) && "tags" in data && Array.isArray(data.tags) && data.tags.every(isDataTag);
1392
1270
  }
1393
-
1271
+ //#endregion
1272
+ //#region src/notify/types.ts
1394
1273
  /**
1395
- * 消息处理分发配置
1396
- */
1274
+ * 通知类型枚举
1275
+ */
1276
+ let NotificationType = /* @__PURE__ */ function(NotificationType) {
1277
+ /**
1278
+ * 世游服务端会在订单状态变更为已支付时,向游戏侧推送发货通知。
1279
+ *
1280
+ * 游戏侧需要在收到通知后,根据通知中的订单信息,发货给用户:
1281
+ *
1282
+ * - 如果游戏内发货成功,则应当返回 void 或 Promise<void>
1283
+ * - 如果游戏内发货出现错误,则应当 throw Error。世游服务端会在稍后重试推送发货通知。
1284
+ */
1285
+ NotificationType["ShipOrder"] = "ship_order";
1286
+ /**
1287
+ * 世游服务端会在订单状态发生退款时,向游戏侧推送退款通知。
1288
+ */
1289
+ NotificationType["Refund"] = "refund";
1290
+ /**
1291
+ * 世游服务端会将约定好的数据标签批量推送给游戏侧。
1292
+ *
1293
+ * 预期游戏侧在接收到数据标签通知后,将这些数据标签持久化存储:
1294
+ *
1295
+ * - 如果游戏内成功处理了数据标签通知,则应当返回 void 或 Promise<void>
1296
+ * - 如果游戏内处理数据标签时出现错误,则应当 throw Error。世游服务端会在稍后重试推送数据标签通知。
1297
+ */
1298
+ NotificationType["DataTags"] = "data_tags";
1299
+ return NotificationType;
1300
+ }({});
1301
+ /**
1302
+ * 消息处理分发配置
1303
+ */
1397
1304
  const messageDataGuards = {
1398
- ["ship_order" /* NotificationType.ShipOrder */]: {
1399
- guard: isShipOrderPayload,
1400
- message: "ShipOrder Data Format Error"
1401
- },
1402
- ["refund" /* NotificationType.Refund */]: {
1403
- guard: isRefundPayload,
1404
- message: "Refund Data Format Error"
1405
- }
1305
+ [NotificationType.ShipOrder]: {
1306
+ guard: isShipOrderPayload,
1307
+ message: "ShipOrder Data Format Error"
1308
+ },
1309
+ [NotificationType.Refund]: {
1310
+ guard: isRefundPayload,
1311
+ message: "Refund Data Format Error"
1312
+ },
1313
+ [NotificationType.DataTags]: {
1314
+ guard: isDataTagsPayload,
1315
+ message: "DataTags Data Format Error"
1316
+ }
1406
1317
  };
1407
-
1318
+ //#endregion
1319
+ //#region src/notify/index.ts
1408
1320
  function isNotificationRequestBody(data) {
1409
- return isObject(data) && "version" in data && "notification_id" in data && "notification_type" in data && "data" in data && typeof data.version === "string" && typeof data.notification_id === "string" && typeof data.notification_type === "string";
1321
+ return isObject(data) && "version" in data && "notification_id" in data && "notification_type" in data && "data" in data && typeof data.version === "string" && typeof data.notification_id === "string" && typeof data.notification_type === "string";
1410
1322
  }
1411
1323
  /**
1412
- * 获取一个处理函数用于接收 Seayoo Server 推送过来的消息通知
1413
- *
1414
- * 另有 express 和 koa2 版本的处理函数可以使用。
1415
- *
1416
- * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1417
- */
1324
+ * 获取一个处理函数用于接收 Seayoo Server 推送过来的消息通知
1325
+ *
1326
+ * 另有 express 和 koa2 版本的处理函数可以使用。
1327
+ *
1328
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1329
+ */
1418
1330
  function getNotificationHandler(config, handler) {
1419
- verifyConfig(config);
1420
- /**
1421
- * 第三个可选参数 rawBodyString 用于在特定场景 request 为 unreadable 时作为容错兜底方案处理
1422
- *
1423
- * 具体方案可以参考
1424
- *
1425
- * https://cloud.tencent.com/developer/ask/sof/110062928
1426
- */
1427
- return async function (req, res, rawBodyString) {
1428
- if (req.method !== "POST") {
1429
- done(res, 405 /* HttpStatus.MethodNotAllowed */);
1430
- return;
1431
- }
1432
- const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1433
- if (!contentType || !contentType.startsWith("application/json")) {
1434
- done(res, 415 /* HttpStatus.UnsupportedMediaType */);
1435
- return;
1436
- }
1437
- const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
1438
- const body = await readBody(req, rawBodyString);
1439
- if (!body || !checkHttpAuthInfo(`${authString}`, {
1440
- game: config.game,
1441
- secret: config.secret,
1442
- method: "POST",
1443
- // 此处协议不参与计算不需要准确设定
1444
- endpoint: `http://${req.headers.host}`,
1445
- url: req.url || "",
1446
- data: body
1447
- })) {
1448
- done(res, 401 /* HttpStatus.Unauthorized */);
1449
- return;
1450
- }
1451
- const notification = parseJSON(body, isNotificationRequestBody);
1452
- if (!notification) {
1453
- done(res, 400 /* HttpStatus.BadRequest */, `Notification body format error`);
1454
- return;
1455
- }
1456
- const guardCfg = messageDataGuards[notification.notification_type];
1457
- if (!guardCfg) {
1458
- done(res, 400 /* HttpStatus.BadRequest */, `Unknown notification type: ${notification.notification_type}`);
1459
- return;
1460
- }
1461
- if (!guardCfg.guard(notification.data)) {
1462
- done(res, 400 /* HttpStatus.BadRequest */, guardCfg.message);
1463
- return;
1464
- }
1465
- // 所有错误检查完毕,通知游戏处理函数
1466
- try {
1467
- await handler(notification.notification_type, notification.data);
1468
- done(res, 200 /* HttpStatus.OK */, "OK");
1469
- } catch (e) {
1470
- console.error(`notify handler error`, e);
1471
- done(res, 500 /* HttpStatus.InternalServerError */, e instanceof Error ? e.message : String(e));
1472
- }
1473
- };
1331
+ verifyConfig(config);
1332
+ /**
1333
+ * 第三个可选参数 rawBodyString 用于在特定场景 request 为 unreadable 时作为容错兜底方案处理
1334
+ *
1335
+ * 具体方案可以参考
1336
+ *
1337
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1338
+ */
1339
+ return async function(req, res, rawBodyString) {
1340
+ if (req.method !== "POST") {
1341
+ done(res, HttpStatus.MethodNotAllowed);
1342
+ return;
1343
+ }
1344
+ const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1345
+ if (!contentType || !contentType.startsWith("application/json")) {
1346
+ done(res, HttpStatus.UnsupportedMediaType);
1347
+ return;
1348
+ }
1349
+ const authString = req.headers["Authorization"] || req.headers["Authorization".toLowerCase()];
1350
+ const body = await readBody(req, rawBodyString);
1351
+ if (!body || !checkHttpAuthInfo(`${authString}`, {
1352
+ game: config.game,
1353
+ secret: config.secret,
1354
+ method: "POST",
1355
+ endpoint: `http://${req.headers.host}`,
1356
+ url: req.url || "",
1357
+ data: body
1358
+ })) {
1359
+ done(res, HttpStatus.Unauthorized);
1360
+ return;
1361
+ }
1362
+ const notification = parseJSON(body, isNotificationRequestBody);
1363
+ if (!notification) {
1364
+ done(res, HttpStatus.BadRequest, `Notification body format error`);
1365
+ return;
1366
+ }
1367
+ const guardCfg = messageDataGuards[notification.notification_type];
1368
+ if (!guardCfg) {
1369
+ done(res, HttpStatus.BadRequest, `Unknown notification type: ${notification.notification_type}`);
1370
+ return;
1371
+ }
1372
+ if (!guardCfg.guard(notification.data)) {
1373
+ done(res, HttpStatus.BadRequest, guardCfg.message);
1374
+ return;
1375
+ }
1376
+ try {
1377
+ await handler(notification.notification_type, notification.data);
1378
+ done(res, HttpStatus.OK, "OK");
1379
+ } catch (e) {
1380
+ console.error(`notify handler error`, e);
1381
+ done(res, HttpStatus.InternalServerError, e instanceof Error ? e.message : String(e));
1382
+ }
1383
+ };
1474
1384
  }
1475
1385
  /**
1476
- * 获取基于 express 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1477
- *
1478
- * 如需自定义处理,可以使用 getNotificationHandler 方法,
1479
- *
1480
- * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1481
- *
1482
- * 处理方法可以参考
1483
- *
1484
- * https://cloud.tencent.com/developer/ask/sof/110062928
1485
- */
1386
+ * 获取基于 express 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1387
+ *
1388
+ * 如需自定义处理,可以使用 getNotificationHandler 方法,
1389
+ *
1390
+ * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1391
+ *
1392
+ * 处理方法可以参考
1393
+ *
1394
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1395
+ */
1486
1396
  function getNotificationHandlerForExpress(config, handler) {
1487
- const func = getNotificationHandler(config, handler);
1488
- return async function (req, res) {
1489
- await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1490
- };
1397
+ const func = getNotificationHandler(config, handler);
1398
+ return async function(req, res) {
1399
+ await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1400
+ };
1491
1401
  }
1492
1402
  /**
1493
- * 获取基于 express 的中间件用于接收 Seayoo Server 推送过来的消息通知
1494
- *
1495
- * 需要先于 body-parse 等类似插件加载
1496
- */
1403
+ * 获取基于 express 的中间件用于接收 Seayoo Server 推送过来的消息通知
1404
+ *
1405
+ * 需要先于 body-parse 等类似插件加载
1406
+ */
1497
1407
  function getNotificationMiddlewareForExpress(paths, config, handler) {
1498
- const func = getNotificationHandler(config, handler);
1499
- const matchPaths = Array.isArray(paths) ? paths : [paths];
1500
- return async function (req, res, next) {
1501
- if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1502
- await func(req, res);
1503
- return;
1504
- }
1505
- next();
1506
- };
1408
+ const func = getNotificationHandler(config, handler);
1409
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1410
+ return async function(req, res, next) {
1411
+ if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1412
+ await func(req, res);
1413
+ return;
1414
+ }
1415
+ next();
1416
+ };
1507
1417
  }
1508
1418
  /**
1509
- * 获取基于 koa2 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1510
- *
1511
- * 如需自定义处理,可以使用 getNotificationHandler 方法
1512
- *
1513
- * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1514
- */
1419
+ * 获取基于 koa2 的处理函数用于接收 Seayoo Server 推送过来的消息通知
1420
+ *
1421
+ * 如需自定义处理,可以使用 getNotificationHandler 方法
1422
+ *
1423
+ * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1424
+ */
1515
1425
  function getNotificationHandlerForKoa(config, handler) {
1516
- const func = getNotificationHandler(config, handler);
1517
- return async function (ctx) {
1518
- await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1519
- };
1426
+ const func = getNotificationHandler(config, handler);
1427
+ return async function(ctx) {
1428
+ await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1429
+ };
1520
1430
  }
1521
1431
  /**
1522
- * 获取基于 koa2 的中间件用于接收 Seayoo Server 推送过来的消息通知
1523
- *
1524
- * 需要先于 koa-body 等类似插件加载
1525
- */
1432
+ * 获取基于 koa2 的中间件用于接收 Seayoo Server 推送过来的消息通知
1433
+ *
1434
+ * 需要先于 koa-body 等类似插件加载
1435
+ */
1526
1436
  function getNotificationMiddlewareForKoa(paths, config, handler) {
1527
- const func = getNotificationHandler(config, handler);
1528
- const matchPaths = Array.isArray(paths) ? paths : [paths];
1529
- return async function (ctx, next) {
1530
- if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1531
- await func(ctx.req, ctx.res);
1532
- return;
1533
- }
1534
- await next();
1535
- };
1536
- }
1537
-
1437
+ const func = getNotificationHandler(config, handler);
1438
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1439
+ return async function(ctx, next) {
1440
+ if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1441
+ await func(ctx.req, ctx.res);
1442
+ return;
1443
+ }
1444
+ await next();
1445
+ };
1446
+ }
1447
+ //#endregion
1448
+ //#region src/gm/types.ts
1538
1449
  function isGMRequestBody(data) {
1539
- return isObject(data) && "version" in data && "request_id" in data && "command" in data && "args" in data && ("idempotency_key" in data ? typeof data.idempotency_key === "string" : true) && ("origin" in data ? typeof data.origin === "string" : true) && typeof data.request_id === "string" && typeof data.command === "string" && typeof data.args === "object" && data.args !== null;
1450
+ return isObject(data) && "version" in data && "request_id" in data && "command" in data && "args" in data && ("idempotency_key" in data ? typeof data.idempotency_key === "string" : true) && ("origin" in data ? typeof data.origin === "string" : true) && typeof data.request_id === "string" && typeof data.command === "string" && typeof data.args === "object" && data.args !== null;
1540
1451
  }
1541
1452
  function isGMErrorResponse(data) {
1542
- return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1453
+ return isObject(data) && Object.keys(data).length === 2 && "error" in data && "message" in data;
1543
1454
  }
1544
1455
  function isIdempotencyRecord(data) {
1545
- return isObject(data) && "key" in data && "id" in data && "cmd" in data && "args" in data;
1456
+ return isObject(data) && "key" in data && "id" in data && "cmd" in data && "args" in data;
1546
1457
  }
1547
-
1458
+ //#endregion
1459
+ //#region src/gm/utils.ts
1548
1460
  function verifyStoreHelper(storeHelper) {
1549
- if (storeHelper) {
1550
- if (typeof storeHelper !== "object" || !("setXX" in storeHelper) || !("setNX" in storeHelper)) {
1551
- throw new Error("store helper should be { setXX, setNX }");
1552
- }
1553
- if (typeof storeHelper.setNX !== "function" || storeHelper.setNX.length !== 2) {
1554
- throw new Error("store.setNX should be (key, value) => string");
1555
- }
1556
- if (typeof storeHelper.setXX !== "function" || storeHelper.setXX.length !== 2) {
1557
- throw new Error("store.setXX should be (key, value) => void");
1558
- }
1559
- }
1461
+ if (storeHelper) {
1462
+ if (typeof storeHelper !== "object" || !("setXX" in storeHelper) || !("setNX" in storeHelper)) throw new Error("store helper should be { setXX, setNX }");
1463
+ if (typeof storeHelper.setNX !== "function" || storeHelper.setNX.length !== 2) throw new Error("store.setNX should be (key, value) => string");
1464
+ if (typeof storeHelper.setXX !== "function" || storeHelper.setXX.length !== 2) throw new Error("store.setXX should be (key, value) => void");
1465
+ }
1560
1466
  }
1561
1467
  function toString(data) {
1562
- return JSON.stringify(data);
1468
+ return JSON.stringify(data);
1563
1469
  }
1564
1470
  /** 提供基于内存的 store helper,仅供本地调试使用,不支持 ttl 超时功能 */
1565
- class MemoryIdempotencyStore {
1566
- constructor() {
1567
- this.mc = void 0;
1568
- this.mc = {};
1569
- }
1570
- async setNX(key, value) {
1571
- const r = this.mc[key];
1572
- if (!r) {
1573
- this.mc[key] = value;
1574
- return "";
1575
- }
1576
- return r;
1577
- }
1578
- async setXX(key, value) {
1579
- const r = this.mc[key];
1580
- if (r) {
1581
- this.mc[key] = value;
1582
- }
1583
- }
1584
- }
1471
+ var MemoryIdempotencyStore = class {
1472
+ constructor() {
1473
+ this.mc = {};
1474
+ }
1475
+ async setNX(key, value) {
1476
+ const r = this.mc[key];
1477
+ if (!r) {
1478
+ this.mc[key] = value;
1479
+ return "";
1480
+ }
1481
+ return r;
1482
+ }
1483
+ async setXX(key, value) {
1484
+ if (this.mc[key]) this.mc[key] = value;
1485
+ }
1486
+ };
1585
1487
  /**
1586
- * 基于 ioredis 的 store helper,
1587
- *
1588
- * 需要 Redis >= 7.0,见 https://redis.io/docs/latest/commands/set/
1589
- */
1590
- class RedisIdempotencyStore {
1591
- constructor(options) {
1592
- var _options$ttl;
1593
- this.client = void 0;
1594
- this.ttl = void 0;
1595
- this.prefix = void 0;
1596
- this.client = options.client;
1597
- this.ttl = Math.max(24 * 3600, (_options$ttl = options.ttl) != null ? _options$ttl : 0);
1598
- this.prefix = options.prefix || "";
1599
- }
1600
- async setNX(key, value) {
1601
- return (await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "NX", "GET")) || "";
1602
- }
1603
- async setXX(key, value) {
1604
- await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "XX");
1605
- }
1606
- }
1607
-
1488
+ * 基于 ioredis 的 store helper,
1489
+ *
1490
+ * 需要 Redis >= 7.0,见 https://redis.io/docs/latest/commands/set/
1491
+ */
1492
+ var RedisIdempotencyStore = class {
1493
+ constructor(options) {
1494
+ var _options$ttl;
1495
+ this.client = options.client;
1496
+ this.ttl = Math.max(24 * 3600, (_options$ttl = options.ttl) !== null && _options$ttl !== void 0 ? _options$ttl : 0);
1497
+ this.prefix = options.prefix || "";
1498
+ }
1499
+ async setNX(key, value) {
1500
+ return await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "NX", "GET") || "";
1501
+ }
1502
+ async setXX(key, value) {
1503
+ await this.client.set(`${this.prefix}${key}`, value, "EX", this.ttl, "XX");
1504
+ }
1505
+ };
1506
+ //#endregion
1507
+ //#region src/gm/index.ts
1608
1508
  const error2httpStatus = {
1609
- [exports.GMError.InvalidHttpMethod]: 405 /* HttpStatus.MethodNotAllowed */,
1610
- [exports.GMError.InvalidContentType]: 415 /* HttpStatus.UnsupportedMediaType */,
1611
- [exports.GMError.InvalidSignature]: 401 /* HttpStatus.Unauthorized */,
1612
- [exports.GMError.InvalidRequest]: 400 /* HttpStatus.BadRequest */,
1613
- [exports.GMError.InvalidCommand]: 400 /* HttpStatus.BadRequest */,
1614
- [exports.GMError.InvalidArgs]: 400 /* HttpStatus.BadRequest */,
1615
- [exports.GMError.NetworkError]: 500 /* HttpStatus.InternalServerError */,
1616
- [exports.GMError.DatabaseError]: 500 /* HttpStatus.InternalServerError */,
1617
- [exports.GMError.IdempotencyConflict]: 409 /* HttpStatus.Conflict */,
1618
- [exports.GMError.IdempotencyMismatch]: 422 /* HttpStatus.UnprocessableEntity */,
1619
- [exports.GMError.TimeoutError]: 500 /* HttpStatus.InternalServerError */,
1620
- [exports.GMError.MaintenanceError]: 503 /* HttpStatus.ServiceUnavailable */,
1621
- [exports.GMError.ThrottlingError]: 429 /* HttpStatus.TooManyRequests */,
1622
- [exports.GMError.InternalError]: 500 /* HttpStatus.InternalServerError */
1509
+ [GMError.InvalidHttpMethod]: HttpStatus.MethodNotAllowed,
1510
+ [GMError.InvalidContentType]: HttpStatus.UnsupportedMediaType,
1511
+ [GMError.InvalidSignature]: HttpStatus.Unauthorized,
1512
+ [GMError.InvalidRequest]: HttpStatus.BadRequest,
1513
+ [GMError.InvalidCommand]: HttpStatus.BadRequest,
1514
+ [GMError.InvalidArgs]: HttpStatus.BadRequest,
1515
+ [GMError.NetworkError]: HttpStatus.InternalServerError,
1516
+ [GMError.DatabaseError]: HttpStatus.InternalServerError,
1517
+ [GMError.IdempotencyConflict]: HttpStatus.Conflict,
1518
+ [GMError.IdempotencyMismatch]: HttpStatus.UnprocessableEntity,
1519
+ [GMError.TimeoutError]: HttpStatus.InternalServerError,
1520
+ [GMError.MaintenanceError]: HttpStatus.ServiceUnavailable,
1521
+ [GMError.ThrottlingError]: HttpStatus.TooManyRequests,
1522
+ [GMError.InternalError]: HttpStatus.InternalServerError
1623
1523
  };
1624
1524
  /**
1625
- * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
1626
- *
1627
- * 另有 express 和 koa2 版本的处理函数可以使用。
1628
- *
1629
- * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1630
- */
1525
+ * 获取一个处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知,storeHelper 提供存储支持以实现幂等key(idempotencyKey)的自动化处理
1526
+ *
1527
+ * 另有 express 和 koa2 版本的处理函数可以使用。
1528
+ *
1529
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1530
+ */
1631
1531
  function getGMCommandHandler(config, handler, storeHelper) {
1632
- verifyConfigWithoutEndpoint(config);
1633
- verifyStoreHelper(storeHelper);
1634
- return async function (req, res, rawBodyString) {
1635
- if (req.method !== "POST") {
1636
- responseError(res, 405 /* HttpStatus.MethodNotAllowed */, exports.GMError.InvalidHttpMethod, `Expecting POST, got ${req.method}`);
1637
- return;
1638
- }
1639
- const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1640
- if (!contentType || !contentType.startsWith("application/json")) {
1641
- responseError(res, 415 /* HttpStatus.UnsupportedMediaType */, exports.GMError.InvalidContentType, `Expecting application/json, got ${contentType}`);
1642
- return;
1643
- }
1644
- const authString = req.headers[AuthorizationField] || req.headers[AuthorizationField.toLowerCase()];
1645
- const body = await readBody(req, rawBodyString);
1646
- if (!body || !checkHttpAuthInfo(`${authString}`, {
1647
- game: config.game,
1648
- secret: config.secret,
1649
- method: "POST",
1650
- // 此处协议不参与计算不需要准确设定
1651
- endpoint: `http://${req.headers.host}`,
1652
- url: req.url || "",
1653
- data: body
1654
- })) {
1655
- responseError(res, 401 /* HttpStatus.Unauthorized */, exports.GMError.InvalidSignature, "Signature failed");
1656
- return;
1657
- }
1658
- const gmRequest = parseJSON(body, isGMRequestBody);
1659
- if (!gmRequest) {
1660
- responseError(res, 400 /* HttpStatus.BadRequest */, exports.GMError.InvalidRequest, `GM request body format error`);
1661
- return;
1662
- }
1663
- // 处理幂等key
1664
- const currentRecord = {
1665
- nonce: genNonceString(),
1666
- key: gmRequest.idempotency_key || "",
1667
- id: gmRequest.request_id,
1668
- cmd: gmRequest.command,
1669
- args: toString(gmRequest.args)
1670
- };
1671
- let oldResponse = null;
1672
- if (storeHelper && gmRequest.idempotency_key) {
1673
- const oldRecordStr = await storeHelper.setNX(gmRequest.idempotency_key, toString(currentRecord)).catch(e => e instanceof Error ? e : new Error(String(e)));
1674
- if (oldRecordStr instanceof Error) {
1675
- console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) setNX error`, oldRecordStr);
1676
- responseError(res, 500 /* HttpStatus.InternalServerError */, exports.GMError.InternalError, oldRecordStr.message);
1677
- return;
1678
- }
1679
- const oldRecord = oldRecordStr ? parseJSON(oldRecordStr, isIdempotencyRecord) : null;
1680
- if (!oldRecord && oldRecordStr) {
1681
- console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) parse old idempotency record failed: ${oldRecordStr}`);
1682
- responseError(res, 500 /* HttpStatus.InternalServerError */, exports.GMError.InternalError, "parse old idempotency record failed");
1683
- return;
1684
- }
1685
- // spell-checker:disable
1686
- // fix spell error
1687
- if (oldRecord && "noce" in oldRecord) {
1688
- oldRecord.nonce = oldRecord.noce + "";
1689
- }
1690
- // spell-checker:enable
1691
- // 检查是否为首次请求
1692
- const isFirstRequest = oldRecordStr === "" || (oldRecord == null ? void 0 : oldRecord.nonce) === currentRecord.nonce;
1693
- if (!isFirstRequest && oldRecord) {
1694
- if (!oldRecord.resp) {
1695
- responseError(res, error2httpStatus[exports.GMError.IdempotencyConflict], exports.GMError.IdempotencyConflict, "previous request is not completed");
1696
- return;
1697
- }
1698
- if (oldRecord.cmd !== gmRequest.command) {
1699
- responseError(res, error2httpStatus[exports.GMError.IdempotencyMismatch], exports.GMError.IdempotencyMismatch, `cmd mismatch, expecting ${oldRecord.cmd}, got ${gmRequest.command}`);
1700
- return;
1701
- }
1702
- if (oldRecord.args !== currentRecord.args) {
1703
- responseError(res, error2httpStatus[exports.GMError.IdempotencyMismatch], exports.GMError.IdempotencyMismatch, `args mismatch, expecting ${oldRecord.args}, got ${currentRecord.args}`);
1704
- return;
1705
- }
1706
- oldResponse = oldRecord.resp;
1707
- }
1708
- }
1709
- // 所有错误检查完毕,通知游戏处理函数
1710
- try {
1711
- const result = oldResponse || (await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version, gmRequest.origin || ""));
1712
- // 记录handler返回的结果以备下次检查使用,setXX出现错误也不再中断请求
1713
- if (storeHelper && gmRequest.idempotency_key) {
1714
- currentRecord.resp = result;
1715
- storeHelper.setXX(gmRequest.idempotency_key, toString(currentRecord)).catch(err => {
1716
- console.error("failed to setXX idempotency record", err, currentRecord);
1717
- });
1718
- }
1719
- // 游戏主动抛错不打印日志信息
1720
- if (result instanceof Error) {
1721
- responseError(res, 500 /* HttpStatus.InternalServerError */, exports.GMError.InternalError, result.message);
1722
- return;
1723
- }
1724
- if (isGMErrorResponse(result)) {
1725
- responseError(res, error2httpStatus[result.error] || 500 /* HttpStatus.InternalServerError */, result.error || exports.GMError.InternalError, result.message);
1726
- return;
1727
- }
1728
- // 对游戏处理函数进一步兼容处理,允许返回一个预定义的错误码
1729
- // 但此逻辑不作为公开 api,仅作为内容兼容处理
1730
- if (typeof result === "string" && result in error2httpStatus) {
1731
- responseError(res, error2httpStatus[result], result, result);
1732
- return;
1733
- }
1734
- // 如果 result 没有结果则进行提示然后继续
1735
- if (!result) {
1736
- console.warn(`gm command "${gmRequest.command}" should give back some data`);
1737
- }
1738
- responseJson(res, result != null ? result : {});
1739
- } catch (e) {
1740
- console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) exec error`, e);
1741
- responseError(res, 500 /* HttpStatus.InternalServerError */, exports.GMError.InternalError, e instanceof Error ? e.message : String(e));
1742
- }
1743
- };
1532
+ verifyConfigWithoutEndpoint(config);
1533
+ verifyStoreHelper(storeHelper);
1534
+ return async function(req, res, rawBodyString) {
1535
+ if (req.method !== "POST") {
1536
+ responseError(res, HttpStatus.MethodNotAllowed, GMError.InvalidHttpMethod, `Expecting POST, got ${req.method}`);
1537
+ return;
1538
+ }
1539
+ const contentType = `${req.headers["Content-Type"] || req.headers["content-type"]}`.toLowerCase();
1540
+ if (!contentType || !contentType.startsWith("application/json")) {
1541
+ responseError(res, HttpStatus.UnsupportedMediaType, GMError.InvalidContentType, `Expecting application/json, got ${contentType}`);
1542
+ return;
1543
+ }
1544
+ const authString = req.headers["Authorization"] || req.headers["Authorization".toLowerCase()];
1545
+ const body = await readBody(req, rawBodyString);
1546
+ if (!body || !checkHttpAuthInfo(`${authString}`, {
1547
+ game: config.game,
1548
+ secret: config.secret,
1549
+ method: "POST",
1550
+ endpoint: `http://${req.headers.host}`,
1551
+ url: req.url || "",
1552
+ data: body
1553
+ })) {
1554
+ responseError(res, HttpStatus.Unauthorized, GMError.InvalidSignature, "Signature failed");
1555
+ return;
1556
+ }
1557
+ const gmRequest = parseJSON(body, isGMRequestBody);
1558
+ if (!gmRequest) {
1559
+ responseError(res, HttpStatus.BadRequest, GMError.InvalidRequest, `GM request body format error`);
1560
+ return;
1561
+ }
1562
+ const currentRecord = {
1563
+ nonce: genNonceString(),
1564
+ key: gmRequest.idempotency_key || "",
1565
+ id: gmRequest.request_id,
1566
+ cmd: gmRequest.command,
1567
+ args: toString(gmRequest.args)
1568
+ };
1569
+ let oldResponse = null;
1570
+ if (storeHelper && gmRequest.idempotency_key) {
1571
+ const oldRecordStr = await storeHelper.setNX(gmRequest.idempotency_key, toString(currentRecord)).catch((e) => e instanceof Error ? e : new Error(String(e)));
1572
+ if (oldRecordStr instanceof Error) {
1573
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) setNX error`, oldRecordStr);
1574
+ responseError(res, HttpStatus.InternalServerError, GMError.InternalError, oldRecordStr.message);
1575
+ return;
1576
+ }
1577
+ const oldRecord = oldRecordStr ? parseJSON(oldRecordStr, isIdempotencyRecord) : null;
1578
+ if (!oldRecord && oldRecordStr) {
1579
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) parse old idempotency record failed: ${oldRecordStr}`);
1580
+ responseError(res, HttpStatus.InternalServerError, GMError.InternalError, "parse old idempotency record failed");
1581
+ return;
1582
+ }
1583
+ if (oldRecord && "noce" in oldRecord) oldRecord.nonce = oldRecord.noce + "";
1584
+ if (!(oldRecordStr === "" || (oldRecord === null || oldRecord === void 0 ? void 0 : oldRecord.nonce) === currentRecord.nonce) && oldRecord) {
1585
+ if (!oldRecord.resp) {
1586
+ responseError(res, error2httpStatus[GMError.IdempotencyConflict], GMError.IdempotencyConflict, "previous request is not completed");
1587
+ return;
1588
+ }
1589
+ if (oldRecord.cmd !== gmRequest.command) {
1590
+ responseError(res, error2httpStatus[GMError.IdempotencyMismatch], GMError.IdempotencyMismatch, `cmd mismatch, expecting ${oldRecord.cmd}, got ${gmRequest.command}`);
1591
+ return;
1592
+ }
1593
+ if (oldRecord.args !== currentRecord.args) {
1594
+ responseError(res, error2httpStatus[GMError.IdempotencyMismatch], GMError.IdempotencyMismatch, `args mismatch, expecting ${oldRecord.args}, got ${currentRecord.args}`);
1595
+ return;
1596
+ }
1597
+ oldResponse = oldRecord.resp;
1598
+ }
1599
+ }
1600
+ try {
1601
+ const result = oldResponse || await handler(gmRequest.command, gmRequest.args, gmRequest.request_id, gmRequest.idempotency_key || "", gmRequest.version, gmRequest.origin || "");
1602
+ if (storeHelper && gmRequest.idempotency_key) {
1603
+ currentRecord.resp = result;
1604
+ storeHelper.setXX(gmRequest.idempotency_key, toString(currentRecord)).catch((err) => {
1605
+ console.error("failed to setXX idempotency record", err, currentRecord);
1606
+ });
1607
+ }
1608
+ if (result instanceof Error) {
1609
+ responseError(res, HttpStatus.InternalServerError, GMError.InternalError, result.message);
1610
+ return;
1611
+ }
1612
+ if (isGMErrorResponse(result)) {
1613
+ responseError(res, error2httpStatus[result.error] || HttpStatus.InternalServerError, result.error || GMError.InternalError, result.message);
1614
+ return;
1615
+ }
1616
+ if (typeof result === "string" && result in error2httpStatus) {
1617
+ responseError(res, error2httpStatus[result], result, result);
1618
+ return;
1619
+ }
1620
+ if (!result) console.warn(`gm command "${gmRequest.command}" should give back some data`);
1621
+ responseJson(res, result !== null && result !== void 0 ? result : {});
1622
+ } catch (e) {
1623
+ console.error(`gm command "${gmRequest.command}"(requestId: ${gmRequest.request_id}; idempotencyKey: ${gmRequest.idempotency_key || ""}) exec error`, e);
1624
+ responseError(res, HttpStatus.InternalServerError, GMError.InternalError, e instanceof Error ? e.message : String(e));
1625
+ }
1626
+ };
1744
1627
  }
1745
1628
  /**
1746
- * 获取基于 express 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1747
- *
1748
- * 如需自定义处理,可以使用 getGMCommandHandler 方法,
1749
- *
1750
- * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1751
- *
1752
- * 处理方法可以参考
1753
- *
1754
- * https://cloud.tencent.com/developer/ask/sof/110062928
1755
- */
1629
+ * 获取基于 express 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1630
+ *
1631
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法,
1632
+ *
1633
+ * 如果 express 使用全局的 bodyParse 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1634
+ *
1635
+ * 处理方法可以参考
1636
+ *
1637
+ * https://cloud.tencent.com/developer/ask/sof/110062928
1638
+ */
1756
1639
  function getGMHandlerForExpress(config, handler, storeHelper) {
1757
- const func = getGMCommandHandler(config, handler, storeHelper);
1758
- return async function (req, res) {
1759
- await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1760
- };
1640
+ const func = getGMCommandHandler(config, handler, storeHelper);
1641
+ return async function(req, res) {
1642
+ await func(req, res, "rawBody" in req ? `${req.rawBody}` : "");
1643
+ };
1761
1644
  }
1762
1645
  /**
1763
- * 获取基于 express 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1764
- *
1765
- * 需要先于 body-parse 等类似插件加载
1766
- */
1646
+ * 获取基于 express 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1647
+ *
1648
+ * 需要先于 body-parse 等类似插件加载
1649
+ */
1767
1650
  function getGMMiddlewareForExpress(paths, config, handler, storeHelper) {
1768
- const func = getGMCommandHandler(config, handler, storeHelper);
1769
- const matchPaths = Array.isArray(paths) ? paths : [paths];
1770
- return async function (req, res, next) {
1771
- if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1772
- await func(req, res);
1773
- return;
1774
- }
1775
- next();
1776
- };
1651
+ const func = getGMCommandHandler(config, handler, storeHelper);
1652
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1653
+ return async function(req, res, next) {
1654
+ if (req.method.toUpperCase() === "POST" && matchPaths.includes(req.path)) {
1655
+ await func(req, res);
1656
+ return;
1657
+ }
1658
+ next();
1659
+ };
1777
1660
  }
1778
1661
  /**
1779
- * 获取基于 koa2 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1780
- *
1781
- * 如需自定义处理,可以使用 getGMCommandHandler 方法
1782
- *
1783
- * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1784
- */
1662
+ * 获取基于 koa2 的处理函数用于响应 Seayoo Server 推送过来的 GM 执行通知
1663
+ *
1664
+ * 如需自定义处理,可以使用 getGMCommandHandler 方法
1665
+ *
1666
+ * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
1667
+ */
1785
1668
  function getGMHandlerForKoa(config, handler, storeHelper) {
1786
- const func = getGMCommandHandler(config, handler, storeHelper);
1787
- return async function (ctx) {
1788
- await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1789
- };
1669
+ const func = getGMCommandHandler(config, handler, storeHelper);
1670
+ return async function(ctx) {
1671
+ await func(ctx.req, ctx.res, "rawBody" in ctx ? `${ctx.rawBody}` : "");
1672
+ };
1790
1673
  }
1791
1674
  /**
1792
- * 获取基于 koa2 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1793
- *
1794
- * 需要先于 koa-body 等类似插件加载
1795
- */
1675
+ * 获取基于 koa2 的中间件用于响应 Seayoo Server 推送过来的 GM 执行通知
1676
+ *
1677
+ * 需要先于 koa-body 等类似插件加载
1678
+ */
1796
1679
  function getGMMiddlewareForKoa(paths, config, handler, storeHelper) {
1797
- const func = getGMCommandHandler(config, handler, storeHelper);
1798
- const matchPaths = Array.isArray(paths) ? paths : [paths];
1799
- return async function (ctx, next) {
1800
- if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1801
- await func(ctx.req, ctx.res);
1802
- return;
1803
- }
1804
- await next();
1805
- };
1806
- }
1807
-
1680
+ const func = getGMCommandHandler(config, handler, storeHelper);
1681
+ const matchPaths = Array.isArray(paths) ? paths : [paths];
1682
+ return async function(ctx, next) {
1683
+ if (ctx.method.toUpperCase() === "POST" && matchPaths.includes(ctx.path)) {
1684
+ await func(ctx.req, ctx.res);
1685
+ return;
1686
+ }
1687
+ await next();
1688
+ };
1689
+ }
1690
+ //#endregion
1808
1691
  exports.ApiClient = ApiClient;
1692
+ exports.Endpoint = Endpoint;
1693
+ exports.GMError = GMError;
1694
+ exports.IdP = IdP;
1809
1695
  exports.MemoryIdempotencyStore = MemoryIdempotencyStore;
1696
+ exports.NotificationType = NotificationType;
1697
+ exports.Platform = Platform;
1810
1698
  exports.RedisIdempotencyStore = RedisIdempotencyStore;
1811
1699
  exports.TokenVerifier = TokenVerifier;
1812
1700
  exports.calcAuthorizationHeader = calcAuthorizationHeader;