@secret-momo/utils 1.8.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +215 -6
  3. package/dist/date-time.js +23 -0
  4. package/{lib → dist}/download/aria2.d.ts +5 -4
  5. package/dist/download/aria2.js +134 -0
  6. package/{lib → dist}/download/extension.d.ts +1 -0
  7. package/dist/download/extension.js +96 -0
  8. package/{lib → dist}/download/index.d.ts +6 -6
  9. package/dist/download/index.js +94 -0
  10. package/dist/download/types.js +1 -0
  11. package/dist/env.d.ts +9 -0
  12. package/dist/env.js +76 -0
  13. package/dist/fetch.d.ts +33 -0
  14. package/dist/fetch.js +174 -0
  15. package/dist/file.js +14 -0
  16. package/dist/index.d.ts +12 -0
  17. package/dist/index.js +12 -0
  18. package/{lib → dist}/mihomo/cache.d.ts +2 -2
  19. package/dist/mihomo/cache.js +6 -0
  20. package/dist/mihomo/client.d.ts +22 -0
  21. package/dist/mihomo/client.js +80 -0
  22. package/{lib → dist}/mihomo/configs.d.ts +2 -2
  23. package/dist/mihomo/configs.js +13 -0
  24. package/{lib → dist}/mihomo/connections.d.ts +5 -3
  25. package/dist/mihomo/connections.js +8 -0
  26. package/{lib → dist}/mihomo/debug.d.ts +3 -3
  27. package/dist/mihomo/debug.js +6 -0
  28. package/{lib → dist}/mihomo/dns.d.ts +2 -2
  29. package/dist/mihomo/dns.js +5 -0
  30. package/{lib → dist}/mihomo/groups.d.ts +2 -2
  31. package/dist/mihomo/groups.js +11 -0
  32. package/dist/mihomo/index.d.ts +39 -0
  33. package/dist/mihomo/index.js +40 -0
  34. package/{lib → dist}/mihomo/logs.d.ts +2 -2
  35. package/dist/mihomo/logs.js +8 -0
  36. package/{lib → dist}/mihomo/memory.d.ts +2 -2
  37. package/dist/mihomo/memory.js +3 -0
  38. package/{lib → dist}/mihomo/proxies.d.ts +2 -2
  39. package/dist/mihomo/proxies.js +17 -0
  40. package/{lib → dist}/mihomo/proxy-providers.d.ts +2 -2
  41. package/dist/mihomo/proxy-providers.js +15 -0
  42. package/{lib → dist}/mihomo/rule-providers.d.ts +2 -2
  43. package/dist/mihomo/rule-providers.js +7 -0
  44. package/{lib → dist}/mihomo/rules.d.ts +2 -2
  45. package/dist/mihomo/rules.js +6 -0
  46. package/{lib → dist}/mihomo/storage.d.ts +2 -2
  47. package/dist/mihomo/storage.js +9 -0
  48. package/{lib → dist}/mihomo/traffic.d.ts +2 -2
  49. package/dist/mihomo/traffic.js +3 -0
  50. package/{lib → dist}/mihomo/types.d.ts +5 -4
  51. package/dist/mihomo/types.js +1 -0
  52. package/{lib → dist}/mihomo/upgrade.d.ts +2 -2
  53. package/dist/mihomo/upgrade.js +11 -0
  54. package/{lib → dist}/mihomo/version.d.ts +2 -2
  55. package/dist/mihomo/version.js +3 -0
  56. package/{lib → dist}/num.d.ts +2 -0
  57. package/dist/num.js +19 -0
  58. package/dist/pino.js +13 -0
  59. package/dist/public-ip.js +19 -0
  60. package/dist/sleep.d.ts +3 -0
  61. package/dist/sleep.js +21 -0
  62. package/{lib → dist}/url.d.ts +1 -1
  63. package/dist/url.js +29 -0
  64. package/{lib → dist}/uuid.d.ts +1 -0
  65. package/dist/uuid.js +16 -0
  66. package/package.json +35 -50
  67. package/lib/date-time.js +0 -1
  68. package/lib/download/aria2.js +0 -1
  69. package/lib/download/extension.js +0 -1
  70. package/lib/download/index.js +0 -1
  71. package/lib/env.d.ts +0 -9
  72. package/lib/env.js +0 -1
  73. package/lib/fetch.d.ts +0 -13
  74. package/lib/fetch.js +0 -1
  75. package/lib/file.js +0 -1
  76. package/lib/index.d.ts +0 -12
  77. package/lib/index.js +0 -1
  78. package/lib/mihomo/cache.js +0 -1
  79. package/lib/mihomo/client.d.ts +0 -25
  80. package/lib/mihomo/client.js +0 -1
  81. package/lib/mihomo/configs.js +0 -1
  82. package/lib/mihomo/connections.js +0 -1
  83. package/lib/mihomo/debug.js +0 -1
  84. package/lib/mihomo/dns.js +0 -1
  85. package/lib/mihomo/groups.js +0 -1
  86. package/lib/mihomo/index.d.ts +0 -39
  87. package/lib/mihomo/index.js +0 -1
  88. package/lib/mihomo/logs.js +0 -1
  89. package/lib/mihomo/memory.js +0 -1
  90. package/lib/mihomo/proxies.js +0 -1
  91. package/lib/mihomo/proxy-providers.js +0 -1
  92. package/lib/mihomo/rule-providers.js +0 -1
  93. package/lib/mihomo/rules.js +0 -1
  94. package/lib/mihomo/storage.js +0 -1
  95. package/lib/mihomo/traffic.js +0 -1
  96. package/lib/mihomo/upgrade.js +0 -1
  97. package/lib/mihomo/version.js +0 -1
  98. package/lib/num.js +0 -1
  99. package/lib/pino.js +0 -1
  100. package/lib/public-ip.js +0 -1
  101. package/lib/sleep.d.ts +0 -2
  102. package/lib/sleep.js +0 -1
  103. package/lib/url.js +0 -1
  104. package/lib/uuid.js +0 -1
  105. /package/{lib → dist}/date-time.d.ts +0 -0
  106. /package/{lib → dist}/download/types.d.ts +0 -0
  107. /package/{lib → dist}/file.d.ts +0 -0
  108. /package/{lib → dist}/pino.d.ts +0 -0
  109. /package/{lib → dist}/public-ip.d.ts +0 -0
