koishi-plugin-rina-currency 0.0.3 → 0.0.4

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/lib/index.js CHANGED
@@ -403,11 +403,35 @@ function extendModel(ctx) {
403
403
  __name(extendModel, "extendModel");
404
404
 
405
405
  // src/providers/common.ts
406
+ var import_node_http = require("node:http");
406
407
  var BOC_SOURCE_URL = "https://www.boc.cn/sourcedb/whpj/index.html";
407
408
  var ICBC_SOURCE_URL = "http://papi.icbc.com.cn/exchanges/ns/getLatest";
408
- async function fetchText(url, timeoutMs, init = {}, retry = { attempts: 1, retryDelay: 0 }) {
409
+ function describeError(error) {
410
+ if (!(error instanceof Error)) return String(error);
411
+ const details = [`${error.name}: ${error.message}`];
412
+ const code = error.code;
413
+ if (code) details.push(`code=${code}`);
414
+ if (error.cause && error.cause !== error) details.push(`cause=${describeError(error.cause)}`);
415
+ return details.join(", ");
416
+ }
417
+ __name(describeError, "describeError");
418
+ async function withRetries(url, retry, operation) {
409
419
  let lastError;
410
420
  for (let attempt = 1; attempt <= retry.attempts; attempt++) {
421
+ try {
422
+ return await operation();
423
+ } catch (error) {
424
+ lastError = error;
425
+ }
426
+ if (attempt < retry.attempts) {
427
+ await new Promise((resolve) => setTimeout(resolve, retry.retryDelay * attempt));
428
+ }
429
+ }
430
+ throw new Error(`请求 ${url} 失败,已尝试 ${retry.attempts} 次:${describeError(lastError)}`);
431
+ }
432
+ __name(withRetries, "withRetries");
433
+ async function fetchText(url, timeoutMs, init = {}, retry = { attempts: 1, retryDelay: 0 }) {
434
+ return withRetries(url, retry, async () => {
411
435
  const controller = new AbortController();
412
436
  const timer = setTimeout(() => controller.abort(), timeoutMs);
413
437
  try {
@@ -416,19 +440,49 @@ async function fetchText(url, timeoutMs, init = {}, retry = { attempts: 1, retry
416
440
  throw new Error(`${response.status} ${response.statusText}`);
417
441
  }
418
442
  return await response.text();
419
- } catch (error) {
420
- lastError = error;
421
443
  } finally {
422
444
  clearTimeout(timer);
423
445
  }
424
- if (attempt < retry.attempts) {
425
- await new Promise((resolve) => setTimeout(resolve, retry.retryDelay * attempt));
426
- }
427
- }
428
- const reason = lastError instanceof Error ? `${lastError.name}: ${lastError.message}` : String(lastError);
429
- throw new Error(`请求 ${url} 失败,已尝试 ${retry.attempts} 次:${reason}`);
446
+ });
430
447
  }
431
448
  __name(fetchText, "fetchText");
449
+ function postJsonText(url, timeoutMs, retry, body = "{}") {
450
+ return withRetries(url, retry, () => new Promise((resolve, reject) => {
451
+ const endpoint = new URL(url);
452
+ const request = (0, import_node_http.request)({
453
+ protocol: endpoint.protocol,
454
+ hostname: endpoint.hostname,
455
+ port: endpoint.port || void 0,
456
+ method: "POST",
457
+ path: `${endpoint.pathname}${endpoint.search}`,
458
+ agent: false,
459
+ headers: {
460
+ "content-type": "application/json",
461
+ "content-length": Buffer.byteLength(body),
462
+ "connection": "close",
463
+ "user-agent": "koishi-plugin-rina-currency/0.1"
464
+ }
465
+ }, (response) => {
466
+ let responseBody = "";
467
+ response.setEncoding("utf8");
468
+ response.on("data", (chunk) => {
469
+ responseBody += chunk;
470
+ });
471
+ response.on("error", reject);
472
+ response.on("end", () => {
473
+ if (response.statusCode == null || response.statusCode < 200 || response.statusCode >= 300) {
474
+ reject(new Error(`${response.statusCode || 0} ${response.statusMessage || ""}`.trim()));
475
+ return;
476
+ }
477
+ resolve(responseBody);
478
+ });
479
+ });
480
+ request.setTimeout(timeoutMs, () => request.destroy(new Error(`请求超时(${timeoutMs}ms)`)));
481
+ request.on("error", reject);
482
+ request.end(body);
483
+ }));
484
+ }
485
+ __name(postJsonText, "postJsonText");
432
486
  function asRate(value, field) {
433
487
  const parsed = Number.parseFloat(String(value).trim());
434
488
  if (!Number.isFinite(parsed) || parsed <= 0) {
@@ -524,14 +578,10 @@ var IcbcProvider = class {
524
578
  }
525
579
  id = "icbc";
526
580
  async fetch() {
527
- const body = await fetchText(ICBC_SOURCE_URL, this.timeoutMs, {
528
- method: "POST",
529
- headers: {
530
- "content-type": "application/json",
531
- "user-agent": "koishi-plugin-rina-currency/0.1"
532
- },
533
- body: "{}"
534
- }, { attempts: this.attempts, retryDelay: this.retryDelay });
581
+ const body = await postJsonText(ICBC_SOURCE_URL, this.timeoutMs, {
582
+ attempts: this.attempts,
583
+ retryDelay: this.retryDelay
584
+ });
535
585
  return parseIcbcJpy(JSON.parse(body));
536
586
  }
537
587
  };
@@ -10,5 +10,11 @@ export interface RetryOptions {
10
10
  retryDelay: number;
11
11
  }
12
12
  export declare function fetchText(url: string, timeoutMs: number, init?: RequestInit, retry?: RetryOptions): Promise<string>;
13
+ /**
14
+ * ICBC's legacy public endpoint is plain HTTP. Keep this request on a fresh
15
+ * Node socket instead of the process-wide fetch pool, which can retain a
16
+ * connection that the upstream has already closed.
17
+ */
18
+ export declare function postJsonText(url: string, timeoutMs: number, retry: RetryOptions, body?: string): Promise<string>;
13
19
  export declare function asRate(value: unknown, field: string): number;
14
20
  export declare function chinaTime(date: string, time?: string): Date;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-rina-currency",
3
3
  "description": "面向购汇决策的日元汇率插件,基于中行和工行数据",
4
- "version": "0.0.3",
4
+ "version": "0.0.4",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [