@seayoo-io/combo-sdk-node 0.1.3 → 0.1.7

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/README.md CHANGED
@@ -40,12 +40,12 @@ import { ApiClient, Endpoint } from "@seayoo-io/combo-sdk-node"
40
40
  const client = new ApiClient({
41
41
  game: "<GameId>",
42
42
  secret: "<SecretKey>",
43
- endpoint: Endpoint.China
43
+ endpoint: Endpoint.China,
44
44
  // 以下参数可选
45
- maxRetry: 1, // 失败后自动重试次数,默认 1
46
- retryInterval: 100 // 重试间隔,默认是 100,单位 ms,可以传递函数动态设置间隔
47
- logger: function(log) {} // 请求日志函数,log 类型参见源码类型定义
48
- timeout: 5000, // 超时等待时长,单位 ms,默认 5000
45
+ maxRetry: 1, // 失败后自动重试次数,默认 1
46
+ retryInterval: 1000, // 重试间隔,默认是 1000,单位 ms,可以传递函数动态设置间隔
47
+ logger: function(log) {}, // 请求日志函数,log 类型参见源码类型定义
48
+ timeout: 5000, // 超时等待时长,单位 ms,默认 5000
49
49
  })
50
50
  ```
51
51
 
package/dist/const.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** SDK 名称 */
2
2
  export declare const SDKName = "combo-sdk-node";
3
3
  /** SDK 版本,在编译前会被动态替换 */
4
- export declare const SDKVersion = "0.1.3";
4
+ export declare const SDKVersion = "0.1.7";
5
5
  /**
6
6
  * 世游支持的服务端点列表
7
7
  */
package/dist/index.cjs CHANGED
@@ -1,34 +1,18 @@
1
- var node_os = require('node:os');
2
- var http = require('node:http');
3
- var https = require('node:https');
1
+ var os = require('os');
2
+ var http = require('http');
3
+ var https = require('https');
4
4
  var crypto = require('crypto');
5
5
  var jsonwebtoken = require('jsonwebtoken');
6
6
 
7
- function _interopNamespace(e) {
8
- if (e && e.__esModule) return e;
9
- var n = Object.create(null);
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- if (k !== 'default') {
13
- var d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: function () { return e[k]; }
17
- });
18
- }
19
- });
20
- }
21
- n["default"] = e;
22
- return n;
23
- }
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
24
8
 
25
- var http__namespace = /*#__PURE__*/_interopNamespace(http);
26
- var https__namespace = /*#__PURE__*/_interopNamespace(https);
9
+ var http__default = /*#__PURE__*/_interopDefaultLegacy(http);
10
+ var https__default = /*#__PURE__*/_interopDefaultLegacy(https);
27
11
 
28
12
  /** SDK 名称 */
29
13
  const SDKName = "combo-sdk-node";
30
14
  /** SDK 版本,在编译前会被动态替换 */
31
- const SDKVersion = "0.1.3";
15
+ const SDKVersion = "0.1.7";
32
16
  /**
33
17
  * 世游支持的服务端点列表
34
18
  */
@@ -73,7 +57,7 @@ exports.IdP = void 0;
73
57
  })(exports.IdP || (exports.IdP = {}));
74
58
 
75
59
  function getUserAgent(game) {
76
- return `${SDKName}/${SDKVersion} game/${game} node/${process.version} os/${node_os.platform()} arch/${node_os.arch()}`;
60
+ return `${SDKName}/${SDKVersion} game/${game} node/${process.version} os/${os.platform()} arch/${os.arch()}`;
77
61
  }
78
62
 
79
63
  const urlReg = /^(?:https?:)?\/\/.+/i;
@@ -137,7 +121,24 @@ function getFullURL(url, baseURL = "") {
137
121
  * @param url 要检查的 url,如果是自适应协议 //... 则会添加当前页面的协议信息,否则添加域名和协议信息
138
122
  */
139
123
  function fillUrl(url) {
140
- return isFullURL(url, true) ? url.startsWith("http") ? url : location.protocol + url : location.origin + "/" + url.replace(/^\/+/, "");
124
+ if (isFullURL(url, true)) {
125
+ if (url.startsWith("http")) {
126
+ return url;
127
+ }
128
+ return ("location" in globalThis ? location.protocol : "https:") + url;
129
+ }
130
+ return ("location" in globalThis ? location.origin + "/" : "http://127.0.0.1/") + url.replace(/^\/+/, "");
131
+ }
132
+ /**
133
+ * 简版 Object.fromEntries
134
+ */
135
+ function fromEntries(kv) {
136
+ return kv.reduce((result, [key, value]) => {
137
+ if (key) {
138
+ result[key] = value || "";
139
+ }
140
+ return result;
141
+ }, {});
141
142
  }
142
143
  function parseJSON(str, typeGuard) {
143
144
  try {
@@ -172,7 +173,7 @@ function verifyConfig(config) {
172
173
  throw Error("Config Missing");
173
174
  }
174
175
  if (!isFullURL(config.endpoint)) {
175
- throw Error(`Config.endpoint Error, Should be url, Preset Values: ${"https://api.seayoo.com" /* Endpoint.China */}, ${"https://api.seayoo.io" /* Endpoint.Global */}}`);
176
+ throw Error(`Config.endpoint Error, Should be url, Preset Values: ${exports.Endpoint.China}, ${exports.Endpoint.Global}}`);
176
177
  }
177
178
  if (!config.game) {
178
179
  throw Error(`Config.game Error, Missing Required GameId`);
@@ -303,7 +304,7 @@ function parseRawAuthHeader(authString, prefix) {
303
304
  if (!authString || !authString.startsWith(prefix + " ")) {
304
305
  return null;
305
306
  }
306
- return Object.fromEntries(authString.substring(prefix.length + 1).split(",").map(kvs => {
307
+ return fromEntries(authString.substring(prefix.length + 1).split(",").map(kvs => {
307
308
  const kv = kvs.split("=");
308
309
  if (kv.length !== 2) {
309
310
  return null;
@@ -550,7 +551,7 @@ function handleResponse(res, url, config, options) {
550
551
  const result = {
551
552
  ...analyseResponse(res.status, res.statusText, res.body, config.get("responseRule"), options == null ? void 0 : options.responseRule),
552
553
  status: res.status,
553
- headers: Object.fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
554
+ headers: fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
554
555
  };
555
556
  // 全局处理响应结果 (浅复制,防止被修改,同时保留修改 result.data 的可能性)
556
557
  (_config$get2 = config.get("responseHandler")) == null || _config$get2({
@@ -663,7 +664,7 @@ const coreNodeRequest = async function (url, config, options) {
663
664
  body: ""
664
665
  };
665
666
  }
666
- const client = /^https:\/\//i.test(opt.url) ? https__namespace : http__namespace;
667
+ const client = /^https:\/\//i.test(opt.url) ? https__default["default"] : http__default["default"];
667
668
  const iURL = new URL(opt.url);
668
669
  const params = opt.params;
669
670
  if (params instanceof Object) {
@@ -671,7 +672,7 @@ const coreNodeRequest = async function (url, config, options) {
671
672
  }
672
673
  const isHeadRequest = opt.method === "HEAD";
673
674
  return new Promise(resolve => {
674
- const req = client.request(iURL, {
675
+ const req = client.request(iURL.toString(), {
675
676
  headers: opt.headers,
676
677
  method: opt.method,
677
678
  timeout: opt.timeout > 0 ? opt.timeout : undefined
@@ -679,7 +680,7 @@ const coreNodeRequest = async function (url, config, options) {
679
680
  const resbody = [];
680
681
  res.on("data", chunk => resbody.push(chunk));
681
682
  res.on("end", () => {
682
- const headers = Object.fromEntries(Object.entries(res.headers).map(([key, value]) => {
683
+ const headers = fromEntries(Object.entries(res.headers).map(([key, value]) => {
683
684
  return [key.toLowerCase(), Array.isArray(value) ? value.join(",") : value];
684
685
  }));
685
686
  resolve({
@@ -908,6 +909,7 @@ function NetRequest(config) {
908
909
  }
909
910
 
910
911
  const ApiPrefix = "/v1/server";
912
+ const TraceIdField = "x-trace-id";
911
913
  /**
912
914
  * Combo SDK For Server REST Api
913
915
  */
@@ -955,7 +957,7 @@ class ApiClient {
955
957
  });
956
958
  },
957
959
  logHandler: config.logger,
958
- timeout: config.timeout
960
+ timeout: config.timeout || 5000
959
961
  });
960
962
  }
961
963
  /**
@@ -965,8 +967,15 @@ class ApiClient {
965
967
  if (!option.combo_id || !option.notify_url || !option.product_id || !option.reference_id) {
966
968
  throw new Error("createOrder: 必要参数缺失");
967
969
  }
970
+ // 检查通知回调地址
971
+ if (!isFullURL(option.notify_url)) {
972
+ throw new Error("createOrder: notify_url 需要是一个完整的 url 地址");
973
+ }
968
974
  // 检查购买数量
969
- option.quantity = Math.min(Math.max(1, Math.ceil(option.quantity)), Number.MAX_SAFE_INTEGER);
975
+ const quantity = Math.min(Math.max(1, Math.ceil(option.quantity)), Number.MAX_SAFE_INTEGER);
976
+ if (quantity !== option.quantity) {
977
+ throw new Error("createOrder: 购买数量 quantity 必须是一个有限的正整数,且不能小于 1");
978
+ }
970
979
  const {
971
980
  ok,
972
981
  data,
@@ -981,7 +990,7 @@ class ApiClient {
981
990
  status,
982
991
  code,
983
992
  message,
984
- traceId: headers["x-trace-id"]
993
+ traceId: headers[TraceIdField]
985
994
  });
986
995
  throw new Error(`createOrder: ${message || code || status}`);
987
996
  }
@@ -1015,7 +1024,7 @@ class ApiClient {
1015
1024
  status,
1016
1025
  code,
1017
1026
  message,
1018
- traceId: headers["x-trace-id"]
1027
+ traceId: headers[TraceIdField]
1019
1028
  });
1020
1029
  }
1021
1030
  return ok;
@@ -1048,7 +1057,7 @@ class ApiClient {
1048
1057
  status,
1049
1058
  code,
1050
1059
  message,
1051
- traceId: headers["x-trace-id"]
1060
+ traceId: headers[TraceIdField]
1052
1061
  });
1053
1062
  }
1054
1063
  return ok;
@@ -1107,7 +1116,7 @@ class TokenVerifier {
1107
1116
  idp: payload.idp,
1108
1117
  external_id: payload.external_id,
1109
1118
  external_name: payload.external_name,
1110
- weixin_unionid: payload.weixin_unionid
1119
+ weixin_unionid: payload.weixin_unionid || ""
1111
1120
  };
1112
1121
  } catch (error) {
1113
1122
  return new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
@@ -1163,7 +1172,7 @@ function isNotificationRequestBody(data) {
1163
1172
  *
1164
1173
  * 另有 express 和 koa2 版本的处理函数可以使用。
1165
1174
  *
1166
- * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以用以签名
1175
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1167
1176
  */
1168
1177
  function getNotificationHandler(config, handler) {
1169
1178
  verifyConfig(config);
@@ -1280,13 +1289,14 @@ function getNotificationMiddlewareForKoa(paths, config, handler) {
1280
1289
  await func(ctx.req, ctx.res);
1281
1290
  return;
1282
1291
  }
1283
- next();
1292
+ await next();
1284
1293
  };
1285
1294
  }
1286
1295
 
1287
1296
  exports.ApiClient = ApiClient;
1288
1297
  exports.TokenVerifier = TokenVerifier;
1289
1298
  exports.calcAuthorizationHeader = calcAuthorizationHeader;
1299
+ exports.checkHttpAuthInfo = checkHttpAuthInfo;
1290
1300
  exports.getNotificationHandler = getNotificationHandler;
1291
1301
  exports.getNotificationHandlerForExpress = getNotificationHandlerForExpress;
1292
1302
  exports.getNotificationHandlerForKoa = getNotificationHandlerForKoa;
package/dist/index.d.ts CHANGED
@@ -8,5 +8,5 @@ export { getNotificationHandler, getNotificationHandlerForExpress, getNotificati
8
8
  export { NotificationType } from "./notify/types";
9
9
  export type { NotificationHandler } from "./notify/types";
10
10
  export type { SDKBaseConfig } from "./utils";
11
- export { parseAuthorizationHeader, calcAuthorizationHeader } from "./utils";
12
11
  export { Endpoint, Platform, IdP } from "./const";
12
+ export { parseAuthorizationHeader, calcAuthorizationHeader, checkHttpAuthInfo } from "./utils";
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { platform, arch } from 'node:os';
2
- import * as http from 'node:http';
3
- import * as https from 'node:https';
1
+ import { platform, arch } from 'os';
2
+ import http from 'http';
3
+ import https from 'https';
4
4
  import { createHash, createHmac } from 'crypto';
5
5
  import { verify } from 'jsonwebtoken';
6
6
 
7
7
  /** SDK 名称 */
8
8
  const SDKName = "combo-sdk-node";
9
9
  /** SDK 版本,在编译前会被动态替换 */
10
- const SDKVersion = "0.1.3";
10
+ const SDKVersion = "0.1.7";
11
11
  /**
12
12
  * 世游支持的服务端点列表
13
13
  */
@@ -116,7 +116,24 @@ function getFullURL(url, baseURL = "") {
116
116
  * @param url 要检查的 url,如果是自适应协议 //... 则会添加当前页面的协议信息,否则添加域名和协议信息
117
117
  */
118
118
  function fillUrl(url) {
119
- return isFullURL(url, true) ? url.startsWith("http") ? url : location.protocol + url : location.origin + "/" + url.replace(/^\/+/, "");
119
+ if (isFullURL(url, true)) {
120
+ if (url.startsWith("http")) {
121
+ return url;
122
+ }
123
+ return ("location" in globalThis ? location.protocol : "https:") + url;
124
+ }
125
+ return ("location" in globalThis ? location.origin + "/" : "http://127.0.0.1/") + url.replace(/^\/+/, "");
126
+ }
127
+ /**
128
+ * 简版 Object.fromEntries
129
+ */
130
+ function fromEntries(kv) {
131
+ return kv.reduce((result, [key, value]) => {
132
+ if (key) {
133
+ result[key] = value || "";
134
+ }
135
+ return result;
136
+ }, {});
120
137
  }
121
138
  function parseJSON(str, typeGuard) {
122
139
  try {
@@ -151,7 +168,7 @@ function verifyConfig(config) {
151
168
  throw Error("Config Missing");
152
169
  }
153
170
  if (!isFullURL(config.endpoint)) {
154
- throw Error(`Config.endpoint Error, Should be url, Preset Values: ${"https://api.seayoo.com" /* Endpoint.China */}, ${"https://api.seayoo.io" /* Endpoint.Global */}}`);
171
+ throw Error(`Config.endpoint Error, Should be url, Preset Values: ${Endpoint.China}, ${Endpoint.Global}}`);
155
172
  }
156
173
  if (!config.game) {
157
174
  throw Error(`Config.game Error, Missing Required GameId`);
@@ -282,7 +299,7 @@ function parseRawAuthHeader(authString, prefix) {
282
299
  if (!authString || !authString.startsWith(prefix + " ")) {
283
300
  return null;
284
301
  }
285
- return Object.fromEntries(authString.substring(prefix.length + 1).split(",").map(kvs => {
302
+ return fromEntries(authString.substring(prefix.length + 1).split(",").map(kvs => {
286
303
  const kv = kvs.split("=");
287
304
  if (kv.length !== 2) {
288
305
  return null;
@@ -529,7 +546,7 @@ function handleResponse(res, url, config, options) {
529
546
  const result = {
530
547
  ...analyseResponse(res.status, res.statusText, res.body, config.get("responseRule"), options == null ? void 0 : options.responseRule),
531
548
  status: res.status,
532
- headers: Object.fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
549
+ headers: fromEntries(Object.entries(res.headers || {}).map(([key, value]) => [key.toLowerCase(), value]))
533
550
  };
534
551
  // 全局处理响应结果 (浅复制,防止被修改,同时保留修改 result.data 的可能性)
535
552
  (_config$get2 = config.get("responseHandler")) == null || _config$get2({
@@ -650,7 +667,7 @@ const coreNodeRequest = async function (url, config, options) {
650
667
  }
651
668
  const isHeadRequest = opt.method === "HEAD";
652
669
  return new Promise(resolve => {
653
- const req = client.request(iURL, {
670
+ const req = client.request(iURL.toString(), {
654
671
  headers: opt.headers,
655
672
  method: opt.method,
656
673
  timeout: opt.timeout > 0 ? opt.timeout : undefined
@@ -658,7 +675,7 @@ const coreNodeRequest = async function (url, config, options) {
658
675
  const resbody = [];
659
676
  res.on("data", chunk => resbody.push(chunk));
660
677
  res.on("end", () => {
661
- const headers = Object.fromEntries(Object.entries(res.headers).map(([key, value]) => {
678
+ const headers = fromEntries(Object.entries(res.headers).map(([key, value]) => {
662
679
  return [key.toLowerCase(), Array.isArray(value) ? value.join(",") : value];
663
680
  }));
664
681
  resolve({
@@ -887,6 +904,7 @@ function NetRequest(config) {
887
904
  }
888
905
 
889
906
  const ApiPrefix = "/v1/server";
907
+ const TraceIdField = "x-trace-id";
890
908
  /**
891
909
  * Combo SDK For Server REST Api
892
910
  */
@@ -934,7 +952,7 @@ class ApiClient {
934
952
  });
935
953
  },
936
954
  logHandler: config.logger,
937
- timeout: config.timeout
955
+ timeout: config.timeout || 5000
938
956
  });
939
957
  }
940
958
  /**
@@ -944,8 +962,15 @@ class ApiClient {
944
962
  if (!option.combo_id || !option.notify_url || !option.product_id || !option.reference_id) {
945
963
  throw new Error("createOrder: 必要参数缺失");
946
964
  }
965
+ // 检查通知回调地址
966
+ if (!isFullURL(option.notify_url)) {
967
+ throw new Error("createOrder: notify_url 需要是一个完整的 url 地址");
968
+ }
947
969
  // 检查购买数量
948
- option.quantity = Math.min(Math.max(1, Math.ceil(option.quantity)), Number.MAX_SAFE_INTEGER);
970
+ const quantity = Math.min(Math.max(1, Math.ceil(option.quantity)), Number.MAX_SAFE_INTEGER);
971
+ if (quantity !== option.quantity) {
972
+ throw new Error("createOrder: 购买数量 quantity 必须是一个有限的正整数,且不能小于 1");
973
+ }
949
974
  const {
950
975
  ok,
951
976
  data,
@@ -960,7 +985,7 @@ class ApiClient {
960
985
  status,
961
986
  code,
962
987
  message,
963
- traceId: headers["x-trace-id"]
988
+ traceId: headers[TraceIdField]
964
989
  });
965
990
  throw new Error(`createOrder: ${message || code || status}`);
966
991
  }
@@ -994,7 +1019,7 @@ class ApiClient {
994
1019
  status,
995
1020
  code,
996
1021
  message,
997
- traceId: headers["x-trace-id"]
1022
+ traceId: headers[TraceIdField]
998
1023
  });
999
1024
  }
1000
1025
  return ok;
@@ -1027,7 +1052,7 @@ class ApiClient {
1027
1052
  status,
1028
1053
  code,
1029
1054
  message,
1030
- traceId: headers["x-trace-id"]
1055
+ traceId: headers[TraceIdField]
1031
1056
  });
1032
1057
  }
1033
1058
  return ok;
@@ -1086,7 +1111,7 @@ class TokenVerifier {
1086
1111
  idp: payload.idp,
1087
1112
  external_id: payload.external_id,
1088
1113
  external_name: payload.external_name,
1089
- weixin_unionid: payload.weixin_unionid
1114
+ weixin_unionid: payload.weixin_unionid || ""
1090
1115
  };
1091
1116
  } catch (error) {
1092
1117
  return new Error(`IdentityToken 验证失败: ${error instanceof Error ? error.message : String(error)}`);
@@ -1142,7 +1167,7 @@ function isNotificationRequestBody(data) {
1142
1167
  *
1143
1168
  * 另有 express 和 koa2 版本的处理函数可以使用。
1144
1169
  *
1145
- * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以用以签名
1170
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
1146
1171
  */
1147
1172
  function getNotificationHandler(config, handler) {
1148
1173
  verifyConfig(config);
@@ -1259,8 +1284,8 @@ function getNotificationMiddlewareForKoa(paths, config, handler) {
1259
1284
  await func(ctx.req, ctx.res);
1260
1285
  return;
1261
1286
  }
1262
- next();
1287
+ await next();
1263
1288
  };
1264
1289
  }
1265
1290
 
1266
- export { ApiClient, Endpoint, IdP, Platform, TokenVerifier, calcAuthorizationHeader, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
1291
+ export { ApiClient, Endpoint, IdP, Platform, TokenVerifier, calcAuthorizationHeader, checkHttpAuthInfo, getNotificationHandler, getNotificationHandlerForExpress, getNotificationHandlerForKoa, getNotificationMiddlewareForExpress, getNotificationMiddlewareForKoa, parseAuthorizationHeader };
@@ -1,15 +1,14 @@
1
- /// <reference types="node" />
2
1
  import { type SDKBaseConfig } from "../utils";
3
2
  import { type NotificationHandler } from "./types";
4
3
  import type { ParameterizedContext, Next } from "koa";
5
- import type { IncomingMessage, ServerResponse } from "node:http";
4
+ import type { IncomingMessage, ServerResponse } from "http";
6
5
  import type { Request as ExpressRequest, Response as ExpressResponse, NextFunction as ExpressNextFunction } from "express";
7
6
  /**
8
7
  * 获取一个处理函数用于接收 Seayoo Server 推送过来的消息通知
9
8
  *
10
9
  * 另有 express 和 koa2 版本的处理函数可以使用。
11
10
  *
12
- * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以用以签名
11
+ * 由于签名需要原始请求的内容,如果 request 在函数执行之前已经被读取,则需要手工传入请求的 rawBody 字符串以核验签名
13
12
  */
14
13
  export declare function getNotificationHandler(config: SDKBaseConfig, handler: NotificationHandler): (req: IncomingMessage, res: ServerResponse, rawBodyString?: string) => Promise<void>;
15
14
  /**
@@ -23,13 +22,15 @@ export declare function getNotificationHandler(config: SDKBaseConfig, handler: N
23
22
  *
24
23
  * https://cloud.tencent.com/developer/ask/sof/110062928
25
24
  */
26
- export declare function getNotificationHandlerForExpress(config: SDKBaseConfig, handler: NotificationHandler): (req: ExpressRequest, res: ExpressResponse) => Promise<void>;
25
+ export declare function getNotificationHandlerForExpress(config: SDKBaseConfig, handler: NotificationHandler): (req: ExpressRequest & {
26
+ rawBody?: string;
27
+ }, res: ExpressResponse) => Promise<void>;
27
28
  /**
28
29
  * 获取基于 express 的中间件用于接收 Seayoo Server 推送过来的消息通知
29
30
  *
30
31
  * 需要先于 body-parse 等类似插件加载
31
32
  */
32
- export declare function getNotificationMiddlewareForExpress(paths: string | string[], config: SDKBaseConfig, handler: NotificationHandler): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => Promise<void>;
33
+ export declare function getNotificationMiddlewareForExpress(paths: string | string[], config: SDKBaseConfig, handler: NotificationHandler): (req: ExpressRequest, res: ServerResponse, next: ExpressNextFunction) => Promise<void>;
33
34
  /**
34
35
  * 获取基于 koa2 的处理函数用于接收 Seayoo Server 推送过来的消息通知
35
36
  *
@@ -37,10 +38,12 @@ export declare function getNotificationMiddlewareForExpress(paths: string | stri
37
38
  *
38
39
  * 如果 koa 使用全局的 koa-body 或类似插件,将需要做额外的处理以获取原始请求的内容 rawBody 以用以计算签名
39
40
  */
40
- export declare function getNotificationHandlerForKoa(config: SDKBaseConfig, handler: NotificationHandler): (ctx: ParameterizedContext) => Promise<void>;
41
+ export declare function getNotificationHandlerForKoa(config: SDKBaseConfig, handler: NotificationHandler): (ctx: Pick<ParameterizedContext, "req" | "res"> & {
42
+ rawBody?: string;
43
+ }) => Promise<void>;
41
44
  /**
42
45
  * 获取基于 koa2 的中间件用于接收 Seayoo Server 推送过来的消息通知
43
46
  *
44
47
  * 需要先于 koa-body 等类似插件加载
45
48
  */
46
- export declare function getNotificationMiddlewareForKoa(paths: string | string[], config: SDKBaseConfig, handler: NotificationHandler): (ctx: ParameterizedContext, next: Next) => Promise<void>;
49
+ export declare function getNotificationMiddlewareForKoa(paths: string | string[], config: SDKBaseConfig, handler: NotificationHandler): (ctx: Pick<ParameterizedContext, "method" | "path" | "req" | "res">, next: Next) => Promise<void>;
@@ -1,4 +1,4 @@
1
- import type { TypeGuardParam, IRequestOptions, IRequestGlobalConfig, NetRequestAgent, ResponseWithType, ResponseWithoutType } from "./type";
1
+ import type { TypeGuardParam, IRequestOptions, IRequestGlobalConfig, IResponseResult, NetRequestAgent } from "./type";
2
2
  type RequestBody = NonNullable<IRequestOptions["body"]>;
3
3
  /** 工具函数主类 */
4
4
  export declare class NetRequestHandler {
@@ -25,36 +25,36 @@ export declare class NetRequestHandler {
25
25
  /**
26
26
  * 发送一个 HEAD 请求,并且不处理响应 body
27
27
  */
28
- head(url: string, options?: IRequestOptions): ResponseWithoutType;
28
+ head(url: string, options?: IRequestOptions): Promise<IResponseResult>;
29
29
  /**
30
30
  * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景
31
31
  */
32
- get(url: string): ResponseWithoutType;
33
- get(url: string, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
34
- get<T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
32
+ get(url: string): Promise<IResponseResult>;
33
+ get(url: string, typeGard: null, options?: IRequestOptions): Promise<IResponseResult>;
34
+ get<T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): Promise<IResponseResult<T | null>>;
35
35
  /**
36
36
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
37
37
  */
38
- post(url: string, data: RequestBody): ResponseWithoutType;
39
- post(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
40
- post<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
38
+ post(url: string, data: RequestBody): Promise<IResponseResult>;
39
+ post(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): Promise<IResponseResult>;
40
+ post<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): Promise<IResponseResult<T | null>>;
41
41
  /**
42
42
  * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
43
43
  */
44
- del(url: string): ResponseWithoutType;
45
- del(url: string, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
46
- del<T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
44
+ del(url: string): Promise<IResponseResult>;
45
+ del(url: string, typeGard: null, options?: IRequestOptions): Promise<IResponseResult>;
46
+ del<T>(url: string, typeGard: TypeGuardParam<T>, options?: IRequestOptions): Promise<IResponseResult<T | null>>;
47
47
  /**
48
48
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
49
49
  */
50
- put(url: string, data: RequestBody): ResponseWithoutType;
51
- put(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
52
- put<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
50
+ put(url: string, data: RequestBody): Promise<IResponseResult>;
51
+ put(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): Promise<IResponseResult>;
52
+ put<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): Promise<IResponseResult<T | null>>;
53
53
  /**
54
54
  * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
55
55
  */
56
- patch(url: string, data: RequestBody): ResponseWithoutType;
57
- patch(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): ResponseWithoutType;
58
- patch<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): ResponseWithType<T>;
56
+ patch(url: string, data: RequestBody): Promise<IResponseResult>;
57
+ patch(url: string, data: RequestBody, typeGard: null, options?: IRequestOptions): Promise<IResponseResult>;
58
+ patch<T>(url: string, data: RequestBody, typeGard: TypeGuardParam<T>, options?: IRequestOptions): Promise<IResponseResult<T | null>>;
59
59
  }
60
60
  export {};
@@ -1,3 +1,3 @@
1
- import { NetRequestCoreFn, IRequestOptions } from "./type";
1
+ import { NetRequestCoreFn, IRequestOptions, IRequestBaseResponse } from "./type";
2
2
  import type { RequestGlobalConfig } from "./config";
3
- export declare function retryRequest(agent: NetRequestCoreFn, url: string, config: RequestGlobalConfig, options?: IRequestOptions, _try?: number): ReturnType<NetRequestCoreFn>;
3
+ export declare function retryRequest(agent: NetRequestCoreFn, url: string, config: RequestGlobalConfig, options?: IRequestOptions, _try?: number): Promise<IRequestBaseResponse>;
@@ -34,6 +34,10 @@ export declare function isJsonLike(text: string): boolean;
34
34
  * @param baseURL 可选 baseURL
35
35
  */
36
36
  export declare function getFullURL(url: string, baseURL?: string): string;
37
+ /**
38
+ * 简版 Object.fromEntries
39
+ */
40
+ export declare function fromEntries(kv: [string, string | undefined][]): Record<string, string>;
37
41
  /**
38
42
  * JSON.parse的扩展,格式化错误则返回 null,第二个参数为可选 typeGuard
39
43
  */
@@ -1,4 +1,4 @@
1
1
  /// <reference types="node" />
2
- import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { IncomingMessage, ServerResponse } from "http";
3
3
  export declare function readBody(req: IncomingMessage, backup?: string): Promise<string>;
4
4
  export declare function done(res: ServerResponse, statusCode: number, message?: string): Promise<void>;
@@ -35,7 +35,7 @@ export interface IdentityPayload {
35
35
  *
36
36
  * 注意:weixin_unionid 只在 IdP 为 weixin 时才会有值。
37
37
  */
38
- weixin_unionid?: string;
38
+ weixin_unionid: string;
39
39
  }
40
40
  export type IdentityJwtPayload = JwtPayload & Omit<IdentityPayload, "combo_id"> & {
41
41
  scope: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-io/combo-sdk-node",
3
- "version": "0.1.3",
3
+ "version": "0.1.7",
4
4
  "description": "Combo SDK for Node.js",
5
5
  "type": "module",
6
6
  "source": "./src/index.ts",
@@ -27,7 +27,7 @@
27
27
  "pub": "pnpm type-check && pnpm lint:fix && vitest run && pnpm build && npm publish"
28
28
  },
29
29
  "engines": {
30
- "node": ">=14.0.0"
30
+ "node": ">=12"
31
31
  },
32
32
  "simple-git-hooks": {
33
33
  "pre-commit": "pnpm lint && pnpm type-check"
@@ -44,19 +44,20 @@
44
44
  "@types/express": "^4.17.21",
45
45
  "@types/jsonwebtoken": "^9.0.5",
46
46
  "@types/koa": "^2.13.12",
47
- "@types/node": "^20.10.6",
48
- "@typescript-eslint/eslint-plugin": "^6.17.0",
49
- "@typescript-eslint/parser": "^6.17.0",
47
+ "@types/node": "12.0.0",
48
+ "@typescript-eslint/eslint-plugin": "^6.18.1",
49
+ "@typescript-eslint/parser": "^6.18.1",
50
50
  "eslint": "^8.56.0",
51
51
  "eslint-config-prettier": "^9.1.0",
52
52
  "eslint-plugin-prettier": "^5.1.2",
53
53
  "lint-staged": "^15.2.0",
54
54
  "microbundle": "^0.15.1",
55
+ "msw": "^2.0.12",
55
56
  "rimraf": "^5.0.5",
56
57
  "simple-git-hooks": "^2.9.0",
57
- "typescript": "^5.3.3",
58
- "vite": "^5.0.10",
59
- "vitest": "^1.1.1"
58
+ "typescript": "5.2.2",
59
+ "vite": "^3.2.7",
60
+ "vitest": "^0.34.6"
60
61
  },
61
62
  "dependencies": {
62
63
  "jsonwebtoken": "^9.0.2"
package/vitest.config.ts CHANGED
@@ -2,6 +2,7 @@ import { defineConfig } from "vitest/config"
2
2
 
3
3
  export default defineConfig({
4
4
  test: {
5
+ environment: "node",
5
6
  onConsoleLog(log: string, type: "stdout" | "stderr"): false | void {
6
7
  if (type === "stderr") return false
7
8
  },