package/dist/env.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 从指定目录开始向上查找仓库根目录。
3
+ *
4
+ * 返回最近的项目/工作区根目录,嵌套项目的锁文件也视为根标记。
5
+ * 支持 Git、pnpm/Bun 标记,以及声明了 workspaces 的 package.json。
6
+ */
7
+ export declare function findRepoRoot(from: string): string;
8
+ /** 首次调用同步探测 macOS 硬件,随后复用缓存结果(含探测失败)。 */
9
+ export declare function getNodeName(): string;
package/dist/env.js ADDED
@@ -0,0 +1,76 @@
1
+ import { execSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ const REPO_MARKERS = ['.git', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'bun.lock'];
5
+ /**
6
+ * 从指定目录开始向上查找仓库根目录。
7
+ *
8
+ * 返回最近的项目/工作区根目录,嵌套项目的锁文件也视为根标记。
9
+ * 支持 Git、pnpm/Bun 标记,以及声明了 workspaces 的 package.json。
10
+ */
11
+ export function findRepoRoot(from) {
12
+ let current = resolve(from);
13
+ while (true) {
14
+ if (REPO_MARKERS.some((marker) => existsSync(join(current, marker)))) {
15
+ return current;
16
+ }
17
+ const packageJsonPath = join(current, 'package.json');
18
+ if (existsSync(packageJsonPath)) {
19
+ try {
20
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8').replace(/^\uFEFF/, ''));
21
+ if (packageJson &&
22
+ typeof packageJson === 'object' &&
23
+ 'workspaces' in packageJson &&
24
+ packageJson.workspaces) {
25
+ return current;
26
+ }
27
+ }
28
+ catch {
29
+ // 元数据无效或不可读时继续向上查找。
30
+ }
31
+ }
32
+ const parent = dirname(current);
33
+ if (parent === current) {
34
+ break;
35
+ }
36
+ current = parent;
37
+ }
38
+ throw new Error(`未找到仓库根目录(缺少 ${REPO_MARKERS.join(' / ')} / 含 workspaces 的 package.json)`);
39
+ }
40
+ let macHardwareInfo = null;
41
+ /**
42
+ * 获取 macOS 硬件信息(基于 system_profiler)
43
+ */
44
+ function getMacHardwareInfo() {
45
+ if (macHardwareInfo) {
46
+ return macHardwareInfo;
47
+ }
48
+ try {
49
+ const output = execSync('system_profiler SPHardwareDataType', {
50
+ encoding: 'utf-8',
51
+ stdio: ['pipe', 'pipe', 'ignore'],
52
+ });
53
+ const getValue = (key) => {
54
+ const regex = new RegExp(`${key}:\\s+(.+)`);
55
+ const match = output.match(regex);
56
+ return match?.[1]?.trim() ?? null;
57
+ };
58
+ macHardwareInfo = {
59
+ modelName: getValue('Model Name'),
60
+ chip: getValue('Chip') || getValue('Processor Name'), // 兼容 Intel
61
+ };
62
+ return macHardwareInfo;
63
+ }
64
+ catch (_e) {
65
+ macHardwareInfo = {
66
+ modelName: null,
67
+ chip: null,
68
+ };
69
+ return macHardwareInfo;
70
+ }
71
+ }
72
+ /** 首次调用同步探测 macOS 硬件,随后复用缓存结果(含探测失败)。 */
73
+ export function getNodeName() {
74
+ const { modelName, chip } = getMacHardwareInfo();
75
+ return `${modelName}(${chip})`;
76
+ }
@@ -0,0 +1,33 @@
1
+ export interface FetchRequestInit extends RequestInit {
2
+ /** 默认仅重试幂等方法;true 表示调用方已提供幂等键或其他去重保障,false 禁用重试。 */
3
+ retry?: boolean;
4
+ }
5
+ export declare const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
6
+ export declare const mobileUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1";
7
+ /**
8
+ * 对 `globalThis.fetch` 的轻量封装:
9
+ * - 默认仅重试幂等方法;非幂等请求需调用方提供去重保障并显式设置 retry: true。
10
+ * - 最多重试 5 次,总尝试次数为 6;retry: false 可关闭重试。
11
+ * - 仅在获取响应头前发生的可重试异常(如超时、连接重置、网络错误)时重试。
12
+ * - 响应体由调用方消费,读取失败不会自动重试。
13
+ * - 允许重试且使用 Request 自带的 body 时,每次尝试使用新克隆。重放大请求体可能增加内存缓冲。
14
+ * - init.body 的一次性流不自动重试,即使设置了 retry: true。
15
+ * - 重试间隔采用指数退避:`2^attempt` 秒,即 `1s, 2s, 4s, 8s, 16s`。
16
+ * - 有效请求信号(优先使用 `init.signal`,否则使用 `Request.signal`)也会中止退避等待。
17
+ */
18
+ export declare function fetch(input: string | URL | Request, init?: FetchRequestInit): Promise<Response>;
19
+ /**
20
+ * 获取响应并读取文本。
21
+ * 仅重试获取响应头之前的可重试网络错误;响应体读取或解析失败直接抛出,不重试。
22
+ */
23
+ export declare function fetchText(input: string | URL | Request, init?: FetchRequestInit): Promise<string>;
24
+ /**
25
+ * 补齐 HTML 请求头并读取文本。
26
+ * 仅重试获取响应头之前的可重试网络错误;响应体读取或解析失败直接抛出,不重试。
27
+ */
28
+ export declare function fetchHtml(input: string | URL | Request, init?: FetchRequestInit): Promise<string>;
29
+ /**
30
+ * 补齐 JSON 请求头并解析 JSON。
31
+ * 仅重试获取响应头之前的可重试网络错误;响应体读取或解析失败直接抛出,不重试。
32
+ */
33
+ export declare function fetchJson(input: string | URL | Request, init?: FetchRequestInit): Promise<unknown>;
package/dist/fetch.js ADDED
@@ -0,0 +1,174 @@
1
+ import { logger } from './pino.js';
2
+ import { sleep } from './sleep.js';
3
+ const MAX_RETRIES = 5;
4
+ const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE']);
5
+ const RETRYABLE_NETWORK_CODES = new Set([
6
+ 'EAI_AGAIN',
7
+ 'ECONNRESET',
8
+ 'ECONNREFUSED',
9
+ 'ETIMEDOUT',
10
+ 'UND_ERR_SOCKET',
11
+ 'UND_ERR_CONNECT_TIMEOUT',
12
+ 'UND_ERR_HEADERS_TIMEOUT',
13
+ 'UND_ERR_BODY_TIMEOUT',
14
+ ]);
15
+ export const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
16
+ export const mobileUserAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1';
17
+ function requestUrl(input) {
18
+ return input instanceof Request ? input.url : input.toString();
19
+ }
20
+ function withDefaultHeaders(input, init, defaults) {
21
+ // 显式 init.headers 替换 Request.headers,与原生 fetch 语义一致。
22
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
23
+ new Headers(defaults).forEach((value, name) => {
24
+ if (!headers.has(name))
25
+ headers.set(name, value);
26
+ });
27
+ return { ...init, headers };
28
+ }
29
+ function originFromUrl(url) {
30
+ try {
31
+ const parsed = new URL(url);
32
+ return parsed.origin;
33
+ }
34
+ catch {
35
+ return url;
36
+ }
37
+ }
38
+ function refererFromUrl(url) {
39
+ return originFromUrl(url) + '/';
40
+ }
41
+ function formatErrorSummary(error) {
42
+ const err = error;
43
+ const name = err?.name ?? 'Error';
44
+ const code = err?.cause?.code ? ` [code=${String(err.cause.code)}]` : '';
45
+ // 错误消息也可能携带完整 URL,日志仅保留异常名和结构化错误码。
46
+ return `${name}${code}`;
47
+ }
48
+ function logUrl(url) {
49
+ try {
50
+ const parsed = new URL(url);
51
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:'
52
+ ? `${parsed.origin}${parsed.pathname}`
53
+ : '[非 HTTP URL]';
54
+ }
55
+ catch {
56
+ return '[无效 URL]';
57
+ }
58
+ }
59
+ function isStreamBody(body) {
60
+ return (body != null &&
61
+ typeof body === 'object' &&
62
+ ('getReader' in body || Symbol.asyncIterator in body));
63
+ }
64
+ function isRetryableError(error, signal) {
65
+ if (signal?.aborted) {
66
+ return false;
67
+ }
68
+ const err = error;
69
+ // 有根因码时以它为准,避免把永久 TLS/证书错误当作网络超时。
70
+ const code = err?.cause?.code ?? err?.code;
71
+ if (typeof code === 'string')
72
+ return RETRYABLE_NETWORK_CODES.has(code.toUpperCase());
73
+ const message = (err?.message ?? String(error)).toLowerCase();
74
+ if (/certificate|unknown cert|\b(?:ssl|tls)\b/.test(message))
75
+ return false;
76
+ const isNetworkLikeMessage = [
77
+ 'network',
78
+ 'socket',
79
+ 'econnreset',
80
+ 'econnrefused',
81
+ 'etimedout',
82
+ 'eai_again',
83
+ 'timeout',
84
+ 'failed to fetch',
85
+ 'unable to connect',
86
+ ].some((m) => message.includes(m));
87
+ return err?.name === 'TimeoutError' || err?.name === 'AbortError' || isNetworkLikeMessage;
88
+ }
89
+ /**
90
+ * 对 `globalThis.fetch` 的轻量封装:
91
+ * - 默认仅重试幂等方法;非幂等请求需调用方提供去重保障并显式设置 retry: true。
92
+ * - 最多重试 5 次,总尝试次数为 6;retry: false 可关闭重试。
93
+ * - 仅在获取响应头前发生的可重试异常(如超时、连接重置、网络错误)时重试。
94
+ * - 响应体由调用方消费,读取失败不会自动重试。
95
+ * - 允许重试且使用 Request 自带的 body 时,每次尝试使用新克隆。重放大请求体可能增加内存缓冲。
96
+ * - init.body 的一次性流不自动重试,即使设置了 retry: true。
97
+ * - 重试间隔采用指数退避:`2^attempt` 秒,即 `1s, 2s, 4s, 8s, 16s`。
98
+ * - 有效请求信号(优先使用 `init.signal`,否则使用 `Request.signal`)也会中止退避等待。
99
+ */
100
+ export async function fetch(input, init) {
101
+ const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
102
+ const allowRetry = (init?.retry ?? IDEMPOTENT_METHODS.has(method)) && !isStreamBody(init?.body);
103
+ const originalSignal = init?.signal !== undefined
104
+ ? (init.signal ?? undefined)
105
+ : input instanceof Request
106
+ ? input.signal
107
+ : undefined;
108
+ const url = requestUrl(input);
109
+ const { retry: _retry, ...requestInit } = withDefaultHeaders(input, init, {
110
+ 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
111
+ Referer: refererFromUrl(url),
112
+ 'User-Agent': userAgent,
113
+ });
114
+ const cloneRequest = allowRetry && input instanceof Request && input.body !== null && requestInit.body == null;
115
+ for (let attempt = 0;; attempt++) {
116
+ try {
117
+ const attemptInput = cloneRequest ? input.clone() : input;
118
+ return await globalThis.fetch(attemptInput, requestInit);
119
+ }
120
+ catch (error) {
121
+ const shouldRetry = allowRetry && attempt < MAX_RETRIES && isRetryableError(error, originalSignal);
122
+ if (!shouldRetry) {
123
+ throw error;
124
+ }
125
+ const totalAttempts = MAX_RETRIES + 1;
126
+ const currentAttempt = attempt + 1;
127
+ const seconds = Math.pow(2, attempt);
128
+ const remainingRetries = MAX_RETRIES - attempt - 1;
129
+ logger.warn(`请求失败,第 ${currentAttempt}/${totalAttempts} 次尝试,${seconds}s 后重试(剩余 ${remainingRetries} 次):${logUrl(url)};错误:${formatErrorSummary(error)}`);
130
+ await sleep(1000 * seconds, originalSignal);
131
+ }
132
+ }
133
+ }
134
+ /**
135
+ * 获取响应并读取文本。
136
+ * 仅重试获取响应头之前的可重试网络错误;响应体读取或解析失败直接抛出,不重试。
137
+ */
138
+ export async function fetchText(input, init) {
139
+ return (await fetch(input, init)).text();
140
+ }
141
+ /**
142
+ * 补齐 HTML 请求头并读取文本。
143
+ * 仅重试获取响应头之前的可重试网络错误;响应体读取或解析失败直接抛出,不重试。
144
+ */
145
+ export async function fetchHtml(input, init) {
146
+ init = withDefaultHeaders(input, init, {
147
+ Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
148
+ 'Cache-Control': 'no-cache',
149
+ 'Content-Type': 'text/html',
150
+ Pragma: 'no-cache',
151
+ 'Upgrade-Insecure-Requests': '1',
152
+ 'Sec-Fetch-Site': 'none',
153
+ 'Sec-Fetch-Mode': 'navigate',
154
+ 'Sec-Fetch-User': '?1',
155
+ 'Sec-Fetch-Dest': 'document',
156
+ });
157
+ return await fetchText(input, init);
158
+ }
159
+ /**
160
+ * 补齐 JSON 请求头并解析 JSON。
161
+ * 仅重试获取响应头之前的可重试网络错误;响应体读取或解析失败直接抛出,不重试。
162
+ */
163
+ export async function fetchJson(input, init) {
164
+ init = withDefaultHeaders(input, init, {
165
+ Accept: 'application/json, text/plain, */*',
166
+ Connection: 'keep-alive',
167
+ 'Content-Type': 'application/json',
168
+ Origin: originFromUrl(requestUrl(input)),
169
+ 'Sec-Fetch-Site': 'same-site',
170
+ 'Sec-Fetch-Mode': 'cors',
171
+ 'Sec-Fetch-Dest': 'empty',
172
+ });
173
+ return (await fetch(input, init)).json();
174
+ }
package/dist/file.js ADDED
@@ -0,0 +1,14 @@
1
+ import { stat } from 'node:fs/promises';
2
+ const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
3
+ function formatFileSize(bytes) {
4
+ if (bytes < 1024) {
5
+ return `${bytes}B`;
6
+ }
7
+ const unitIndex = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), UNITS.length - 1);
8
+ const size = bytes / 1024 ** unitIndex;
9
+ return `${size.toFixed(2)}${UNITS[unitIndex]}`;
10
+ }
11
+ export async function fileSize(filePath) {
12
+ const { size } = await stat(filePath);
13
+ return formatFileSize(size);
14
+ }
@@ -0,0 +1,12 @@
1
+ export * from './download/index.js';
2
+ export * from './date-time.js';
3
+ export * from './env.js';
4
+ export * from './fetch.js';
5
+ export * from './file.js';
6
+ export * from './num.js';
7
+ export * from './pino.js';
8
+ export * from './public-ip.js';
9
+ export * from './sleep.js';
10
+ export * from './uuid.js';
11
+ export * from './url.js';
12
+ export * from './mihomo/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export * from './download/index.js';
2
+ export * from './date-time.js';
3
+ export * from './env.js';
4
+ export * from './fetch.js';
5
+ export * from './file.js';
6
+ export * from './num.js';
7
+ export * from './pino.js';
8
+ export * from './public-ip.js';
9
+ export * from './sleep.js';
10
+ export * from './uuid.js';
11
+ export * from './url.js';
12
+ export * from './mihomo/index.js';
@@ -1,5 +1,5 @@
1
- import type { MihomoClient } from './client';
2
- import type { MihomoRequestOptions } from './types';
1
+ import type { MihomoClient } from './client.js';
2
+ import type { MihomoRequestOptions } from './types.js';
3
3
  export interface MihomoCacheModule {
4
4
  /** POST `/cache/fakeip/flush`:清除 fake-ip 缓存,成功时返回 HTTP 204。 */
5
5
  flushFakeIp(options?: MihomoRequestOptions): Promise<void>;
@@ -0,0 +1,6 @@
1
+ export function createCache(client) {
2
+ return {
3
+ flushFakeIp: (options) => client.empty('POST', '/cache/fakeip/flush', options),
4
+ flushDns: (options) => client.empty('POST', '/cache/dns/flush', options),
5
+ };
6
+ }
@@ -0,0 +1,22 @@
1
+ import type { MihomoOptions, MihomoRequestOptions } from './types.js';
2
+ type RequestOptions = MihomoRequestOptions & {
3
+ body?: unknown;
4
+ query?: Record<string, string | number | boolean | undefined>;
5
+ };
6
+ export declare class MihomoHttpError extends Error {
7
+ readonly response: Response;
8
+ readonly body: string;
9
+ constructor(response: Response, body: string, options?: ErrorOptions);
10
+ }
11
+ export declare class MihomoClient {
12
+ private readonly baseUrl;
13
+ private readonly basePath;
14
+ private readonly secret?;
15
+ constructor(options: MihomoOptions);
16
+ url(path: string, query?: Record<string, string | number | boolean | undefined>): string;
17
+ response(method: string, path: string, options?: RequestOptions): Promise<Response>;
18
+ json<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
19
+ empty(method: string, path: string, options?: RequestOptions): Promise<void>;
20
+ }
21
+ export declare function encodePathSegment(value: string): string;
22
+ export {};
@@ -0,0 +1,80 @@
1
+ export class MihomoHttpError extends Error {
2
+ response;
3
+ body;
4
+ constructor(response, body, options) {
5
+ super(`Mihomo request failed: ${response.status} ${response.statusText}`, options);
6
+ this.response = response;
7
+ this.body = body;
8
+ this.name = 'MihomoHttpError';
9
+ }
10
+ }
11
+ export class MihomoClient {
12
+ baseUrl;
13
+ basePath;
14
+ secret;
15
+ constructor(options) {
16
+ const parsed = new URL(options.baseUrl?.toString() ?? 'http://127.0.0.1:9090');
17
+ parsed.search = '';
18
+ parsed.hash = '';
19
+ const url = parsed.toString().replace(/\/+$/, '');
20
+ this.baseUrl = url;
21
+ this.basePath = parsed.pathname.replace(/\/+$/, '');
22
+ this.secret = options.secret;
23
+ }
24
+ url(path, query) {
25
+ const pathname = path.split(/[?#]/, 1)[0] ?? '';
26
+ // URL 解析会移除制表符和换行,并将点号段规范化。
27
+ const route = pathname.replace(/[\t\n\r]/g, '');
28
+ if (!pathname.startsWith('/') ||
29
+ route.includes('\\') ||
30
+ /\/(?:\.|%2e){1,2}(?:\/|$)/i.test(route.trimEnd())) {
31
+ throw new TypeError('Mihomo 请求路径必须以 / 开头,且不能包含点号导航段或反斜杠');
32
+ }
33
+ const url = new URL(`${this.baseUrl}${path}`);
34
+ if (url.pathname !== this.basePath && !url.pathname.startsWith(`${this.basePath}/`)) {
35
+ throw new TypeError('Mihomo 请求路径超出了 baseUrl 的路径前缀');
36
+ }
37
+ for (const [key, value] of Object.entries(query ?? {})) {
38
+ if (value !== undefined)
39
+ url.searchParams.set(key, String(value));
40
+ }
41
+ return url.toString();
42
+ }
43
+ async response(method, path, options = {}) {
44
+ const headers = new Headers(options.headers);
45
+ if (this.secret && !headers.has('Authorization')) {
46
+ headers.set('Authorization', `Bearer ${this.secret}`);
47
+ }
48
+ let body;
49
+ if (options.body !== undefined) {
50
+ body = JSON.stringify(options.body);
51
+ if (!headers.has('Content-Type'))
52
+ headers.set('Content-Type', 'application/json');
53
+ }
54
+ const response = await globalThis.fetch(this.url(path, options.query), {
55
+ method,
56
+ headers,
57
+ body,
58
+ signal: options.signal ?? undefined,
59
+ });
60
+ if (!response.ok) {
61
+ const body = await response.text().catch((cause) => {
62
+ throw new MihomoHttpError(response, '', { cause });
63
+ });
64
+ throw new MihomoHttpError(response, body);
65
+ }
66
+ return response;
67
+ }
68
+ async json(method, path, options) {
69
+ return (await this.response(method, path, options)).json();
70
+ }
71
+ async empty(method, path, options) {
72
+ await this.response(method, path, options);
73
+ }
74
+ }
75
+ export function encodePathSegment(value) {
76
+ if (value === '.' || value === '..') {
77
+ throw new TypeError('路径参数不能是独立的 . 或 .. 段');
78
+ }
79
+ return encodeURIComponent(value);
80
+ }
@@ -1,5 +1,5 @@
1
- import type { MihomoClient } from './client';
2
- import type { MihomoMode, MihomoPathPayload, MihomoRequestOptions } from './types';
1
+ import type { MihomoClient } from './client.js';
2
+ import type { MihomoMode, MihomoPathPayload, MihomoRequestOptions } from './types.js';
3
3
  export interface MihomoConfig {
4
4
  port?: number;
5
5
  'socks-port'?: number;
@@ -0,0 +1,13 @@
1
+ export function createConfigs(client) {
2
+ return {
3
+ get: (options) => client.json('GET', '/configs', options),
4
+ reload: (payload, options = {}) => client.empty('PUT', '/configs', {
5
+ ...options,
6
+ body: payload,
7
+ query: { force: options.force },
8
+ }),
9
+ patch: (config, options) => client.empty('PATCH', '/configs', { ...options, body: config }),
10
+ updateGeo: (payload, options) => client.empty('POST', '/configs/geo', { ...options, body: payload }),
11
+ restart: (payload, options) => client.empty('POST', '/restart', { ...options, body: payload }),
12
+ };
13
+ }
@@ -1,7 +1,9 @@
1
- import { type MihomoClient } from './client';
2
- import type { MihomoConnections, MihomoRequestOptions } from './types';
1
+ import { type MihomoClient } from './client.js';
2
+ import type { MihomoConnections, MihomoRequestOptions } from './types.js';
3
3
  export interface MihomoConnectionsModule {
4
- /** GET `/connections`:获取累计流量、内存使用量及活跃连接;可用 `interval` 指定 WS 刷新间隔。 */
4
+ /** GET `/connections`:获取累计流量、内存使用量及活跃连接的单次快照。
5
+ * interval 仅为兼容保留并转发,不会让 HTTP 快照自动刷新;本方法不建立 WebSocket。
6
+ */
5
7
  list(options?: MihomoRequestOptions & {
6
8
  interval?: number;
7
9
  }): Promise<MihomoConnections>;
@@ -0,0 +1,8 @@
1
+ import { encodePathSegment } from './client.js';
2
+ export function createConnections(client) {
3
+ return {
4
+ list: (options = {}) => client.json('GET', '/connections', { ...options, query: { interval: options.interval } }),
5
+ closeAll: (options) => client.empty('DELETE', '/connections', options),
6
+ close: (id, options) => client.empty('DELETE', `/connections/${encodePathSegment(id)}`, options),
7
+ };
8
+ }
@@ -1,9 +1,9 @@
1
- import type { MihomoClient } from './client';
2
- import type { MihomoRequestOptions } from './types';
1
+ import type { MihomoClient } from './client.js';
2
+ import type { MihomoRequestOptions } from './types.js';
3
3
  export interface MihomoDebugModule {
4
4
  /** PUT `/debug/gc`:主动触发 Go GC;仅在内核日志级别为 `debug` 时可用。 */
5
5
  gc(options?: MihomoRequestOptions): Promise<void>;
6
- /** 返回 `/debug/pprof` 的完整 URL,可在浏览器中打开查看原始 pprof 调试信息。 */
6
+ /** 返回 `/debug/pprof` 的完整 URL;URL 不携带认证头,直接浏览器访问需另行满足 controller 的认证要求。 */
7
7
  pprofUrl(): string;
8
8
  }
9
9
  export declare function createDebug(client: MihomoClient): MihomoDebugModule;
@@ -0,0 +1,6 @@
1
+ export function createDebug(client) {
2
+ return {
3
+ gc: (options) => client.empty('PUT', '/debug/gc', options),
4
+ pprofUrl: () => client.url('/debug/pprof'),
5
+ };
6
+ }
@@ -1,5 +1,5 @@
1
- import type { MihomoClient } from './client';
2
- import type { MihomoDnsResponse, MihomoRequestOptions } from './types';
1
+ import type { MihomoClient } from './client.js';
2
+ import type { MihomoDnsResponse, MihomoRequestOptions } from './types.js';
3
3
  export interface MihomoDnsModule {
4
4
  /** GET `/dns/query`:查询指定域名和记录类型,返回 DNS Rcode、问题及解析记录。 */
5
5
  query(name: string, type: string, options?: MihomoRequestOptions): Promise<MihomoDnsResponse>;
@@ -0,0 +1,5 @@
1
+ export function createDns(client) {
2
+ return {
3
+ query: (name, type, options) => client.json('GET', '/dns/query', { ...options, query: { name, type } }),
4
+ };
5
+ }
@@ -1,5 +1,5 @@
1
- import { type MihomoClient } from './client';
2
- import type { MihomoDelayOptions, MihomoProxy, MihomoRequestOptions } from './types';
1
+ import { type MihomoClient } from './client.js';
2
+ import type { MihomoDelayOptions, MihomoProxy, MihomoRequestOptions } from './types.js';
3
3
  export interface MihomoGroupsModule {
4
4
  /** GET `/group`:获取全部策略组,返回的每项字段与单个代理信息相同。 */
5
5
  list(options?: MihomoRequestOptions): Promise<MihomoProxy[]>;
@@ -0,0 +1,11 @@
1
+ import { encodePathSegment } from './client.js';
2
+ export function createGroups(client) {
3
+ return {
4
+ list: async (options) => (await client.json('GET', '/group', options)).proxies,
5
+ get: (name, options) => client.json('GET', `/group/${encodePathSegment(name)}`, options),
6
+ delay: (name, options) => client.json('GET', `/group/${encodePathSegment(name)}/delay`, {
7
+ ...options,
8
+ query: { url: options.url, timeout: options.timeout, expected: options.expected },
9
+ }),
10
+ };
11
+ }
@@ -0,0 +1,39 @@
1
+ import { type MihomoCacheModule } from './cache.js';
2
+ import { type MihomoConfigsModule } from './configs.js';
3
+ import { type MihomoConnectionsModule } from './connections.js';
4
+ import { type MihomoDebugModule } from './debug.js';
5
+ import { type MihomoDnsModule } from './dns.js';
6
+ import { type MihomoGroupsModule } from './groups.js';
7
+ import { type MihomoLogsModule } from './logs.js';
8
+ import { type MihomoMemoryModule } from './memory.js';
9
+ import { type MihomoProxiesModule } from './proxies.js';
10
+ import { type MihomoProxyProvidersModule } from './proxy-providers.js';
11
+ import { type MihomoRuleProvidersModule } from './rule-providers.js';
12
+ import { type MihomoRulesModule } from './rules.js';
13
+ import { type MihomoStorageModule } from './storage.js';
14
+ import { type MihomoTrafficModule } from './traffic.js';
15
+ import type { MihomoOptions } from './types.js';
16
+ import { type MihomoUpgradeModule } from './upgrade.js';
17
+ import { type MihomoVersionModule } from './version.js';
18
+ export interface Mihomo {
19
+ cache: MihomoCacheModule;
20
+ configs: MihomoConfigsModule;
21
+ connections: MihomoConnectionsModule;
22
+ debug: MihomoDebugModule;
23
+ dns: MihomoDnsModule;
24
+ groups: MihomoGroupsModule;
25
+ logs: MihomoLogsModule;
26
+ memory: MihomoMemoryModule;
27
+ proxies: MihomoProxiesModule;
28
+ proxyProviders: MihomoProxyProvidersModule;
29
+ ruleProviders: MihomoRuleProvidersModule;
30
+ rules: MihomoRulesModule;
31
+ storage: MihomoStorageModule;
32
+ traffic: MihomoTrafficModule;
33
+ upgrade: MihomoUpgradeModule;
34
+ version: MihomoVersionModule;
35
+ }
36
+ /** 创建按模块组织的 mihomo external-controller HTTP API 类型化客户端。 */
37
+ export declare function createMihomo(options: MihomoOptions): Mihomo;
38
+ export { MihomoClient, MihomoHttpError } from './client.js';
39
+ export type * from './types.js';
@@ -0,0 +1,40 @@
1
+ import { MihomoClient } from './client.js';
2
+ import { createCache } from './cache.js';
3
+ import { createConfigs } from './configs.js';
4
+ import { createConnections } from './connections.js';
5
+ import { createDebug } from './debug.js';
6
+ import { createDns } from './dns.js';
7
+ import { createGroups } from './groups.js';
8
+ import { createLogs } from './logs.js';
9
+ import { createMemory } from './memory.js';
10
+ import { createProxies } from './proxies.js';
11
+ import { createProxyProviders } from './proxy-providers.js';
12
+ import { createRuleProviders } from './rule-providers.js';
13
+ import { createRules } from './rules.js';
14
+ import { createStorage } from './storage.js';
15
+ import { createTraffic } from './traffic.js';
16
+ import { createUpgrade } from './upgrade.js';
17
+ import { createVersion } from './version.js';
18
+ /** 创建按模块组织的 mihomo external-controller HTTP API 类型化客户端。 */
19
+ export function createMihomo(options) {
20
+ const client = new MihomoClient(options);
21
+ return {
22
+ cache: createCache(client),
23
+ configs: createConfigs(client),
24
+ connections: createConnections(client),
25
+ debug: createDebug(client),
26
+ dns: createDns(client),
27
+ groups: createGroups(client),
28
+ logs: createLogs(client),
29
+ memory: createMemory(client),
30
+ proxies: createProxies(client),
31
+ proxyProviders: createProxyProviders(client),
32
+ ruleProviders: createRuleProviders(client),
33
+ rules: createRules(client),
34
+ storage: createStorage(client),
35
+ traffic: createTraffic(client),
36
+ upgrade: createUpgrade(client),
37
+ version: createVersion(client),
38
+ };
39
+ }
40
+ export { MihomoClient, MihomoHttpError } from './client.js';
@@ -1,5 +1,5 @@
1
- import type { MihomoClient } from './client';
2
- import type { MihomoLogLevel, MihomoRequestOptions } from './types';
1
+ import type { MihomoClient } from './client.js';
2
+ import type { MihomoLogLevel, MihomoRequestOptions } from './types.js';
3
3
  export interface MihomoLogsModule {
4
4
  /**
5
5
  * GET `/logs`:获取实时日志 HTTP 流;逐行读取 `response.body`。